参数数量对比
您已经看到,one-hot 表示并不是一种好的词表示方式,因为它非常稀疏。使用 Embedding 层可以创建稠密的向量表示,但也会带来需要学习的大量参数。
在本练习中,您将比较使用 embeddings 和 one-hot 编码的两个模型的参数数量,从而直观看到差异。
环境中已加载模型 model_onehot,以及来自 keras 的 Sequential、Dense 和 GRU。最后,参数 vocabulary_size=80000 和 sentence_len=200 也已加载。
本练习是课程的一部分
使用 Keras 构建语言建模的循环神经网络(RNN)
练习说明
- 从
keras.layers导入Embedding层。 - 在嵌入层中,将词汇表大小加 1 作为输入维度,并将句子长度作为输入长度。
- 编译模型。
- 打印包含嵌入层的模型摘要。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Import the embedding layer
from tensorflow.keras.layers import ____
# Create a model with embeddings
model = Sequential(name="emb_model")
model.add(Embedding(input_dim=____, output_dim=wordvec_dim, input_length=____, trainable=True))
model.add(GRU(128))
model.add(Dense(1))
model.____(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
# Print the summaries of the one-hot model
model_onehot.summary()
# Print the summaries of the model with embeddings
model.____