步驟 2:探索資料

建構及訓練模型只是工作流程的一部分。事先瞭解資料特徵可讓您建立更優質的模型。這可能意味著提高精確度。這也意味著訓練所需的資料較少,或者運算資源較少。

載入資料集

首先,請將資料集載入 Python。

def load_imdb_sentiment_analysis_dataset(data_path, seed=123):
    """Loads the IMDb movie reviews sentiment analysis dataset.

    # Arguments
        data_path: string, path to the data directory.
        seed: int, seed for randomizer.

    # Returns
        A tuple of training and validation data.
        Number of training samples: 25000
        Number of test samples: 25000
        Number of categories: 2 (0 - negative, 1 - positive)

    # References
        Mass et al., http://www.aclweb.org/anthology/P11-1015

        Download and uncompress archive from:
        http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz
    """
    imdb_data_path = os.path.join(data_path, 'aclImdb')

    # Load the training data
    train_texts = []
    train_labels = []
    for category in ['pos', 'neg']:
        train_path = os.path.join(imdb_data_path, 'train', category)
        for fname in sorted(os.listdir(train_path)):
            if fname.endswith('.txt'):
                with open(os.path.join(train_path, fname)) as f:
                    train_texts.append(f.read())
                train_labels.append(0 if category == 'neg' else 1)

    # Load the validation data.
    test_texts = []
    test_labels = []
    for category in ['pos', 'neg']:
        test_path = os.path.join(imdb_data_path, 'test', category)
        for fname in sorted(os.listdir(test_path)):
            if fname.endswith('.txt'):
                with open(os.path.join(test_path, fname)) as f:
                    test_texts.append(f.read())
                test_labels.append(0 if category == 'neg' else 1)

    # Shuffle the training data and labels.
    random.seed(seed)
    random.shuffle(train_texts)
    random.seed(seed)
    random.shuffle(train_labels)

    return ((train_texts, np.array(train_labels)),
            (test_texts, np.array(test_labels)))

檢查資料

載入資料後,建議您對資料執行一些檢查:挑選一些樣本,並手動檢查是否符合您的期望。例如,列印幾個隨機範例,看看情緒標籤是否對應至評論的情緒。以下是我們從 IMDb 資料集隨機挑選的評論:「經過十分鐘的故事情節,故事時間足以延長兩小時。如果在中途點的時候沒有什麼重要性,

收集主要指標

驗證資料後,請收集下列重要指標,以便描述文字分類問題:

  1. 樣本數量:資料中的範例總數。

  2. 類別數量:資料中的主題或類別總數。

  3. 每個類別的樣本數量:每個類別的樣本數量 (主題/類別)。在已平衡的資料集中,所有類別的範例數量都相同;在不平衡的資料集中,每個類別的樣本數量會有所不同。

  4. 每個樣本的字詞數:單一樣本中的字詞中位數。

  5. 字詞的頻率分佈:顯示資料集中各字詞的頻率 (出現次數)。

  6. 發布樣本長度:顯示資料集中每個樣本的字詞數量。

讓我們來看看這些指標的 IMDb 評論資料集值 (請參閱圖 34 的數值頻率和樣本長度分佈圖)。

指標名稱 指標值
樣本數 25000
課程數量 2
每個類別的樣本數 12500
每個樣本的字詞數 174

表 1:IMDb 審查資料集指標

explore_data.py 包含用來計算及分析這些指標的函式。以下舉幾個範例:

import numpy as np
import matplotlib.pyplot as plt

def get_num_words_per_sample(sample_texts):
    """Returns the median number of words per sample given corpus.

    # Arguments
        sample_texts: list, sample texts.

    # Returns
        int, median number of words per sample.
    """
    num_words = [len(s.split()) for s in sample_texts]
    return np.median(num_words)

def plot_sample_length_distribution(sample_texts):
    """Plots the sample length distribution.

    # Arguments
        samples_texts: list, sample texts.
    """
    plt.hist([len(s) for s in sample_texts], 50)
    plt.xlabel('Length of a sample')
    plt.ylabel('Number of samples')
    plt.title('Sample length distribution')
    plt.show()

IMDb 字詞的頻率分佈

圖 3:IMDb 字詞的頻率分佈

IMDb 樣本長度分佈

圖 4:IMDb 樣本長度分佈