開始使用免費開始

產生翻譯

你現在要使用以 Teacher Forcing 訓練出的推論模型來產生法文翻譯。

此模型(nmt_tf)在 100,000 句上訓練了 50 個 epoch,在超過 35,000 筆的驗證集上達到約 98% 的準確率。由於需要載入已訓練的模型,這個練習初始化可能會花比較久的時間。你已獲得 sents2seqs() 函式。此外也提供了兩個新函式:

word2onehot(tokenizer, word, vocab_size),其參數為:

  • tokenizer - Keras 的 Tokenizer 物件
  • word - 詞彙表中的一個單字字串(例如:'apple'
  • vocab_size - 詞彙量大小

probs2word(probs, tok),其參數為:

  • probs - 來自模型的輸出,形狀為 [1,<French Vocab Size>]
  • tok - Keras 的 Tokenizer 物件

你可以在主控台輸入 print(inspect.getsource(word2onehot))print(inspect.getsource(probs2word)) 來查看這些函式的原始程式碼。

本練習屬於課程

使用 Keras 進行機器翻譯

檢視課程

練習說明

  • 使用編碼器預測初始解碼器狀態(de_s_t)。
  • 使用前一次的預測結果(輸出)與前一次的狀態作為輸入,從解碼器中預測輸出與新狀態。記得以遞迴方式產生並更新新狀態。
  • 使用 probs2word() 函式,從機率輸出取得單字字串。
  • 使用 word2onehot() 函式,將該單字字串轉換為 one-hot 序列。

動手互動練習

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

en_sent = ['the united states is sometimes chilly during december , but it is sometimes freezing in june .']
print('English: {}'.format(en_sent))
en_seq = sents2seqs('source', en_sent, onehot=True, reverse=True)
# Predict the initial decoder state with the encoder
de_s_t = ____.predict(____)
de_seq = word2onehot(fr_tok, 'sos', fr_vocab)
fr_sent = ''
for i in range(fr_len):    
  # Predict from the decoder and recursively assign the new state to de_s_t
  de_prob, ____ = ____.predict([____,____])
  # Get the word from the probability output using probs2word
  de_w = probs2word(____, fr_tok)
  # Convert the word to a onehot sequence using word2onehot
  de_seq = word2onehot(fr_tok, ____, fr_vocab)
  if de_w == 'eos': break
  fr_sent += de_w + ' '
print("French (Ours): {}".format(fr_sent))
print("French (Google Translate): les etats-unis sont parfois froids en décembre, mais parfois gelés en juin")
編輯並執行程式碼