開始使用免費開始

轉換新文本

在這個練習中,你會把一段新的文本轉換為出現在前面字典中的數值索引序列。

當你已經有一個訓練好的模型,並想把它應用到新的資料集時,這很實用。對訓練資料所做的前處理步驟也必須同樣套用到新的文本,模型才能進行預測/分類。

這裡你也會使用特殊權標 '<UKN/>' 來表示不在詞彙表中的單字。一般來說,這類特殊權標會是字典的最前面幾個索引,其中位置 0

變數 word_to_indexindex_to_wordvocabulary 已載入環境。新的文本也已載入為 new_text。我們已經將新的文本列印出來,方便你先查看。

本練習屬於課程

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

檢視課程

練習說明

  • 針對包含各句子的串列 new_text 進行迴圈。
  • 若字典中找不到該單字,請將其索引設為 0
  • 將由索引組成的句子附加到變數 new_text_split
  • 使用字典 index_to_word 將索引轉回文字。

動手互動練習

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

# Loop through the sentences and get indexes
new_text_split = []
for sentence in ____:
    sent_split = []
    for wd in sentence.split(' '):
        index = word_to_index.get(wd, ____)
        sent_split.append(index)
    new_text_split.append(____)

# Print the first sentence's indexes
print(new_text_split[0])

# Print the sentence converted using the dictionary
print(' '.join([index_to_word[____] for index in new_text_split[0]]))
編輯並執行程式碼