開始使用免費開始

Keras 前處理

Keras 的第二個重要模組是 keras.preprocessing。你將學習如何使用其中最重要的模組與函式,把原始資料整理成正確的輸入形狀。Keras 提供的功能可以取代你先前學到的字典做法。

你會使用模組 keras.preprocessing.text.Tokenizer,透過 .fit_on_texts() 建立文字詞典,並用 .texts_to_sequences() 將文字轉成數值 id,也就是各詞在詞典中的索引。

接著,從 keras.preprocessing.sequence 使用函式 .pad_sequences(),讓所有序列都有相同長度(模型所需):對較短的文字在結尾補 0,對較長的文字則截斷。

本練習屬於課程

使用 Keras 建立語言模型的循環神經網路(RNN)

檢視課程

練習說明

  • 從相關模組匯入 Tokenizerpad_sequences
  • 在範例資料 texts 上擬合 tokenizer 物件。
  • 使用 .texts_to_sequences() 將文字轉為數值索引序列。
  • 透過 padding 固定文字序列的長度。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Import relevant classes/functions
from tensorflow.keras.preprocessing.text import ____
from tensorflow.keras.preprocessing.sequence import ____

# Build the dictionary of indexes
tokenizer = Tokenizer()
tokenizer.fit_on_texts(____)

# Change texts into sequence of indexes
texts_numeric = tokenizer.____(texts)
print("Number of words in the sample texts: ({0}, {1})".format(len(texts_numeric[0]), len(texts_numeric[1])))

# Pad the sequences
texts_pad = ____(texts_numeric, 60)
print("Now the texts have fixed length: 60. Let's see the first one: \n{0}".format(texts_pad[0]))
編輯並執行程式碼