參數數量比較
你已經看到 one-hot 表示法並不適合用來表示單字,因為它非常稀疏。使用 Embedding 層會產生密集的向量表示,但也需要學習大量參數。
在這個練習中,你會比較使用 embeddings 與 one-hot 編碼的兩個模型之參數數量,來看看差異。
環境中已經載入模型 model_onehot,以及來自 keras 的 Sequential、Dense 和 GRU。最後,參數 vocabulary_size=80000 與 sentence_len=200 也已載入。
本練習屬於課程
使用 Keras 建立語言模型的循環神經網路(RNN)
練習說明
- 從
keras.layers匯入Embedding層。 - 在嵌入層中,將詞彙表大小加一作為輸入維度,並將句子長度作為輸入長度。
- 編譯模型。
- 列印含有嵌入層的模型摘要。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# 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.____