ニューラルネットワークの作成,学習,データの2クラス分類を行う. IMDB データセットを使用する.
ここで行うこと
参考Webページ:
このページの内容は,Google Colab でも実行できる.
そのために,次の URL で,Google Colab のノートブックを準備している.
次のリンクをクリックすると,Google Colab のノートブックが開く. そして,Google アカウントでログインすると,Google Colab のノートブック内のコードを実行することができる.Google Colab のノートブックは書き換えて使うこともできる.このとき,書き換え後のものを,各自の Google ドライブ内に保存することもできる.
https://colab.research.google.com/drive/1hBMPOyUaDCTNYqOcHoQRiilznK728r_T?usp=sharing
Google Colab を使うか,パソコンを使う.それぞれの場合の前準備を説明する.
https://colab.research.google.com
Google Colab はオンラインの Python 開発環境. 使用するには Google アカウントが必要
TensorFlow を使う場合は,必要となる NVIDIA CUDA ツールキット,NVIDIA cuDNN のバージョン確認
TensorFlow は,そのバージョンによって,必要となるNVIDIA CUDA ツールキット,NVIDIA cuDNN のバージョンが違う(最新の NVIDIA CUDA ツールキット,NVIDIA cuDNN で動くというわけでない). そのことは,https://www.tensorflow.org/install/gpu で確認できる.
そこで, まずは,使用したい TensorFlow のバージョンを確認し,それにより, NVIDIA CUDA ツールキット,NVIDIA cuDNN を確認する.
NVIDIA CUDA ツールキットのバージョン:
指定されているバージョンより高いものは使わない. その根拠は次のページ. URL: https://www.tensorflow.org/install/source#common_installation_problems
NVIDIA cuDNN のバージョン:
その根拠は次のページ. URL: https://www.tensorflow.org/install/source#common_installation_problems
GPU とは,グラフィックス・プロセッシング・ユニットの略で、コンピュータグラフィックス関連の機能,乗算や加算の並列処理の機能などがある.
NVIDIA CUDA は,NVIDIA社が提供している GPU 用のプラットフォームである.
インストール手順の説明
関連 Web ページ
インストール手順の説明
端末で,次のコマンドを実行.
sudo apt -y install python3-dev python3-pip python3-setuptools python3-venv sudo pip3 uninstall ptyprocess sniffio terminado tornado jupyterlab jupyter jupyter-console jupytext nteract_on_jupyter spyder sudo apt -y install jupyter jupyter-qtconsole spyder3 sudo apt -y install python3-ptyprocess python3-sniffio python3-terminado python3-tornado sudo pip3 install -U jupyterlab nteract_on_jupyter sudo pip3 uninstall -y tensorflow tensorflow-cpu tensorflow-gpu tensorflow_datasets tensorflow-hub keras sudo pip3 uninstall six wheel astunparse tensorflow-estimator numpy keras-preprocessing absl-py wrapt gast flatbuffers grpcio opt-einsum protobuf termcolor typing-extensions google-pasta h5py tensorboard-plugin-wit markdown werkzeug requests-oauthlib rsa cachetools google-auth google-auth-oauthlib tensorboard tensorflow sudo apt -y install python3-six python3-wheel python3-numpy python3-grpcio python3-protobuf python3-termcolor python3-typing-extensions python3-h5py python3-markdown python3-werkzeug python3-requests-oauthlib python3-rsa python3-cachetools python3-google-auth sudo apt -y install python3-numpy python3-pil python3-pydot python3-matplotlib python3-keras python3-keras-applications python3-keras-preprocessing sudo pip3 install -U tensorflow tf-models-official tensorflow_datasets tensorflow-hub keras keras-tuner keras-visualizer opencv-python sudo pip3 install git+https://github.com/tensorflow/docs sudo pip3 install git+https://github.com/tensorflow/examples.git
詳細は: 別ページで説明している.
Ubuntu では,システムの Python を使うことができる(その場合,Python のインストールは行わない)
Python プログラムを動かすために, pythonやpython3などのコマンドを使う. あるいは, 開発環境や Python コンソール(Jupyter Qt Console,spyder,PyCharm,PyScripter など)の利用も便利である.
from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow.compat.v2 as tf
import tensorflow_datasets as tfds
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import warnings
warnings.filterwarnings('ignore') # Suppress Matplotlib warnings
tf.enable_v2_behavior()
from tensorflow.keras import backend as K
K.clear_session()
print(tf.__version__)
変数 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=tf.nn.relu),
tf.keras.layers.Dense(1, activation=tf.nn.sigmoid)
])
m.summary()
m.compile(optimizer='adam',
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)
訓練時とテスト時で,大きく損失や精度が違っており,過学習が起きていることが確認できる
import matplotlib.pyplot as plt
%matplotlib inline
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()