始める無料で始める

翻訳の生成

ここでは、Teacher Forcing で学習した推論モデルを使ってフランス語訳を生成します。

このモデル(nmt_tf)は 100,000 文で 50 エポック学習しており、35,000 件超の検証セットでおよそ 98% の精度を達成しています。学習済みモデルを読み込む必要があるため、この演習の初期化には時間がかかる場合があります。sents2seqs() 関数が用意されています。さらに、次の 2 つの新しい関数も利用できます。

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で学ぶMachine Translation

コースを見る

演習の手順

  • エンコーダで初期デコーダ状態(de_s_t)を予測します。
  • 直前の予測(出力)と直前の状態を入力として、デコーダから出力と新しい状態を予測します。新しい状態を再帰的に生成することを忘れないでください。
  • probs2word() 関数を使って、確率出力から単語文字列を取得します。
  • word2onehot() 関数を使って、その単語文字列をワンホットシーケンスに変換します。

実践的なインタラクティブ演習

このサンプルコードを完成させて、この演習に挑戦してみましょう。

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")
コードを編集して実行