開始使用免費開始

使用 LSTM 進行文字預測

在接下來的練習中,你將建立一個簡易的 LSTM 模型,利用一個小型文字資料集來預測下一個單字。 這個資料集包含整理過的電影 The Lord of the Ring 的台詞。內容已放在變數 text 中。

你會把這段 text 轉成長度為 4sequences,並使用 Keras 的 Tokenizer 來為你的模型準備特徵與標籤!

Keras 的 Tokenizer 已經替你匯入。它會為每個不重複的單字指定一個唯一數字,並把對應關係儲存在字典中。這很重要,因為模型只能處理數字,但之後我們會想把模型輸出的數字再解碼回單字。

本練習屬於課程

Keras 深度學習入門

檢視課程

練習說明

  • 使用 .split() 把文字分割成單字陣列。
  • 以每次往後移動 1 個單字的方式,建立每句含 4 個單字的句子。
  • 建立一個 Tokenizer(),並用 .fit_on_texts() 對句子進行擬合。
  • 呼叫 .texts_to_sequences(),把 sentences 轉成數字序列。

動手互動練習

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

# Split text into an array of words 
words = ____.____

# Make sentences of 4 words each, moving one word at a time
sentences = []
for i in range(4, len(words)):
  sentences.append(' '.join(words[i-____:i]))

# Instantiate a Tokenizer, then fit it on the sentences
tokenizer = ____
tokenizer.____(____)

# Turn sentences into a sequence of numbers
sequences = tokenizer.____(____)
print("Sentences: \n {} \n Sequences: \n {}".format(sentences[:5],sequences[:5]))
編輯並執行程式碼