建立文字生成模型
在這個練習中,你會使用 Keras 定義一個文字生成模型。
環境中已載入變數 n_vocab(字彙表大小)與 input_shape(訓練資料的形狀)。另外,預先訓練模型的權重已存於檔案 model_weights.h5。該模型在訓練資料上以 40 個 epochs 訓練完成。複習一下,在 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.____