ニューラルネットワークの作成,学習,データの分類を行う. TensorFlow データセットのMNIST データセットを使用する.
ここで行うこと
説明資料: [パワーポイント]
【サイト内の関連ページ】
参考 Web ページ
TensorFlow のチュートリアルの Web ページに記載のソースコードを使用している.
このページの内容は,Google Colaboratory でも実行できる.
そのために,次の URL で,Google Colaboratory のノートブックを準備している.
次のリンクをクリックすると,Google Colaboratory のノートブックが開く. そして,Google アカウントでログインすると,Google Colaboratory のノートブック内のコードを実行することができる.Google Colaboratory のノートブックは書き換えて使うこともできる.このとき,書き換え後のものを,各自の Google ドライブ内に保存することもできる.
https://colab.research.google.com/drive/1IfArIvhh-FsvJIE9YTNO8T44Qhpi0rIJ?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
結果は,TensorFlow の Tensor である.
type は型,shape はサイズ,np.max と np.mi は最大値と最小値.
tensorflow_datasets の loadで, 「batch_size = -1」を指定して,一括読み込みを行っている.
mnist, mnist_metadata = tfds.load('mnist', with_info = True, shuffle_files=True, as_supervised=True, batch_size = -1)
x_train, y_train, x_test, y_test = mnist['train'][0], mnist['train'][1], mnist['test'][0], mnist['test'][1]
print(mnist_metadata)
print(type(x_train), x_train.shape, np.max(x_train), np.min(x_train)) print(type(x_test), x_test.shape, np.max(x_test), np.min(x_test)) print(type(y_train), y_train.shape, np.max(y_train), np.min(y_train)) print(type(y_test), y_test.shape, np.max(y_test), np.min(y_test))
MatplotLib を用いて,0 番目の画像を表示する
NUM = 0 plt.figure() plt.imshow(x_train[NUM,:,:,0], cmap='gray') plt.colorbar() plt.gca().grid(False) plt.show()
print(mnist_metadata) print(mnist_metadata.features["label"].num_classes) print(mnist_metadata.features["label"].names)
x_train, x_test は主成分分析で2次元にマッピング, y_train, y_test は色.
import pandas as pd
import seaborn as sns
sns.set()
import sklearn.decomposition
# 主成分分析
def prin(A, n):
pca = sklearn.decomposition.PCA(n_components=n)
return pca.fit_transform(A)
# 主成分分析で2つの成分を得る
def prin2(A):
return prin(A, 2)
# M の最初の2列を,b で色を付けてプロット
def scatter_plot(M, b, alpha):
a12 = pd.DataFrame( M[:,0:2], columns=['a1', 'a2'] )
a12['target'] = b
sns.scatterplot(x='a1', y='a2', hue='target', data=a12, palette=sns.color_palette("hls", np.max(b) + 1), legend="full", alpha=alpha)
# 主成分分析プロット
def pcaplot(A, b, alpha):
scatter_plot(prin2(A), b, alpha)
pcaplot(np.reshape(x_train, (x_train.shape[0], -1)), y_train, 0.1)
pcaplot(np.reshape(x_test, (x_test.shape[0], -1)), y_test, 0.1)
x_train = x_train.numpy().astype("float32") / 255.0
x_test = x_test.numpy().astype("float32") / 255.0
y_train = y_train.numpy()
y_test = y_test.numpy()
print(type(x_train), x_train.shape, np.max(x_train), np.min(x_train))
print(type(x_test), x_test.shape, np.max(x_test), np.min(x_test))
print(type(y_train), y_train.shape, np.max(y_train), np.min(y_train))
print(type(y_test), y_test.shape, np.max(y_test), np.min(y_test))
MatplotLib を用いて,複数の画像を並べて表示する.
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
plt.style.use('default')
plt.figure(figsize=(10,10))
for i in range(25):
plt.subplot(5,5,i+1)
plt.xticks([])
plt.yticks([])
plt.grid(False)
plt.imshow(x_train[i], cmap=plt.cm.binary)
plt.xlabel(class_names[y_train[i]])
plt.show()
ADAM を使う場合のプログラム例
NUM_CLASSES = 10
m = tf.keras.Sequential()
m.add(tf.keras.layers.Flatten(input_shape=(28, 28, 1)))
m.add(tf.keras.layers.Dense(units=128, activation='relu'))
m.add(tf.keras.layers.Dropout(rate=0.5))
m.add(tf.keras.layers.Dense(units=NUM_CLASSES, activation='softmax'))
m.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),,
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
SGD を使う場合のプログラム例
NUM_CLASSES = 10
m = tf.keras.Sequential()
m.add(tf.keras.layers.Flatten(input_shape=(28, 28, 1)))
m.add(tf.keras.layers.Dense(units=128, activation='relu'))
m.add(tf.keras.layers.Dropout(rate=0.5))
m.add(tf.keras.layers.Dense(units=NUM_CLASSES, activation='softmax'))
m.compile(optimizer=tf.keras.optimizers.SGD(lr=0.01, momentum=0.9, nesterov=True),
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
print(m.summary())
Keras のモデルのビジュアライズについては: https://keras.io/ja/visualization/
ここでの表示で,エラーメッセージが出る場合でも,モデル自体は問題なくできていると考えられる.続行する.
from tensorflow.keras.utils import plot_model import pydot plot_model(m)
ニューラルネットワークの学習は fit メソッドにより行う. 教師データを使用する.
EPOCHS = 50 history = m.fit(x_train, y_train, validation_data=(x_test, y_test), verbose=2, epochs=EPOCHS)
※ 訓練(学習)などで乱数が使われるので,下図と違う値になる.
predictions = m.predict( x_test ) print( predictions[0] )
テスト画像 0 番の正解を表示
print( y_test[0] )
過学習や学習不足について確認.
import pandas as pd hist = pd.DataFrame(history.history) hist['epoch'] = history.epoch print(hist)
参考Webページ: 訓練の履歴の可視化については,https://keras.io/ja/visualization/
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs = range(1, len(acc) + 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() # 図のクリア
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
plt.plot(epochs, acc, 'bo', label='Training acc')
plt.plot(epochs, val_acc, 'b', label='Validation acc')
plt.title('Training and validation accuracy')
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.legend()
plt.show()