第 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 数据集随机挑选的评价:“10 分钟的故事延伸到两个小时里比较好的部分。当中途完全没有意义。”预期情绪(消极)与样本的标签一致。

收集关键指标

验证数据后,请收集以下有助于描述文本分类问题特征的重要指标:

  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 的样本长度分布