ニューラルネットワークの作成,学習,データの分類を行う. Iris データセットを使用する.
ここで行うこと
説明資料: [パワーポイント]
サイト内の関連ページ
参考Webページ:
このページの内容は,Google Colab でも実行できる.
そのために,次の URL で,Google Colab のノートブックを準備している.
次のリンクをクリックすると,Google Colab のノートブックが開く. そして,Google アカウントでログインすると,Google Colab のノートブック内のコードを実行することができる.Google Colab のノートブックは書き換えて使うこともできる.このとき,書き換え後のものを,各自の Google ドライブ内に保存することもできる.
https://colab.research.google.com/drive/1GCOC1SQjAuqjpB5MV3_cXQVQ3Cdrro0t?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, y に Iris データセットをロードする
次の Python プログラムを実行
import sklearn.datasets iris = sklearn.datasets.load_iris() x = iris.data y = iris.target
Iris データセットの先頭部分
x は外花被片、内花被片の幅と高さである
配列(アレイ)の形:サイズは 150 × 4.次元数は 2.
print( x.shape ) print( x.ndim ) print( x )
y は花の種類のデータである
配列(アレイ)の形:サイズは 150.次元数は 1.
print( y.shape ) print( y.ndim ) print( y )
x, y の表示
x は主成分分析で2次元にマッピング, y は色.
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(x, y, 0.4)
x_train, y_train, x_test, y_test に Iris データセットを設定する.正規化も行う.
import sklearn.model_selection
# 2次元の配列. 要素は float64, 最大値と最小値を用いて正規化
def normalizer(A):
M = np.reshape(A, (len(A), -1))
M = M.astype('float32')
max = M.max(axis=0)
min = M.min(axis=0)
return (M - min)/(max - min)
x_train, x_test, y_train, y_test = sklearn.model_selection.train_test_split(normalizer(x), y, train_size=0.5)
print(x_train)
print(y_train)
最適化器(オプティマイザ) と損失関数とメトリクスを設定する.
NUM_CLASSES = 3
m = tf.keras.Sequential([
tf.keras.layers.Dense(units=64, input_dim=len(x_train[0]), activation='relu'),
tf.keras.layers.Dropout(0.05),
tf.keras.layers.Dense(NUM_CLASSES, activation='softmax')
])
m.summary()
m.compile(
optimizer=tf.keras.optimizers.Adam(0.001),
loss='sparse_categorical_crossentropy',
metrics=['sparse_categorical_crossentropy', 'accuracy']
)
Google Colab では「!pip install git+https://github.com/lordmahyar/keras-visualizer」を実行
# Google Colab では「!pip install git+https://github.com/lordmahyar/keras-visualizer」を実行 !pip install git+https://github.com/lordmahyar/keras-visualizer
from keras_visualizer import visualizer
visualizer(m, format='png')
from IPython.display import Image,display_png
display_png(Image('graph.png'))
学習(訓練)は fit メソッドにより行う. 学習データを投入する.
EPOCHS = 300 history = m.fit(x_train, y_train, epochs=EPOCHS, validation_data=(x_test, y_test), verbose=1)
分類を行わせたいデータは、x_test である
分類させたいデータx_test は、ランダムに選ばれていたので、実行結果は下の図と違うものになる
print(m.predict(x_test))
それぞれ、3つの数値の中で、一番大きいものはどれか?
m.predict(x_test).argmax(axis=1)
y_test 内にある正解のラベル(クラス名)を表示する(上の結果と比べるため)
print(y_test)
過学習や学習不足について確認.
import pandas as pd hist = pd.DataFrame(history.history) hist['epoch'] = history.epoch print(hist)
過学習や学習不足について確認.
https://www.tensorflow.org/tutorials/keras/overfit_and_underfit?hl=ja で公開されているプログラムを使用
import matplotlib.pyplot as plt
%matplotlib inline
import warnings
warnings.filterwarnings('ignore') # Suppress Matplotlib warnings
def plot_history(histories, key='binary_crossentropy'):
plt.figure(figsize=(16,10))
for name, history in histories:
val = plt.plot(history.epoch, history.history['val_'+key],
'--', label=name.title()+' Val')
plt.plot(history.epoch, history.history[key], color=val[0].get_color(),
label=name.title()+' Train')
plt.xlabel('Epochs')
plt.ylabel(key.replace('_',' ').title())
plt.legend()
plt.xlim([0,max(history.epoch)])
plot_history([('history', history)], key='sparse_categorical_crossentropy')
plot_history([('history', history)], key='accuracy')