ニューラルネットワークの作成,学習,データの2クラス分類を行う. IMDb データセットを使用する.
【目次】
【関連する外部ページ】
Google Colaboratory のページ:
次のリンクをクリックすると,Google Colaboratory のノートブックが開く. そして,Google アカウントでログインすると,Google Colaboratory のノートブック内のコード等を編集したり再実行したりができる.編集した場合でも,他の人に影響が出たりということはない.そして,編集後のものを,各自の Google ドライブ内に保存することもできる.
https://colab.research.google.com/drive/1hBMPOyUaDCTNYqOcHoQRiilznK728r_T?usp=sharing
【サイト内の関連ページ】
【関連する外部ページ】
Python の公式ページ: https://www.python.org/
Windows での TensorFlow,Keras のインストール: 別ページ »で説明
(このページで,Build Tools for Visual Studio 2022,NVIDIA ドライバ, NVIDIA CUDA ツールキット, NVIDIA cuDNNのインストールも説明している.)
コマンドプロンプトを管理者として実行: 別ページ »で説明
python -m pip install -U tensorflow_datasets
Windows での Graphviz のインストール: 別ページ »で説明している.
コマンドプロンプトを管理者として実行: 別ページ »で説明
python -m pip install -U numpy matplotlib seaborn scikit-learn pandas pydot
【Python の利用】
Python は,次のコマンドで起動できる.
Python 開発環境(Jupyter Qt Console, Jupyter ノートブック (Jupyter Notebook), Jupyter Lab, Nteract, Spyder, PyCharm, PyScripterなど)も便利である.
Python のまとめ: 別ページ »にまとめ
これ以降の操作は,jupyter qtconsole で行う.
jupyter qtconsole
from __future__ import absolute_import, division, print_function, unicode_literals import tensorflow as tf from tensorflow.keras import backend as K K.clear_session() import numpy as np import tensorflow_datasets as tfds from tensorflow.keras.preprocessing import image %matplotlib inline import matplotlib.pyplot as plt import warnings warnings.filterwarnings('ignore') # Suppress Matplotlib warnings
x_train: 25000件のデータ,批評文
y_train: 25000件のデータ,ラベル(ラベルの値は 0 または 1)
x_test: 25000件のデータ,批評文
y_test: 25000件のデータ,ラベル(ラベルの値は 0 または 1)
IMDb での映画の批評は,批評文とスコア(10点満点)である.
IMDb の URL: https://www.imdb.com/
IMDb データセットでは,7点以上の批評は positive,4点以下の批評は negative としている.つまり,2種類ある. そして,IMDb データセットには,positive か negative の批評のみが含まれている(中間の点数である 5点,6点のものは含まれていない).そして, positive,negative の批評が同数である. 学習用として,positive,negative がそれぞれ 25000. テスト用として,positive,negative がそれぞれ 25000.
IMDb データセットのURL: https://ai.stanford.edu/%7Eamaas/data/sentiment/
imdb = tf.keras.datasets.imdb (x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=10000)
print(len(x_train)) print(len(y_train)) print(len(x_test)) print(len(y_test))
まず,単語を整数にマッピングするなどを行う.
# 単語を整数にマッピングする辞書 word_index = imdb.get_word_index() # インデックスの最初の方は予約済み word_index = {k:(v+3) for k,v in word_index.items()} word_index[""] = 0 word_index[" "] = 1 word_index[" "] = 2 # unknown word_index[" "] = 3 reverse_word_index = dict([(value, key) for (key, value) in word_index.items()]) def decode_review(text): return ' '.join([reverse_word_index.get(i, '?') for i in text])
批評文の確認
0番目の批評文とその単語数を表示.
x_train は費用文のデータセットである. x_train[0] は 0 番目の批評文である. 批評文は整数のリストになっている. それぞれの整数は,単語をコード化したものである. それぞれの整数を decode_review を使って単語に変換.
print(decode_review(x_train[0])) print(len(x_train[0]))
1番目の批評文とその単語数を表示.
print(decode_review(x_train[1])) print(len(x_train[1]))
ラベルの確認
print(y_train[0])
print(y_train[1])
パッデングを行う. 批評文のそれぞれは長さが異なるのを,同じ長さ 256 にそろえる.
詳細は https://www.tensorflow.org/tutorials/keras/text_classification?hl=ja に説明がある.
x_train = tf.keras.preprocessing.sequence.pad_sequences(x_train, value=word_index[""], padding='post', maxlen=256) x_test = tf.keras.preprocessing.sequence.pad_sequences(x_test, value=word_index[" "], padding='post', maxlen=256)
print(x_train) print(len(x_train[0]))
print(y_train) print(len(y_train))
# 入力の形式は映画レビューで使われている語彙数(10,000語) VOCAB_SIZE = 10000 m = tf.keras.Sequential([ tf.keras.layers.Embedding(VOCAB_SIZE, 16), tf.keras.layers.GlobalAveragePooling1D(), tf.keras.layers.Dense(16, activation='relu'), tf.keras.layers.Dense(1, activation=tf.nn.sigmoid) ]) m.summary() m.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.001), loss='binary_crossentropy', metrics=['accuracy'])
Keras のモデルのビジュアライズについては: https://keras.io/ja/visualization/
ここでの表示で,エラーメッセージが出る場合でも,モデル自体は問題なくできていると考えられる.続行する.
from tensorflow.keras.utils import plot_model import pydot plot_model(m)
x_train, y_train を,学習用データ (training set) と,検証用データ (validation set) に分ける
EPOCHS = 40 history = m.fit(x_train, y_train, epochs=EPOCHS, batch_size=512, validation_data=(x_test, y_test), verbose=1)
print(m.predict(x_test))
y_test 内にある正解のラベル(クラス名)を表示する(上の結果と比べるため)
print(y_test)
過学習や学習不足について確認.
import pandas as pd hist = pd.DataFrame(history.history) hist['epoch'] = history.epoch print(hist)
学習時と検証時で,大きく損失や精度が違っており,過学習が起きていることが確認できる
%matplotlib inline import matplotlib.pyplot as plt import warnings warnings.filterwarnings('ignore') # Suppress Matplotlib warnings accuracy = history.history['accuracy'] val_accuracy = history.history['val_accuracy'] loss = history.history['loss'] val_loss = history.history['val_loss'] epochs = range(1, len(accuracy) + 1) # "bo" は青いドット plt.plot(epochs, loss, 'bo', label='Training loss') # ”b" は青い実線 plt.plot(epochs, val_loss, 'b', label='Validation loss') plt.title('Training and validation loss') plt.xlabel('Epochs') plt.ylabel('Loss') plt.legend() plt.show()
# plt.clf() # 図のクリア accuracy = history.history['accuracy'] val_accuracy = history.history['val_accuracy'] plt.plot(epochs, accuracy, 'bo', label='Training acc') plt.plot(epochs, val_accuracy, 'b', label='Validation acc') plt.title('Training and validation accuracy') plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.legend() plt.show()