はじめに
初学者向けの分類(手書き数字)を行う機械学習プログラムです
動作確認環境
・Google Colabratory (2026.9.30時点)
1. 準備
Google Coabratory を立ち上げてドライブのマウント
※この作業は 自分の Google Drive に接続して,プログラム等のデータをそこに保存しておいたり,既に保存してあるデータを使う場合に必要です(そうでない場合は必要ありません)
ドライブのマウント
from google.colab import drive
drive.mount('/content/drive')
下記は自分の Google Drive の保存場所へ移動するプログラム(例)です.「プログラム練習」の部分は自分の環境にあわせて修正して下さい.
保存場所の確認・移動
%cd /content/drive/MyDrive/プログラム練習/
計算リソースの選択
上部タブの「ランタイム」から「ランタイムの変更」を選択すると「ハードウェアアクセラレータ」を変更することができます.CPUが最も計算速度が遅いため,他のGPU等に変更すると計算速度が速くなります.無料で使えるものもありますが,使用時間に制限等があります.
GPUを選択した場合は,下記コマンドで認識できているか確認できます.選択したGPUの仕様等が簡単に表示されます.
保存場所の確認・移動
!nvidia-smi
2. プログラム
必要なライブラリのインポート
import sys
import tensorflow as tf
import tensorflow.keras
import pandas as pd
import sklearn as sk
import tensorflow as tf
print(f"Tensor Flow Version: {tf.__version__}")
print(f"Keras Version: {tensorflow.keras.__version__}")
print()
print(f"Python {sys.version}")
print(f"Pandas {pd.__version__}")
print(f"Scikit-Learn {sk.__version__}")
gpu = len(tf.config.list_physical_devices('GPU'))>0
print("GPU is", "available" if gpu else "NOT AVAILABLE")
時刻表示用の自作関数
# Nicely formatted time string
def hms_string(sec_elapsed):
h = int(sec_elapsed / (60 * 60))
m = int((sec_elapsed % (60 * 60)) / 60)
s = sec_elapsed % 60
return f"{h}:{m:>02}:{s:>05.2f}"
データセットのダウンロード
import tensorflow.keras
from tensorflow.keras.callbacks import EarlyStopping
from tensorflow.keras.layers import Dense, Dropout
from tensorflow.keras import regularizers
from tensorflow.keras.datasets import mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
print("Shape of x_train: {}".format(x_train.shape))
print("Shape of y_train: {}".format(y_train.shape))
print()
print("Shape of x_test: {}".format(x_test.shape) )
print("Shape of y_test: {}".format(y_test.shape) )
データの中の画像を1つ表示してみる(画像)
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
digit = 105 # Change to choose new digit
a = x_train[digit]
plt.imshow(a, cmap='gray', interpolation='nearest')
print("Image (#{}): Which is digit '{}'".format(digit, y_train[digit]) )
from IPython.display import display
import pandas as pd
データの中の画像を1つ表示してみる(数値)
pd.set_option('display.max_columns', 29)
pd.set_option('display.max_rows', 29)
print("Shape for dataset: {}".format(x_train.shape))
print("Labels: {}".format(y_train))
# single MNIST digit
digit = 105
single = x_train[digit]
print("Shape for single: {}".format(single.shape))
pd.DataFrame(single.reshape(28,28))
データの中の画像をランダムに複数表示してみる(数値)
import random
ROWS = 6
random_indices = random.sample(range(x_train.shape[0]), ROWS*ROWS)
sample_images = x_train[random_indices, :]
plt.clf()
fig, axes = plt.subplots(ROWS, ROWS, figsize=(ROWS,ROWS),sharex=True, sharey=True)
for i in range(ROWS*ROWS):
subplot_row = int(i/ROWS)
subplot_col = int(i%ROWS)
ax = axes[subplot_row, subplot_col]
plottable_image = np.reshape(sample_images[i,:], (28,28))
ax.imshow(plottable_image, cmap='gray_r')
ax.set_xbound([0,28])
plt.tight_layout()
plt.show()
入力データの前処理
import tensorflow.keras
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Flatten
from tensorflow.keras.layers import Conv2D, MaxPooling2D
from tensorflow.keras import backend as K
batch_size = 128
num_classes = 10
epochs = 12
#input image dimensions
img_rows, img_cols = 28, 28
if K.image_data_format() == 'channels_first':
x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
input_shape = (1, img_rows, img_cols)
else:
x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
input_shape = (img_rows, img_cols, 1)
x_train= x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255.0
x_test /= 255.0
print("Training samples: {}".format(x_train.shape[0]))
print("Test samples: {}".format(x_test.shape[0]))
# convert class vectors to binary class matrices
y_train = tensorflow.keras.utils.to_categorical(y_train, num_classes)
y_test = tensorflow.keras.utils.to_categorical(y_test, num_classes)
print('x_train shape:', x_train.shape)
print('y_train shape:', y_train.shape)
print('x_test shape:', x_test.shape)
print('y_test shape:', y_test.shape)
ニューラルネットワークの構築
Denseのみのシンプルなニューラルネットワーク
model = Sequential()
model.add(Flatten(input_shape=input_shape))
model.add(Dense(512, activation='relu'))
model.add(Dense(128, activation='relu'))
model.add(Dense(num_classes, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
構築したニューラルネットワークを図で示してみる
plotモード
from tensorflow.keras.utils import plot_model
plot_model(model, show_shapes=True, to_file="model.png", dpi=60)
学習
import tensorflow as tf
import time
start_time = time.time()
model.fit(x_train, y_train,
batch_size=batch_size,
epochs=epochs,
verbose=2,
validation_data=(x_test,y_test)
)
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss: {}'.format(score[0]))
print('Test accuracy: {}'.format(score[1]))
elapsed_time = time.time() - start_time
print("Elapsed time: {}".format(hms_string(elapsed_time)))
学習後のNNのテスト・評価
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss: {}'.format(score[0]))
print('Test accuracy: {}'.format(score[1]))
from sklearn import metrics
# For GPU just grab the first 100 images
small_x = x_test[1:100]
small_y = y_test[1:100]
small_y2 = np.argmax(small_y, axis=1)
pred = model.predict(small_x)
pred = np.argmax(pred,axis=1)
score = metrics.accuracy_score(small_y2, pred)
print('Accuracy: {}'.format(score))
学習後のNNの保存
import os
save_path = "."
# save entire network to HDF5 (save everything, suggested)
model.save(os.path.join(save_path,"my_network.keras"))
保存したNNの読み込みと確認
from tensorflow.keras.models import load_model
import os
save_path = "." # Assuming the model was saved in the current directory
model2 = load_model(os.path.join(save_path, 'my_network.keras'))
model2.summary() #モデル情報を出力
読み込んだモデルのテスト
from tensorflow.keras.models import load_model
import os
save_path = "." # Assuming the model was saved in the current directory
model2 = load_model(os.path.join(save_path, 'my_network.keras'))
model2.summary() #モデル情報を出力
3. 演習
演習①
ネットワーク構造を改善して,学習後の「Test accuracy」の値ができるだけ大きくなるようにして下さい.目標:0.99以上.
ヒント
CNNを導入する,ドロップアウトを導入する など