ニューラルネットワークの作成,学習,データの2クラス分類を行う. IMDb データセットを使用する.
ここで行うこと
参考Webページ:
このページの内容は,Google Colaboratory でも実行できる.
そのために,次の URL で,Google Colaboratory のノートブックを準備している.
次のリンクをクリックすると,Google Colaboratory のノートブックが開く. そして,Google アカウントでログインすると,Google Colaboratory のノートブック内のコードを実行することができる.Google Colaboratory のノートブックは書き換えて使うこともできる.このとき,書き換え後のものを,各自の Google ドライブ内に保存することもできる.
https://colab.research.google.com/drive/1hBMPOyUaDCTNYqOcHoQRiilznK728r_T?usp=sharing
自分で,Google Colaboratory のノートブックを新規作成する場合(上のリンクを使わない)のため,手順を説明する.
パソコンを使う場合は,下に「前準備(パソコンを使う場合)」で説明している.
https://colab.research.google.com
Google Colab はオンラインの Python 開発環境. 使用するには Google アカウントが必要
システム Python を使うことができる(その場合,Python のインストールは行わない)
システム Python を用いるときは,pip, setuptools の更新は次のコマンドで行う.
sudo apt -y update sudo apt -y install python3-pip python3-setuptools
Ubuntu で,システム Python 以外の Python をインストールしたい場合は pyenv が便利である: 別ページで説明している.
Python の URL: http://www.python.org/
【Python, pip の使い方】
Python, pip は,次のコマンドで起動できる.
【Python 開発環境のインストール】
JupyterLab, spyder, nteract (Python 開発環境) のインストールは, Windows でコマンドプロンプトを管理者として実行し, 次のコマンドを実行.
python -m pip install -U pip setuptools jupyterlab jupyter jupyter-console jupytext nteract_on_jupyter spyder
詳しくは,: 別ページで説明している.
JupyterLab, spyder, nteract (Python 開発環境) のインストール: : 別ページで説明している.
Windows での pip の実行では,コマンドプロンプトを管理者として実行することにする。
python -m pip uninstall -y tensorflow tensorflow-cpu tensorflow-gpu tensorflow_datasets tensorflow-hub keras python -m pip install -U tensorflow tensorflow_datasets numpy matplotlib seaborn scikit-learn scikit-learn-intelex
Windows でのインストール詳細(NVIDIA グラフィックスドライバ,NVIDIA CUDA ツールキット,NVIDIA cuDNN, TensorFlow 関連ソフトウエアを含む): 別ページで説明している.
端末で,次のコマンドを実行.
sudo pip3 uninstall -y tensorflow tensorflow-cpu tensorflow-gpu tensorflow_datasets tensorflow-hub keras sudo pip3 uninstall -y 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-sklearn python3-matplotlib python3-seaborn sudo pip3 install -U tensorflow tensorflow_datasets
Ubuntu でのインストール詳細(NVIDIA グラフィックスドライバ,NVIDIA CUDA ツールキット,NVIDIA cuDNN, TensorFlow 関連ソフトウエアを含む): 別ページで説明している.
from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow.compat.v2 as tf
tf.enable_v2_behavior()
from tensorflow.keras import backend as K
K.clear_session()
print(tf.__version__)
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()