開始使用免費開始

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

在第 1 部分中,你實作了 compute_onehot_length() 函式,計算 one-hot 向量時沒有使用 num_classes 參數。

num_classes 參數會控制 to_categorical() 函式產生的 one-hot 編碼向量長度。當你面對兩個詞彙表不同的語料庫(也就是多個文本集合)時,若未設定 num_classes,可能會得到長度不一致的 one-hot 向量。

在本練習中,已提供 compute_onehot_length() 函式與 word2index 字典供你使用。

本練習屬於課程

使用 Keras 進行機器翻譯

檢視課程

練習說明

  • words_1 呼叫 compute_onehot_length()
  • words_2 呼叫 compute_onehot_length()
  • 印出針對 words_1words_2 所得到的 one-hot 向量長度。

動手互動練習

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

words_1 = ["I", "like", "cats", "We", "like", "dogs", "He", "hates", "rabbits"]
# Call compute_onehot_length on words_1
length_1 = ____(____, ____)

words_2 = ["I", "like", "cats", "We", "like", "dogs", "We", "like", "cats"]
# Call compute_onehot_length on words_2
length_2 = ____(____, ____)

# Print length_1 and length_2
print("length_1 =>", ____, " and length_2 => ", ____)
編輯並執行程式碼