ディープラーニング CNNアルゴリズム

# CNNでMNISTの分類問題に挑戦
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras.optimizers import RMSprop 
from keras.datasets import mnist
import matplotlib.pyplot as plt

# 入力と出力を指定 --- (*1)
im_rows = 28 # 画像の縦ピクセルサイズ
im_cols = 28 # 画像の横ピクセルサイズ
im_color = 1 # 画像の色空間/グレイスケール
in_shape = (im_rows, im_cols, im_color)
out_size = 10

# MNISTのデータを読み込み 
(X_train, y_train), (X_test, y_test) = mnist.load_data()
# 読み込んだデータをの三次元配列に変換 --- (*1a)
X_train = X_train.reshape(-1, im_rows, im_cols, im_color)
X_train = X_train.astype('float32') / 255
X_test = X_test.reshape(-1, im_rows, im_cols, im_color)
X_test = X_test.astype('float32') / 255
# ラベルデータをone-hotベクトルに直す
y_train = keras.utils.to_categorical(y_train.astype('int32'),10)
y_test = keras.utils.to_categorical(y_test.astype('int32'),10)

# CNNモデル構造を定義 --- (*2)
model = Sequential()
model.add(Conv2D(32, 
          kernel_size=(3, 3),
          activation='relu',
          input_shape=in_shape))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(out_size, activation='softmax'))

# モデルをコンパイル --- (*3)
model.compile(
    loss='categorical_crossentropy',
    optimizer=RMSprop(),
    metrics=['accuracy'])

# 学習を実行 --- (*4)
hist = model.fit(X_train, y_train,
          batch_size=128, 
          epochs=12,
          verbose=1,
          validation_data=(X_test, y_test))

# モデルを評価 --- (*5)
score = model.evaluate(X_test, y_test, verbose=1)
print('正解率=', score[1], 'loss=', score[0])

# 学習の様子をグラフへ描画 --- (*6)
# 正解率の推移をプロット
plt.plot(hist.history['accuracy'])
plt.plot(hist.history['val_accuracy'])
plt.title('Accuracy')
plt.legend(['train', 'test'], loc='upper left')
plt.show()

# ロスの推移をプロット
plt.plot(hist.history['loss'])
plt.plot(hist.history['val_loss'])
plt.title('Loss')
plt.legend(['train', 'test'], loc='upper left')
plt.show()

$ python mnist-cnn.py 
/home/ten/Documents/Untitled Folder/venv/lib/python3.10/site-packages/keras/src/layers/convolutional/base_conv.py:99: UserWarning: Do not pass an `input_shape`/`input_dim` argument to a layer. When using Sequential models, prefer using an `Input(shape)` object as the first layer in the model instead.
  super().__init__(
2024-04-18 14:31:35.151848: W external/local_tsl/tsl/framework/cpu_allocator_impl.cc:83] Allocation of 188160000 exceeds 10% of free system memory.
Epoch 1/12
469/469 ━━━━━━━━━━━━━━━━━━━━ 70s 147ms/step - accuracy: 0.8429 - loss: 0.4924 - val_accuracy: 0.9830 - val_loss: 0.0527
Epoch 2/12
469/469 ━━━━━━━━━━━━━━━━━━━━ 85s 180ms/step - accuracy: 0.9748 - loss: 0.0850 - val_accuracy: 0.9844 - val_loss: 0.0484
Epoch 3/12
469/469 ━━━━━━━━━━━━━━━━━━━━ 86s 182ms/step - accuracy: 0.9822 - loss: 0.0630 - val_accuracy: 0.9895 - val_loss: 0.0322
Epoch 4/12
469/469 ━━━━━━━━━━━━━━━━━━━━ 78s 167ms/step - accuracy: 0.9848 - loss: 0.0518 - val_accuracy: 0.9907 - val_loss: 0.0299
Epoch 5/12
469/469 ━━━━━━━━━━━━━━━━━━━━ 72s 154ms/step - accuracy: 0.9871 - loss: 0.0440 - val_accuracy: 0.9893 - val_loss: 0.0341
Epoch 6/12
469/469 ━━━━━━━━━━━━━━━━━━━━ 69s 148ms/step - accuracy: 0.9888 - loss: 0.0376 - val_accuracy: 0.9886 - val_loss: 0.0375
Epoch 7/12
469/469 ━━━━━━━━━━━━━━━━━━━━ 68s 144ms/step - accuracy: 0.9894 - loss: 0.0348 - val_accuracy: 0.9912 - val_loss: 0.0323
Epoch 8/12
469/469 ━━━━━━━━━━━━━━━━━━━━ 67s 142ms/step - accuracy: 0.9901 - loss: 0.0326 - val_accuracy: 0.9910 - val_loss: 0.0317
Epoch 9/12
469/469 ━━━━━━━━━━━━━━━━━━━━ 67s 143ms/step - accuracy: 0.9899 - loss: 0.0333 - val_accuracy: 0.9883 - val_loss: 0.0378
Epoch 10/12
469/469 ━━━━━━━━━━━━━━━━━━━━ 67s 143ms/step - accuracy: 0.9910 - loss: 0.0284 - val_accuracy: 0.9918 - val_loss: 0.0291
Epoch 11/12
469/469 ━━━━━━━━━━━━━━━━━━━━ 67s 142ms/step - accuracy: 0.9904 - loss: 0.0282 - val_accuracy: 0.9914 - val_loss: 0.0283
Epoch 12/12
469/469 ━━━━━━━━━━━━━━━━━━━━ 67s 142ms/step - accuracy: 0.9927 - loss: 0.0242 - val_accuracy: 0.9913 - val_loss: 0.0360
2024-04-18 14:45:56.994451: W external/local_tsl/tsl/framework/cpu_allocator_impl.cc:83] Allocation of 31360000 exceeds 10% of free system memory.
313/313 ━━━━━━━━━━━━━━━━━━━━ 3s 10ms/step - accuracy: 0.9890 - loss: 0.0446    
タイトルとURLをコピーしました