定義 Teacher Forcing 模型層
你將要定義一個升級版的機器翻譯模型,基於你先前建立的版本。你知道嗎?像 Google 翻譯這類模型就使用了 Teacher Forcing 技術來訓練模型。
如同你已經看過的,先前的模型需要稍作調整才能採用 Teacher Forcing。在本練習中,你會對先前的模型做必要的修改。我們已提供語言參數 en_len 與 fr_len(英/法句子在補齊後的長度)、en_vocab 與 fr_vocab(英/法資料集的詞彙表大小),以及 hsize(GRU 層的隱藏層大小)。請記住,解碼器會接收一個法文序列,其長度比 fr_len 少 1。也請記得以 en 作為編碼器相關物件的前綴,de 作為解碼器相關物件的前綴。
本練習屬於課程
使用 Keras 進行機器翻譯
練習說明
- 從
tensorflow.keras匯入layers子模組。 - 取得編碼器的輸出與狀態值,並分別指定給
en_out與en_state。 - 定義一個解碼器的
Input層,能接受長度為fr_len-1的 one-hot 編碼法文字詞序列。 - 定義一個
TimeDistributed的Densesoftmax 層,節點數為fr_vocab。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Import the layers submodule from keras
import ____.____.____ as layers
en_inputs = layers.Input(shape=(en_len, en_vocab))
en_gru = layers.GRU(hsize, return_state=True)
# Get the encoder output and state
____, ____ = en_gru(____)
# Define the decoder input layer
de_inputs = layers.____(shape=(____, ____))
de_gru = layers.GRU(hsize, return_sequences=True)
de_out = de_gru(de_inputs, initial_state=en_state)
# Define a TimeDistributed Dense softmax layer with fr_vocab nodes
de_dense = layers.____(____.____(____, activation=____))
de_pred = de_dense(de_out)