Embedding 提升性能
嵌入层是否能提升模型的准确率?让我们用同一份 IMDB 数据来验证。
该模型已经训练了 10 个 epoch,与之前使用 simpleRNN 单元的模型一致。为便于对比,环境中提供了测试集 (X_test, y_test),以及旧模型 simpleRNN_model。旧模型的准确率已存入变量 acc_SimpleRNN。
所有所需的模块和函数均已在环境中加载完毕:来自 keras.models 的 Sequential(),来自 keras.layers 的 Embedding 和 Dense,以及来自 keras.layers 的 SimpleRNN。
本练习是课程的一部分
使用 Keras 构建语言建模的循环神经网络(RNN)
练习说明
- 将嵌入层添加到模型中。
- 计算模型的准确率并存入变量
acc_embeddings。 - 打印旧模型与新模型的准确率。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Create the model with embedding
model = Sequential(name="emb_model")
model.add(____(input_dim=max_vocabulary, output_dim=wordvec_dim, input_length=max_len))
model.add(SimpleRNN(units=128))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
# Load pre-trained weights
model.load_weights('embedding_model_weights.h5')
# Evaluate the models' performance (ignore the loss value)
_, ____ = model.evaluate(X_test, y_test, verbose=0)
# Print the results
print("SimpleRNN model's accuracy:\t{0}\nEmbeddings model's accuracy:\t{1}".format(acc_simpleRNN, ____))