開始使用免費開始

理解 one-hot 向量

在這裡你會學到如何從單字產生 one-hot 編碼向量。One-hot 編碼是將單字轉成數值表示時常用的轉換方式。

你會使用 Keras 的 to_categorical() 函式來建立 one-hot 向量。to_categorical() 需要一個整數序列作為輸入。因此我們提供了一個 word2index 字典,可以用來把單字轉成整數。

要順利完成本練習,你也需要使用 Python 內建的 zip() 函式。zip() 可以讓你同時迭代多個序列。例如,若你有兩個長度相同的串列 xxyy,透過 for x,y in zip(xx,yy),就能逐一取得串列中的每個 xy 元素。

本練習屬於課程

使用 Keras 進行機器翻譯

檢視課程

動手互動練習

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

from tensorflow.keras.utils import to_categorical

# Create a list of words and convert them to indices
words = [____, ____, ____]
word_ids = [word2index[____] for w in ____]
print(____)
編輯並執行程式碼