定义解码器

使用 Keras 的机器翻译

Thushan Ganegedara

Data Scientist and Author

编码器-解码器模型

  • 编码器逐个读取英文单词
  • 最终生成上下文向量
  • 解码器以该向量作为初始状态
  • 解码器逐个生成法语单词

编码器-解码器模型

使用 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 3 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 的机器翻译

Passons à la pratique !

使用 Keras 的机器翻译

Preparing Video For Download...