开始使用免费开始使用

更优的情感分类

在本练习中,您将回到第 1 章的情感分类问题。

您将为模型增加复杂度以提升准确率。您会使用一个 Embedding 层在训练集上训练词向量,并使用两个 LSTM 层来处理更长的文本。此外,您还会在输出层之前添加一个额外的 Dense 层。

这已不再是一个简单模型,训练可能需要一些时间。为此,您可以通过 keras.models.Sequential 类的 .load_weights() 方法加载其权重来使用一个预训练模型。该模型训练了 10 个 epoch,其权重保存在文件 model_weights.h5 中。

当前环境已加载以下模块:SequentialEmbeddingLSTMDropoutDense

本练习是课程的一部分

使用 Keras 构建语言建模的循环神经网络(RNN)

查看课程

练习说明

  • 添加一个 Embedding 层作为模型的第一层。
  • 添加第二个 LSTM 层,包含 64 个单元,并设置返回序列。
  • 添加一个额外的 Dense 层,包含 16 个单元。
  • 评估模型并打印训练集上的准确率。

交互式实操练习

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

# Build and compile the model
model = Sequential()
model.add(____(vocabulary_size, wordvec_dim, trainable=True, input_length=max_text_len))
model.add(____(64, return_sequences=____, dropout=0.2, recurrent_dropout=0.15))
model.add(LSTM(64, return_sequences=False, dropout=0.2, recurrent_dropout=0.15))
model.add(____(16))
model.add(Dropout(rate=0.25))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

# Load pre-trained weights
model.load_weights('model_weights.h5')

# Print the obtained loss and accuracy
print("Loss: {0}\nAccuracy: {1}".format(*model.____(X_test, y_test, verbose=0)))
编辑并运行代码