创建文本生成模型
在本练习中,您将使用 Keras 定义一个文本生成模型。
变量 n_vocab(词表大小)和 input_shape(用于训练的数据形状)已在环境中加载。另外,预训练模型的权重保存在文件 model_weights.h5 中。该模型在训练数据上训练了 40 个 epoch。回顾一下,在 Keras 中训练模型,可在训练数据 (X, y) 上调用 .fit() 方法,并传入参数 epochs。例如:
model.fit(X_train, y_train, epochs=40)
本练习是课程的一部分
使用 Keras 构建语言建模的循环神经网络(RNN)
练习说明
- 添加一个返回序列的
LSTM层。 - 添加一个不返回序列的
LSTM层。 - 添加具有
n_vocab个单元的输出层。 - 显示模型摘要。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Instantiate the model
model = Sequential(name="LSTM model")
# Add two LSTM layers
model.add(____(64, input_shape=input_shape, dropout=0.15, recurrent_dropout=0.15, return_sequences=____, name="Input_layer"))
model.add(____(64, dropout=0.15, recurrent_dropout=0.15, return_sequences=____, name="LSTM_hidden"))
# Add the output layer
model.add(Dense(____, activation='softmax', name="Output_layer"))
# Compile and load weights
model.compile(loss='categorical_crossentropy', optimizer='adam')
model.load_weights('model_weights.h5')
# Summary
model.____