為模型輸入準備文字資料
在前面,你已經學過如何建立索引到單字、以及單字到索引的字典。這個練習中,你會把文字依字元切分,並繼續為監督式學習準備資料。
把文字切成字元看起來有點特別,但在文字生成任務中很常見。而且資料準備流程相同,唯一不同的是如何切分文字。
你會建立訓練資料,包含固定長度文字片段的清單與其標籤,標籤就是對應的下一個字元。
你會繼續使用包含《宅男行不行》(The Big Bang Theory)中 Sheldon 名言的資料集,已放在變數 sheldon_quotes 中。
print_examples() 函式會印出這些配對,讓你看到資料如何被轉換。細節請使用 help() 查看。
本練習屬於課程
使用 Keras 建立語言模型的循環神經網路(RNN)
練習說明
- 將
step設為2,將chars_window設為10。 - 將下一個句子加入變數
sentences。 - 將文字
sheldon中正確的位置加入變數next_chars。 - 使用
print_examples()函式列印10個句子與其下一個字元。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Create lists to keep the sentences and the next character
sentences = [] # ~ Training data
next_chars = [] # ~ Training labels
# Define hyperparameters
step = ____ # ~ Step to take when reading the texts in characters
chars_window = ____ # ~ Number of characters to use to predict the next one
# Loop over the text: length `chars_window` per time with step equal to `step`
for i in range(0, len(sheldon_quotes) - chars_window, step):
sentences.____(sheldon_quotes[i:i + chars_window])
next_chars.append(sheldon_quotes[____])
# Print 10 pairs
print_examples(____, ____, 10)