長野エンジニアライフ

東京から長野に移住したエンジニアのブログです。🦒🗻⛰

MNISTデータセットからモデルを作成する

MNISTデータセットについて

  • MNIST(Mixed National Institute of Standards and Technology database)
    手書き数字(0~9)が格納されたデータセット
    MNISTは、エムニストと読む

必要なモジュールを準備

  • jupyter
  • keras
  • tensorflow
> pip3 intstall jupyter keras tensorflow

データセットの読み込み

from keras.datasets import mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
# 訓練データの確認
print(train_images.shape)
print(len(train_labels))
print(train_labels)
(60000, 28, 28)
60000
[5 0 4 ... 5 6 8]

60,000個の訓練データが存在する。手書きの画像データの大きさは28×28

# テストデータの確認
print(test_images.shape)
print(len(test_labels))
print(test_labels)
(10000, 28, 28)
10000
[7 2 1 ... 4 5 6]

10,000個のテストデータが存在する。画像の大きさは同じく28×28

ニューラルネットワークモデルの構築

# ニューラルネットワークモデルの構築
from keras import models
from keras import layers

network = models.Sequential()
network.add(layers.Dense(512, activation='relu', input_shape=(28 * 28, )))
network.add(layers.Dense(10, activation='softmax'))

何をしているかは後で調べる。

コンパイルステップ

# コンパイルステップ
network.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])

何をしているかは後で調べる。

画像データの前処理

# 画像データの前処理
train_images = train_images.reshape((60000, 28 * 28))
train_images = train_images.astype('float32') / 255

test_images = test_images.reshape((10000, 28 * 28))
test_images = test_images.astype('float32') / 255

(60000,28,28)3次元データを(60000,784)2次元データに変換

ラベルの準備

# ラベルの準備
from keras.utils import to_categorical

train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)

0~9のラベルの値をone-hotエンコーディングする。

ニューラルネットワークモデルの学習

# ニューラルネットワークモデルの学習
network.fit(train_images, train_labels, epochs=5, batch_size=128)
Epoch 1/5
60000/60000 [==============================] - 1s 19us/step - loss: 0.2561 - accuracy: 0.9261
Epoch 2/5
60000/60000 [==============================] - 1s 18us/step - loss: 0.1060 - accuracy: 0.9680
Epoch 3/5
60000/60000 [==============================] - 1s 18us/step - loss: 0.0704 - accuracy: 0.9787
Epoch 4/5
60000/60000 [==============================] - 1s 18us/step - loss: 0.0511 - accuracy: 0.9844
Epoch 5/5
60000/60000 [==============================] - 1s 18us/step - loss: 0.0384 - accuracy: 0.9884

lossは損失値、accは正解率を表す。

テストデータによる精度確認

# テストデータによる精度確認
test_loss, test_acc = network.evaluate(test_images, test_labels)
print('test_acc:', test_acc)
10000/10000 [==============================] - 0s 19us/step
test_acc: 0.9790999889373779

以上、MNISTデータセットを判定するモデルを作成した。

github.com

nbviewer.jupyter.org