第 2 部分:尋寶遊戲
現在尋寶遊戲有個小小的變化。你忘了帶筆電,手邊只有記憶體有限的裝置。你寫的程式碼必須少於 4 行(不含註解)。因為需要盡可能精簡,所以你會使用列表推導式(list comprehension)。
列表推導式能用一行程式碼就完成走訪資料的工作。舉例來說,如果你想從一串數字中取出所有偶數,可以寫成 [n for n in range(100) if n%2==0]。如你所見,列表推導式能把 for 迴圈與 if 條件結合在同一行。
本練習屬於課程
使用 Keras 進行機器翻譯
練習說明
- 取得
treasure_map中 one-hot 編碼向量對應的文字 ID(word IDs)。 - 取得 treasure map 的批次大小(最前面的維度),並用它來建立一個 for 迴圈。
- 走訪
word_ids的第 i 列以取得第 i 個句子的單字,同時忽略等於 0 的文字 ID。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Get the word IDs from the treasure map
word_ids = np.argmax(____, axis=-1)
# Get the batch size from the treasure map
for i in range(treasure_map.shape[____]):
# Get all the words of the i-th sentence using list comprehension
words = [index2word[____] for wid in word_ids[____] if wid != ____]
print("Instruction ", i+1, ": ", ' '.join(words))