定义推理模型的解码器
推理模型是在真实使用场景中为用户执行翻译的模型。在本练习中,您需要实现推理模型的解码器。
推理模型的解码器与训练模型的解码器不同。我们不能把法语词喂给解码器,因为那正是我们要预测的目标。幸运的是,有一个办法:可以使用上一个时间步预测得到的法语词来喂给推理模型的解码器。因此,当您要生成翻译时,解码器需要一次生成一个词,并将上一步的输出作为下一步的输入。
在本练习中,变量 hsize(GRU 层的隐藏大小)、fr_len 和 fr_vocab 已经导入。请记住,前缀 de 用于指代解码器。
本练习是课程的一部分
使用 Keras 的机器翻译
练习说明
- 定义一个
Input层,用于接收一批独热编码的法语词序列(序列长度为 1)。 - 再定义一个
Input层,用于接收一批hsize维度的状态,您将用它把上一步的状态传给解码器。 - 获取解码器
GRU的输出和状态。 - 定义一个模型,接收法语词的
Input和上一步状态的Input,并输出最终预测以及新的GRU状态。
交互式实操练习
通过完成这段示例代码来试试这个练习。
import tensorflow.keras.layers as layers
from tensorflow.keras.models import Model
# Define an input layer that accepts a single onehot encoded word
de_inputs = layers.____(shape=(____, ____))
# Define an input to accept the t-1 state
de_state_in = layers.____(shape=(____,))
de_gru = layers.GRU(hsize, return_state=True)
# Get the output and state from the GRU layer
de_out, de_state_out = ____(de_inputs, initial_state=____)
de_dense = layers.Dense(fr_vocab, activation='softmax')
de_pred = de_dense(de_out)
# Define a model
decoder = Model(inputs=[____, ____], outputs=[____, ____])
print(decoder.summary())