開始使用免費開始

第 1 部分:探索 `to_categorical()` 函式

你知道在真實情境中,詞彙表的大小可能會非常大(例如超過十萬)嗎?

這個練習分成兩部分,你會學到在 to_categorical() 函式中設定 num_classes 參數為什麼重要。在第 1 部分,你要實作 compute_onehot_length(),它會針對給定的單字清單產生 one-hot 向量,並計算這些向量的長度。

to_categorical() 函式已經匯入完成。

本練習屬於課程

使用 Keras 進行機器翻譯

檢視課程

練習說明

  • compute_onehot_length() 中使用 wordsword2index 來建立單字 ID。
  • 使用這些單字 ID 搭配 to_categorical() 函式建立 one-hot 向量。
  • 使用 <array>.shape 語法回傳單一 one-hot 向量的長度。
  • 使用 compute_onehot_length() 計算並印出單字清單 Hedrankmilk 的 one-hot 向量長度。

動手互動練習

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

def compute_onehot_length(words, word2index):
  # Create word IDs for words
  word_ids = [____[w] for w in ____]
  # Convert word IDs to onehot vectors
  onehot = ____(____)
  # Return the length of a single one-hot vector
  return onehot.____[1]

word2index = {"He":0, "drank": 1, "milk": 2}
# Compute and print onehot length of a list of words
print(____([____,____,____], ____))
編輯並執行程式碼