手書きの数字をフィードフォワードニューラルネットワークに認識させてみる。
MNISTデータベース
手書き数字のデータセットには、MNISTと呼ばれる有名なデータベースを使う。このデータセットはKerasを使って簡単に読み込むことができる。
from keras.datasets import mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
実行すると、60000個のトレーニング用データがx_train
, y_train
に、10000個のテストデータがx_test
, y_test
に格納される。
x_train
は60000×28×28の配列変数で、各要素は0-255の値をとる整数である。i番目のデータはx_train[i,:,:]
で取り出せる。
実際にx_train
に格納された初めの3つの画像を表示する。
import numpy as np
import matplotlib.pyplot as plt
from keras.datasets import mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
plt.figure(1, figsize=(12, 3.2))
plt.subplots_adjust(wspace=0.5)
plt.gray()
for id in range(3):
plt.subplot(1, 3, id + 1)
img = x_train[id, :, :]
plt.pcolor(255 - img)
plt.text(24.5, 26, "%d" % y_train[id], color='cornflowerblue', fontsize=18)
plt.xlim(0, 27)
plt.ylim(27, 0)
plt.grid('on', color='white')
plt.show()
目標データであるy_train
の値は画像の右下に青色の数字で表示している。