ポルトガル語を英語に翻訳する
コース最後の演習です。ここまで来たことをお祝いします!
ここでは、翻訳に NMT モデルを使う方法を学びます。
ポルトガル語の短いフレーズをエンコードし、英語の短いフレーズにデコードするモデルはすでに事前学習済みで、model 変数に読み込まれています。
また、関数 predict_one() も読み込まれています。詳細は help() を使用してください。データセットは test(生テキスト)と X_test(トークン化済み)の各変数で利用できます。
これから、文のリストを翻訳する関数を定義します。パラメータのうち、sentences は翻訳対象のフレーズのリスト、index_to_word は英語の語彙について数値インデックスをキー、単語を値とする dict で、en_index_to_word 変数に読み込まれています。
モデルのサマリーは参考のためにすでに出力されています。
この演習はコースの一部です
Kerasで学ぶ言語モデリングのためのRecurrent Neural Networks (RNNs)
演習の手順
- フレーズの
enumerate()したイテレータをループ処理します。 - 事前に読み込まれている関数
predict_one()を使って、各フレーズを翻訳します。 - 翻訳結果を表示します。
- 定義した関数を呼び出し、
X_test変数の先頭10件を翻訳します。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
# Function to predict many phrases
def predict_many(model, sentences, index_to_word, raw_dataset):
for i, sentence in ____(sentences):
# Translate the Portuguese sentence
translation = ____(model, sentence, index_to_word)
# Get the raw Portuguese and English sentences
raw_target, raw_src = raw_dataset[i]
# Print the correct Portuguese and English sentences and the predicted
print('src=[%s], target=[%s], predicted=[%s]' % (raw_src, raw_target, ____))
____(model, X_test[____], en_index_to_word, test)