教师强迫介绍

使用 Keras 的机器翻译

Thushan Ganegedara

Data Scientist and Author

之前的机器翻译模型

  • 之前的模型

编码器-解码器完整模型

  • 编码器 GRU
    • 读取英文词
    • 输出上下文向量
  • 解码器 GRU
    • 读取上下文向量
    • 输出一系列 GRU 隐状态
  • 解码器预测层
    • 读取该序列
    • 输出法语词的概率
使用 Keras 的机器翻译

类比:无教师强迫训练

无教师强迫 1

使用 Keras 的机器翻译

类比:无教师强迫训练

无教师强迫 2

使用 Keras 的机器翻译

类比:无教师强迫训练

无教师强迫 3

使用 Keras 的机器翻译

类比:使用教师强迫训练

教师强迫 1

使用 Keras 的机器翻译

类比:使用教师强迫训练

教师强迫 2

使用 Keras 的机器翻译

类比:使用教师强迫训练

教师强迫 3

使用 Keras 的机器翻译

类比:使用教师强迫训练

教师强迫 4

使用 Keras 的机器翻译

之前的机器翻译模型

  • 之前的模型

编码器-解码器完整模型

  • 教师强迫模型

带教师强迫的编码器-解码器模型

使用 Keras 的机器翻译

实现带教师强迫的模型

  • 编码器
    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 的机器翻译

输入与输出

  • 编码器输入 - 例如 Ilikedogs
  • 解码器输入 - 例如 J'aimeles
  • 解码器输出 - 例如 leschiens

教师强迫的输入与输出

使用 Keras 的机器翻译

实现带教师强迫的模型

  • 编码器
    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 的机器翻译

数据预处理

  • 编码器

    • 输入——所有英文词(独热编码)
      • en_x = sents2seqs('source', en_text, onehot=True, reverse=True)
  • 解码器

    de_xy = sents2seqs('target', fr_text, onehot=True)
    
    • 输入——除最后一个词外的所有法语词(独热编码)
      • de_x = de_xy[:,:-1,:]
    • 输出/目标——除第一个词外的所有法语词(独热编码)
      • de_y = de_xy[:,1:,:]
使用 Keras 的机器翻译

让我们练习!

使用 Keras 的机器翻译

Preparing Video For Download...