Keras の前処理
Keras のもう一つの重要なモジュールが keras.preprocessing です。ここでは、生データを正しい入力形状に整えるための主要なモジュールと関数の使い方を学びます。Keras は、前のレッスンで学んだ辞書方式の代わりとなる機能を提供しています。
keras.preprocessing.text.Tokenizer モジュールを使い、メソッド .fit_on_texts() で単語の辞書を作成し、メソッド .texts_to_sequences() で各単語の辞書内インデックスを表す数値 ID の列にテキストを変換します。
その後、keras.preprocessing.sequence の関数 .pad_sequences() を使って、短いテキストはゼロで埋め、長いテキストは切り詰めることで、すべてのシーケンスが同じ長さ(モデルに必要)になるように調整します。
この演習はコースの一部です
Kerasで学ぶ言語モデリングのためのRecurrent Neural Networks (RNNs)
演習の手順
- 関連するモジュールから
Tokenizerとpad_sequencesをインポートします。 - サンプルデータ
textsに対してtokenizerオブジェクトを学習させます。 - メソッド
.texts_to_sequences()を使って、テキストを数値インデックスのシーケンスに変換します。 - パディングでテキストの長さをそろえます。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
# Import relevant classes/functions
from tensorflow.keras.preprocessing.text import ____
from tensorflow.keras.preprocessing.sequence import ____
# Build the dictionary of indexes
tokenizer = Tokenizer()
tokenizer.fit_on_texts(____)
# Change texts into sequence of indexes
texts_numeric = tokenizer.____(texts)
print("Number of words in the sample texts: ({0}, {1})".format(len(texts_numeric[0]), len(texts_numeric[1])))
# Pad the sequences
texts_pad = ____(texts_numeric, 60)
print("Now the texts have fixed length: 60. Let's see the first one: \n{0}".format(texts_pad[0]))