Keras 3 API 文件 / 內建小型資料集 / IMDB 電影評論情感分類資料集

IMDB 電影評論情感分類資料集

[原始碼]

load_data 函數

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,
    **kwargs
)

載入 IMDB 資料集

這是一個來自 IMDB 的 25,000 部電影評論資料集,並依據情感(正面/負面)標記。評論已預處理,且每則評論都編碼為字詞索引(整數)列表。為了方便起見,字詞依據在資料集中的整體頻率進行索引,例如,整數「3」編碼資料中第 3 個最常見的字詞。這允許快速的過濾操作,例如:「僅考慮前 10,000 個最常見的字詞,但排除前 20 個最常見的字詞」。

按照慣例,「0」不代表特定字詞,而是用於編碼填充符記 (pad token)。

參數

  • 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:整數。詞彙外字元 (out-of-vocabulary character)。由於 num_wordsskip_top 限制而被刪除的字詞將被此字元取代。
  • index_from:整數。使用此索引及更高的索引來索引實際的字詞。

回傳

  • 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)。

注意:「詞彙外」字元僅用於訓練集中出現但在這裡因未達到 num_words 限制而不包括的字詞。未在訓練集中看到但在測試集中出現的字詞將被直接跳過。


[原始碼]

get_word_index 函數

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])