第 1 部分:文字反轉模型-Encoder
建立一個簡單的文字反轉模型,是理解 encoder-decoder 模型運作機制與彼此銜接方式的好方法。你現在要實作文字反轉模型的 encoder 部分。
encoder 的實作分成兩個練習。在本練習中,你會定義輔助函式 words2onehot()。words2onehot() 應該接收一個單字清單與字典 word2index,並將該單字清單轉換為由 one-hot 向量組成的陣列。word2index 字典已在工作環境中提供。
本練習屬於課程
使用 Keras 進行機器翻譯
練習說明
- 在
words2onehot()函式中,使用字典word2index將單字轉為 ID。 - 將單字 ID 轉換為長度為
3的 one-hot 向量(使用num_classes參數),並回傳轉換後的陣列。 - 以單字
I、like和cats呼叫words2onehot()函式,並將結果指定給onehot。 - 使用
print()與zip()函式列印單字及其對應的 one-hot 向量。zip()函式可讓你同時迭代多個清單。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
import numpy as np
def words2onehot(word_list, word2index):
# Convert words to word IDs
word_ids = [____[w] for w in ____]
# Convert word IDs to onehot vectors and return the onehot array
onehot = ____(____, num_classes=3)
return ____
words = ["I", "like", "cats"]
# Convert words to onehot vectors using words2onehot
onehot = ____(____, ____)
# Print the result as (, ) tuples
print([(w,ohe.tolist()) for ____,____ in zip(words, ____)])