定義解碼器

使用 Keras 進行機器翻譯

Thushan Ganegedara

Data Scientist and Author

編碼器—解碼器模型

  • 編碼器逐一讀入英文單字
  • 最後產生情境向量(context vector)
  • 解碼器以情境向量作為初始狀態
  • 解碼器逐一產生法文單字

編碼器—解碼器模型

使用 Keras 進行機器翻譯

解碼器的輸入

  • 解碼器以 Keras 的 GRU 層實作
  • GRU 模型需要兩個輸入
    • 時間序列輸入(???)
    • 隱藏狀態

編碼器—解碼器模型

使用 Keras 進行機器翻譯

解碼器的輸入

將編碼器的情境向量重複 N 次

  • 若要生成 10 個字的法文句子,就重複情境向量 10 次。

重複向量的編碼器—解碼器模型

使用 Keras 進行機器翻譯

理解 RepeatVector 層

RepeatVector 層:

  • 接受一個參數,用來指定輸出序列長度
  • 輸入形狀為(batch_size, input size)(例如大小為 2 x 3)
  • 輸出形狀為(batch_size, sequence length, input size)(例如大小為 2 x 5 x 3)

RepeatVector 功能示意

使用 Keras 進行機器翻譯

定義 RepeatVector 層

from tensorflow.keras.layers import RepeatVector
rep = RepeatVector(5)
r_inp = Input(shape=(3,))
r_out = rep(r_inp)
repeat_model = Model(inputs=r_inp, outputs=r_out)
  • 注意以下兩種寫法等價
rep = RepeatVector(5)
r_out = rep(r_inp)
r_out = RepeatVector(5)(r_inp)
使用 Keras 進行機器翻譯

用模型預測

使用模型進行預測

x = np.array([[0,1,2],[3,4,5]])
y = repeat_model.predict(x)
print('x.shape = ',x.shape,'\ny.shape = ',y.shape)
x.shape =  (2, 3) 
y.shape =  (2, 5, 3)
使用 Keras 進行機器翻譯

實作解碼器

定義解碼器

de_inputs = RepeatVector(fr_len)(en_state)
decoder_gru = GRU(hsize, return_sequences=True)

設定解碼器的初始狀態

gru_outputs = decoder_gru(de_inputs, initial_state=en_state)
使用 Keras 進行機器翻譯

定義模型

enc_dec = Model(inputs=en_inputs, outputs=gru_outputs)
使用 Keras 進行機器翻譯

一起來練習吧!

使用 Keras 進行機器翻譯

Preparing Video For Download...