你的第一個 RNN 模型
在這個練習中,你會動手使用 Keras 模組,建立你的第一個 RNN 模型,並用它來對電影評論進行情感分類。
這個入門模型包含一個使用基本 RNN 元件的循環層:SimpleRNN,以及一個輸出層,有兩種可能的輸出值:0 代表負向情感,1 代表正向情感。
你會使用 keras.datasets 中的 IMDB 資料集。一個模型已經訓練完成,且其權重已儲存於 model_weights.h5 檔案。你將建立模型的架構,並使用預先載入的變數 x_test 與 y_test 來檢查其效能。
本練習屬於課程
使用 Keras 建立語言模型的循環神經網路(RNN)
練習說明
- 加入具有
128個單元的SimpleRNN元件。 - 加入 1 個單元的
Dense層作為情感分類輸出。 - 使用適合二元分類的損失函式。
- 在預先訓練的驗證集上評估模型效能:(
x_test,y_test)。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Build model
model = Sequential()
model.add(____(units=____, input_shape=(None, 1)))
model.add(Dense(____, activation='sigmoid'))
model.compile(loss='____',
optimizer='adam',
metrics=['accuracy'])
# Load pre-trained weights
model.load_weights('model_weights.h5')
# Method '.evaluate()' shows the loss and accuracy
loss, acc = model.evaluate(____, ____, verbose=0)
print("Loss: {0} \nAccuracy: {1}".format(loss, acc))