開始使用免費開始

準備輸出文字

在這個練習中,你會準備要用在翻譯模型上的輸出文字。除了把文字轉換成索引序列之外,你還需要對每個索引做 one-hot 編碼。

英文文字已載入到變數 en_sentences,已擬合的 tokenizer 在變數 output_tokenizer,英文詞彙表大小在 en_vocab_size

另外,已經為輸出語言的前置轉換步驟(將文字轉成索引序列)建立好函式。這個函式已載入環境為 transform_text_to_sequences(),有兩個參數:sentences(預期為英文句子的清單)與 tokenizer(預期為從 keras.preprocessing.text 模組擬合好的 Tokenizer 物件)。

numpy 已以 np 名稱載入。

本練習屬於課程

使用 Keras 建立語言模型的循環神經網路(RNN)

檢視課程

練習說明

  • 將變數 en_sentencesoutput_tokenizer 傳入 transform_text_to_sequences() 函式,初始化變數 Y
  • 使用 to_categorical() 對句子做 one-hot 編碼。類別數請使用變數 en_vocab_size
  • 將暫存清單轉為 numpy 陣列,並重塑為 (num_sentences, sentences_len, en_vocab_size) 的形狀。
  • 列印原始文字與轉換後的結果。

動手互動練習

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

# Initialize the variable
Y = transform_text_to_sequences(____, ____)

# Temporary list
ylist = list()
for sequence in Y:
  	# One-hot encode sentence and append to list
    ylist.append(____(sequence, num_classes=____))

# Update the variable
Y = np.array(ylist).reshape(____, Y.shape[1], en_vocab_size)

# Print the raw sentence and its transformed version
print("Raw sentence: {0}\nTransformed: {1}".format(____, Y[0]))
編輯並執行程式碼