开始使用免费开始使用

定义解码器

在本练习中,您将实现解码器,并定义一个从编码器输入到解码器 GRU 输出的端到端模型。解码器与编码器使用相同的模型结构,但输入和传入的状态与编码器不同。例如,解码器既将编码器产生的上下文向量作为输入,也将其作为解码器的初始状态。请记住,我们用前缀 en(如 en_gru)表示与编码器相关的对象,用 de 表示与解码器相关的对象(如 de_gru)。

要实现解码器,您将使用 RepeatVectorGRU 层。

本练习已为您提供编码器模型以及您之前已经实现的各个编码器层。例如,编码器输入以 en_inputs 提供,上下文向量以 en_state 提供。另请注意,GRUModel 对象已经导入。

本练习是课程的一部分

使用 Keras 的机器翻译

查看课程

练习说明

  • 定义一个 RepeatVector 层,以 en_state 为输入,并将其重复 fr_len 次。
  • 定义一个 GRU 层 decoder_gru,其隐藏单元数等于 hsize,并返回所有时间步产生的输出。
  • de_inputs 作为输入、将 en_state 作为解码器的初始状态,获取 decoder_gru 层的输出。
  • 定义一个模型,以 en_inputs 作为输入、以 gru_outputs 作为输出。

交互式实操练习

通过完成这段示例代码来试试这个练习。

from tensorflow.keras.layers import RepeatVector

hsize = 48
fr_len = 20
# Define a RepeatVector layer
de_inputs = ____(____)(____)
# Define a GRU model that returns all outputs
decoder_gru = ____(____, ____=____)
# Get the outputs of the decoder
gru_outputs = ____(____, initial_state=____)
# Define a model with the correct inputs and outputs
enc_dec = ____(inputs=____, outputs=____)
enc_dec.summary()
编辑并运行代码