前回「キカガク(KIKAGAKU)で逆伝播を学ぶ」のつづき。
今回は「ニューラルネットワークの実装(分類)
- KIKAGAKU」を学ぶ。
Table of Contents [Disable]
実習環境
演習では、敢えて Google Colaboratory 使わずに、PyCharm の環境で Tensorflow や scikit-learn をインストールして演習を行った。
Tensorflow は「pip
での TensorFlow のインストール」 を参照してインストールした。
学習内容
Tensorflow の基礎
データセットの準備
- 入力変数と目的変数に切り分け
- Keras で計算できるデータの形式に変換
- 目標値を 0 からに変換
- 学習用データとテスト用データに分割
モデルの定義
- モデルの層の定義
- モデルの学習プロセスを定義
最適化手法の指定
目的関数の指定
評価指標の指定
モデルの学習
- 学習済みモデルの精度の確認
- モデル精度の向上
- 学習済みモデルの保存と推論
学習済みモデルの保存
- 学習済みモデルのロード
- 予測値の計算
ソースコード
学習済みモデルの保存まで
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ========================= | |
# 学習済みモデルの保存まで | |
# ========================= | |
import tensorflow as tf | |
import numpy as np | |
import pandas as pd | |
import matplotlib.pyplot as plt | |
from sklearn.model_selection import train_test_split | |
import os, random | |
from tensorflow.keras import models, layers | |
# データの読み込み | |
df = pd.read_csv('wine_class.csv') | |
# 目的変数 | |
t = df['Class'] | |
# 入力変数 | |
x = df.drop('Class', axis=1) | |
# ラベルを 0 から始める | |
t = t.values - 1 | |
x = x.values | |
# 学習データとテストデータの分割 | |
x_train, x_test, t_train, t_test = train_test_split(x, t, train_size=0.7, random_state=0) | |
# 32 bit にキャスト | |
x_train = np.array(x_train, np.float32) | |
x_test = np.array(x_train, np.float32) | |
t_train = np.array(t_train, np.int32) | |
t_test = np.array(t_train, np.int32) | |
def reset_seed(seed=0): | |
os.environ['PYTHONHASHSEED'] = '0' | |
random.seed(seed) # random関数のシードを固定 | |
np.random.seed(seed) # numpyのシードを固定 | |
tf.random.set_seed(seed) # tensorflowのシードを固定 | |
# シードの固定 | |
reset_seed(0) | |
# モデルの構築 | |
model = tf.keras.models.Sequential([ | |
tf.keras.layers.BatchNormalization(input_shape=(10,)), | |
tf.keras.layers.Dense(10, activation='relu'), | |
tf.keras.layers.Dense(3, activation='softmax') | |
]) | |
# モデルのコンパイル | |
model.compile(optimizer='sgd', | |
loss='sparse_categorical_crossentropy', | |
metrics=['accuracy']) | |
# モデルの学習 | |
history = model.fit(x_train, t_train, | |
batch_size=10, | |
epochs=50, | |
validation_data=(x_test, t_test)) | |
# 正解率と損失を Pandas の形式に変換 | |
result_batchnorm = pd.DataFrame(history.history) | |
print(result_batchnorm) | |
# 目的関数の値 | |
result_batchnorm[['loss', 'val_loss']].plot() | |
plt.show() | |
# 正解率 | |
result_batchnorm[['accuracy', 'val_accuracy']].plot() | |
plt.show() | |
# モデルの保存 | |
model.save(filepath='wine_model.h5', save_format='h5') |
保存した学習済みモデルのロードして推論
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ========================= | |
# 保存した学習済みモデルのロード | |
# ========================= | |
import tensorflow as tf | |
import numpy as np | |
import pandas as pd | |
import matplotlib.pyplot as plt | |
from sklearn.model_selection import train_test_split | |
import os, random | |
from tensorflow.keras import models, layers | |
# データの読み込み | |
df = pd.read_csv('wine_class.csv') | |
# 目的変数 | |
t = df['Class'] | |
# 入力変数 | |
x = df.drop('Class', axis=1) | |
# ラベルを 0 から始める | |
t = t.values - 1 | |
x = x.values | |
# 学習データとテストデータの分割 | |
x_train, x_test, t_train, t_test = train_test_split(x, t, train_size=0.7, random_state=0) | |
# 32 bit にキャスト | |
x_train = np.array(x_train, np.float32) | |
x_test = np.array(x_train, np.float32) | |
t_train = np.array(t_train, np.int32) | |
t_test = np.array(t_train, np.int32) | |
def reset_seed(seed=0): | |
os.environ['PYTHONHASHSEED'] = '0' | |
random.seed(seed) # random関数のシードを固定 | |
np.random.seed(seed) # numpyのシードを固定 | |
tf.random.set_seed(seed) # tensorflowのシードを固定 | |
# シードの固定 | |
reset_seed(0) | |
# モデルの読み込み | |
loaded_model = tf.keras.models.load_model('wine_model.h5') | |
# データの準備 | |
sample = x_train[0] | |
# 形を変換 | |
sample = sample.reshape(1, 10) | |
sample.shape | |
# 予測値の計算 | |
loaded_model.predict(sample) | |
# 予測値の計算 | |
y = loaded_model.predict(sample) | |
print(y) | |
# 最も値の大きなラベルを取得 | |
print(np.argmax(y)) | |
# 正解ラベル | |
print(t_train[0]) |