建立句子與下一個字元的向量
本練習要更強調資料前處理的重要性。你會把《宅男行不行》(The Big Bang Theory)中角色 Sheldon 的台詞做為輸入,並在建立文字產生模型之前,先建立句子索引與下一個字元所需的向量。
文字內容已放在變數 sheldon 中,字彙(字元)在變數 vocabulary,超參數 chars_window 與 step 分別設定為 20 與 3。也就是說,會用長度為 20 的字元序列來預測下一個字元,且視窗在每次迭代會移動 3 個字元。
此外,已在環境中載入套件 pandas 並以 pd 命名。
本練習屬於課程
使用 Keras 建立語言模型的循環神經網路(RNN)
練習說明
- 以換行符號分割文字,方便逐行(句)迴圈處理。
- 迴圈執行到句子長度減去
chars_window為止。 - 將具有
chars_window個字元的句子片段附加到變數sentences,並將其下一個字元附加到變數next_chars。 - 使用得到的向量建立
pd.DataFrame(),並印出前幾列。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Instantiate the vectors
sentences = []
next_chars = []
# Loop for every sentence
for sentence in sheldon.____:
# Get 20 previous chars and next char; then shift by step
for i in range(0, len(sentence) - ____, step):
sentences.append(sentence[i:i + ____])
next_chars.append(sentence[____ + chars_window])
# Define a Data Frame with the vectors
df = pd.DataFrame({'sentence': ____, 'next_char': ____})
# Print the initial rows
print(df.head())