文のパディング
これから sents2seqs() という関数を実装します。後でこの関数を使って、ニューラル機械翻訳(NMT)モデルが受け付ける形式へデータを手軽に変換します。sents2seqs() は文文字列のリストを受け取り、
- 文をIDのシーケンスのリストに変換し、
- 文の長さがそろうようにパディングし、
- 必要に応じてIDをone-hotベクトルに変換します。
すでに学習済みの Tokenizer である en_tok が用意されています。もう1点、sents2seqs() を実装するときに未使用の引数 input_type があることに注意してください。後でこの input_type は、シーケンス長や語彙サイズなど、言語に依存するパラメータを切り替えるために使います。
この演習はコースの一部です
Kerasで学ぶMachine Translation
演習の手順
en_tokTokenizer を使ってsentencesをシーケンスに変換します。- シーケンスを固定長
en_lenにパディングし、パディングの種類はpad_typeを使用し、切り詰めはpostにします。 to_categorical()関数を使って、preproc_textの単語IDを長さen_vocabのone-hotベクトルに変換します。sents2seqs()メソッドを用いて、sentenceをpreパディングでパディング済みシーケンスに変換します。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.utils import to_categorical
def sents2seqs(input_type, sentences, onehot=False, pad_type='post'):
# Convert sentences to sequences
encoded_text = ____.____(sentences)
# Pad sentences to en_len
preproc_text = ____(____, padding=____, truncating=____, maxlen=____)
if onehot:
# Convert the word IDs to onehot vectors
preproc_text = ____(____, num_classes=____)
return preproc_text
sentence = 'she likes grapefruit , peaches , and lemons .'
# Convert a sentence to sequence by pre-padding the sentence
pad_seq = sents2seqs('source', [____], pad_type=____)