Teacher Forcing 入門

使用 Keras 進行機器翻譯

Thushan Ganegedara

Data Scientist and Author

先前的機器翻譯模型

  • 前一個模型

Encoder Decoder full model

  • 編碼器 GRU
    • 讀取英文單字
    • 輸出脈絡向量
  • 解碼器 GRU
    • 讀取脈絡向量
    • 輸出一串 GRU 結果
  • 解碼器預測層
    • 讀取 GRU 輸出序列
    • 輸出法文字的機率
使用 Keras 進行機器翻譯

類比:沒有 Teacher Forcing 的訓練

No teacher forcing 1

使用 Keras 進行機器翻譯

類比:沒有 Teacher Forcing 的訓練

No teacher forcing 2

使用 Keras 進行機器翻譯

類比:沒有 Teacher Forcing 的訓練

No teacher forcing 3

使用 Keras 進行機器翻譯

類比:使用 Teacher Forcing 的訓練

Teacher forcing 1

使用 Keras 進行機器翻譯

類比:使用 Teacher Forcing 的訓練

Teacher forcing 2

使用 Keras 進行機器翻譯

類比:使用 Teacher Forcing 的訓練

Teacher forcing 3

使用 Keras 進行機器翻譯

類比:使用 Teacher Forcing 的訓練

Teacher forcing 4

使用 Keras 進行機器翻譯

先前的機器翻譯模型

  • 前一個模型

Encoder decoder full model

  • 加入 Teacher Forcing 的模型

Encoder decoder model with teacher forcing

使用 Keras 進行機器翻譯

實作含 Teacher Forcing 的模型

  • 編碼器
    en_inputs = layers.Input(shape=(en_len, en_vocab))
    en_gru = layers.GRU(hsize, return_state=True)
    en_out, en_state = en_gru(en_inputs)
    
  • 解碼器 GRU
    de_inputs = layers.Input(shape=(fr_len-1, fr_vocab))
    de_gru = layers.GRU(hsize, return_sequences=True)
    de_out = de_gru(de_inputs, initial_state=en_state)
    
使用 Keras 進行機器翻譯

輸入與輸出

  • 編碼器輸入-如 I、like、dogs
  • 解碼器輸入-如 J'aime、les
  • 解碼器輸出-如 les、chiens

Teacher forcing inputs and outputs

使用 Keras 進行機器翻譯

實作含 Teacher Forcing 的模型

  • 編碼器
    en_inputs = layers.Input(shape=(en_len, en_vocab))
    en_gru = layers.GRU(hsize, return_state=True)
    en_out, en_state = en_gru(en_inputs)
    
  • 解碼器 GRU
    de_inputs = layers.Input(shape=(fr_len-1, fr_vocab))
    de_gru = layers.GRU(hsize, return_sequences=True)
    de_out = de_gru(de_inputs, initial_state=en_state)
    
  • 解碼器預測
    de_dense = layers.TimeDistributed(layers.Dense(fr_vocab, activation='softmax'))
    de_pred = de_dense(de_out)
    
使用 Keras 進行機器翻譯

編譯模型

nmt_tf = Model(inputs=[en_inputs, de_inputs], outputs=de_pred)
nmt_tf.compile(optimizer='adam', loss="categorical_crossentropy", metrics=["acc"])
使用 Keras 進行機器翻譯

資料前處理

  • 編碼器

    • 輸入-所有英文單字(onehot 編碼)
      • en_x = sents2seqs('source', en_text, onehot=True, reverse=True)
  • 解碼器

    de_xy = sents2seqs('target', fr_text, onehot=True)
    
    • 輸入-除了最後一個詞的所有法文字(onehot 編碼)
      • de_x = de_xy[:,:-1,:]
    • 輸出/標的-除了第一個詞的所有法文字(onehot 編碼)
      • de_y = de_xy[:,1:,:]
使用 Keras 進行機器翻譯

一起來練習吧!

使用 Keras 進行機器翻譯

Preparing Video For Download...