開始使用免費開始

定義推論模型的解碼器

推論模型是實際上線供使用者需要時執行翻譯的模型。在這個練習中,你需要實作推論模型的解碼器。

推論模型的解碼器與訓練模型的解碼器不同。我們不能把法文字詞餵給解碼器,因為那正是我們想要預測的。所幸有個解法:我們可以將前一個時間步所預測出的法文字詞,拿來餵給推論模型的解碼器。因此,當你要產生一段翻譯時,解碼器需要一次產生一個字,並把前一次的輸出當作輸入來使用。

在這個練習中,變數 hsizeGRU 層的隱藏層大小)、fr_lenfr_vocab 已經匯入。請記得,前綴 de 用來指涉解碼器。

本練習屬於課程

使用 Keras 進行機器翻譯

檢視課程

練習說明

  • 定義一個 Input 層,能接受一批 onehot 編碼的法文字詞序列(序列長度為 1)。
  • 再定義一個 Input 層,能接受一批 hsize 的狀態,你會用它把前一個狀態餵給解碼器。
  • 取得解碼器 GRU 的輸出與狀態。
  • 定義一個模型,接受法文字詞的 Input 與前一個狀態的 Input,並輸出最終的預測與新的 GRU 狀態。

動手互動練習

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

import tensorflow.keras.layers as layers
from tensorflow.keras.models import Model
# Define an input layer that accepts a single onehot encoded word
de_inputs = layers.____(shape=(____, ____))
# Define an input to accept the t-1 state
de_state_in = layers.____(shape=(____,))
de_gru = layers.GRU(hsize, return_state=True)
# Get the output and state from the GRU layer
de_out, de_state_out = ____(de_inputs, initial_state=____)
de_dense = layers.Dense(fr_vocab, activation='softmax')
de_pred = de_dense(de_out)

# Define a model
decoder = Model(inputs=[____, ____], outputs=[____, ____])
print(decoder.summary())
編輯並執行程式碼