開始使用免費開始

訓練以詞嵌入為基礎的模型

在這裡你會學到如何實作使用詞嵌入向量(embedding)的機器翻譯模型之訓練流程。與先前練習使用 one-hot 編碼向量不同,這裡一個單字以單一數字來表示。你會在完整資料集上以批次方式進行多個 epoch 的訓練。

本練習提供以句子清單形式的訓練資料(tr_entr_fr)。為了避免訓練時間過長,你只會使用實際資料中的一小部分樣本(1,000 句)。你也有在前一個練習中實作的 sents2seqs() 函式與模型 nmt_emb。請記得,我們用 en_x 表示編碼器輸入,用 de_x 表示解碼器輸入。

本練習屬於課程

使用 Keras 進行機器翻譯

檢視課程

練習說明

  • 使用 sents2seqs() 函式,取得未做 onehot 編碼的法文句子單一批次資料。
  • de_xy 取出除了「最後一個」以外的所有單字。
  • de_xy_oh(採 onehot 編碼的法文字)取出除了「第一個」以外的所有單字。
  • 使用這一個批次的資料來訓練模型

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

for ei in range(3):
  for i in range(0, train_size, bsize):    
    en_x = sents2seqs('source', tr_en[i:i+bsize], onehot=False, reverse=True)
    # Get a single batch of French sentences with no onehot encoding
    de_xy = ____('target', ____[i:i+bsize], ____=____)
    # Get all words except the last word in that batch
    de_x = de_xy[:,____]
    de_xy_oh = sents2seqs('target', tr_fr[i:i+bsize], onehot=True)
    # Get all words except the first from de_xy_oh
    de_y = de_xy_oh[____,____,____]
    # Training the model on a single batch of data
    nmt_emb.train_on_batch([____,____], ____)    
    res = nmt_emb.evaluate([en_x, de_x], de_y, batch_size=bsize, verbose=0)
    print("{} => Loss:{}, Train Acc: {}".format(ei+1,res[0], res[1]*100.0))
編輯並執行程式碼