使用驗證來訓練模型
在這裡你會使用 Teacher Forcing 來訓練模型,並執行驗證步驟。你將以多個 epoch 與多次迭代來訓練模型,並在每個 epoch 結束時執行驗證並取得結果。
為此,已提供 en_text(英文句子)、fr_text(法文句子)、sents2seqs() 函式,以及已編譯好的模型 nmt_tf。你也已經載入了 tr_en 與 tr_fr(訓練資料),以及 v_en 和 v_fr(驗證資料)。
本練習屬於課程
使用 Keras 進行機器翻譯
練習說明
- 從
de_xy萃取 decoder 輸入(除了最後一個以外的所有詞)與輸出(除了第一個以外的所有詞)。 - 在單一批次資料上訓練模型。
- 以與訓練資料相同的方式,從驗證資料建立 decoder 輸入與輸出。
- 在驗證資料集上評估模型,取得驗證損失與準確率。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
for ei in range(n_epochs):
for i in range(0,train_size,bsize):
en_x = sents2seqs('source', tr_en[i:i+bsize], onehot=True, reverse=True)
de_xy = sents2seqs('target', tr_fr[i:i+bsize], onehot=True)
# Create a single batch of decoder inputs and outputs
de_x, de_y = ____[:,____,:], de_xy[:,____,:]
# Train the model on a single batch of data
nmt_tf.____([____,____], de_y)
v_en_x = sents2seqs('source', v_en, onehot=True, reverse=True)
# Create a single batch of validation decoder inputs and outputs
v_de_xy = ____('target', ____, onehot=____)
v_de_x, v_de_y = ____[____], v_de_xy[____]
# Evaluate the trained model on the validation data
res = nmt_tf.evaluate([____,____], ____, batch_size=valid_size, verbose=0)
print("{} => Loss:{}, Val Acc: {}".format(ei+1,res[0], res[1]*100.0))