Keras 2 API 文档 / 内置小型数据集 / IMDB 电影评论情感分类数据集

IMDB 电影评论情感分类数据集

[源代码]

load_data 函数

tf_keras.datasets.imdb.load_data(
    path="imdb.npz",
    num_words=None,
    skip_top=0,
    maxlen=None,
    seed=113,
    start_char=1,
    oov_char=2,
    index_from=3,
    cache_dir=None,
    **kwargs
)

加载 IMDB 数据集

这是一个包含 25,000 条 IMDB 电影评论的数据集,已按情感(正面/负面)标记。评论已经过预处理,每条评论都编码为词索引列表(整数)。为了方便起见,单词按其在数据集中的总体频率进行索引,例如,整数“3”编码了数据中出现频率第三高的单词。这使得可以进行快速过滤操作,例如:“仅考虑出现频率最高的前 10,000 个单词,但排除出现频率最高的前 20 个单词”。

作为约定,“0”不代表任何特定单词,而是用于编码填充(pad)标记。

参数

  • path:数据缓存位置(相对于 ~/.keras/dataset)。
  • num_words:整数或 None。单词按出现频率(在训练集中)排序,并且只保留 num_words 个最常见的单词。任何不常见的单词将在序列数据中显示为 oov_char 值。如果为 None,则保留所有单词。默认为 None
  • skip_top:跳过出现频率最高的 N 个单词(这些单词可能没有信息量)。这些单词将在此数据集中显示为 oov_char 值。当值为 0 时,不跳过任何单词。默认为 0
  • maxlen:整数或 None。最大序列长度。任何更长的序列都将被截断。None 表示不截断。默认为 None
  • seed:整数。用于可重现数据混洗的种子。
  • start_char:整数。序列的开头将用此字符标记。0 通常是填充字符。默认为 1
  • oov_char:整数。词汇表外字符。因 num_wordsskip_top 限制而被切除的词语将替换为此字符。
  • index_from:整数。实际词语从此索引及更高索引开始。
  • cache_dir: 用于在本地缓存数据集的目录。如果为None,则默认为~/.keras/datasets
  • **kwargs:用于向后兼容。

返回

  • Numpy 数组元组(x_train, y_train), (x_test, y_test)

x_train, x_test:序列列表,其中每个序列是索引(整数)列表。如果指定了 num_words 参数,则最大可能索引值为 num_words - 1。如果指定了 maxlen 参数,则最大可能序列长度为 maxlen

y_train, y_test:整数标签列表(1 或 0)。

引发

  • ValueError:当 maxlen 设置得非常低,以至于无法保留任何输入序列时引发。

请注意,“词汇外”(out of vocabulary)字符仅用于在训练集中出现但在 num_words 限制之外而被排除的单词。在测试集中出现但未在训练集中看到的单词则被简单地跳过了。


[源代码]

get_word_index 函数

tf_keras.datasets.imdb.get_word_index(path="imdb_word_index.json")

检索一个将单词映射到其在 IMDB 数据集中索引的字典。

参数

  • path:数据缓存位置(相对于 ~/.keras/dataset)。

返回

词语索引字典。键是词语字符串,值是其索引。

示例

# Use the default parameters to keras.datasets.imdb.load_data
start_char = 1
oov_char = 2
index_from = 3
# Retrieve the training sequences.
(x_train, _), _ = keras.datasets.imdb.load_data(
    start_char=start_char, oov_char=oov_char, index_from=index_from
)
# Retrieve the word index file mapping words to indices
word_index = keras.datasets.imdb.get_word_index()
# Reverse the word index to obtain a dict mapping indices to words
# And add `index_from` to indices to sync with `x_train`
inverted_word_index = dict(
    (i + index_from, word) for (word, i) in word_index.items()
)
# Update `inverted_word_index` to include `start_char` and `oov_char`
inverted_word_index[start_char] = "[START]"
inverted_word_index[oov_char] = "[OOV]"
# Decode the first sequence in the dataset
decoded_sequence = " ".join(inverted_word_index[i] for i in x_train[0])