Kerasでのニューラルネットワークのサンプル

投稿者: | 2020-03-07
Table of Content

Kerasでニューラルネットワークを実行するコードを描いてみました。
データセットとしてはmnistを使っています。

In [ ]:
from keras.datasets import mnist
In [ ]:
# MNIST データセットの読み込み
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
In [ ]:
train_images.shape
Out[ ]:
(60000, 28, 28)
In [ ]:
len(train_labels)
Out[ ]:
60000
In [ ]:
train_labels
Out[ ]:
array([5, 0, 4, ..., 5, 6, 8], dtype=uint8)
In [ ]:
test_images.shape
Out[ ]:
(10000, 28, 28)
In [ ]:
len(test_labels)
Out[ ]:
10000
In [ ]:
test_labels
Out[ ]:
array([7, 2, 1, ..., 4, 5, 6], dtype=uint8)
In [ ]:
from keras import models
from keras import layers

ニューラルネットワークの作成

シンプルなニューラルネットワークを作成します。

In [ ]:
network = models.Sequential()
network.add(layers.Dense(512, activation='relu', input_shape=(28 * 28,)))
network.add(layers.Dense(10, activation='softmax'))
In [ ]:
network.compile(optimizer='rmsprop',
                               loss='categorical_crossentropy',
                               metrics=['accuracy'])

データの前処理

入力を28×28の行列に変換します。
画像の値は、0〜255の値が入っているので、255で割って0-1の値に正規化します。

In [ ]:
# データの前処理
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
In [ ]:
# ラベルをカテゴリ値でエンコード
from keras.utils import to_categorical
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)
In [ ]:
network.summary()
In [ ]:
# ネットワークのトレーニング
network.fit(train_images, train_labels, epochs=5, batch_size=128)
Out[ ]:
In [ ]:
test_loss, test_acc = network.evaluate(test_images, test_labels)
print('test_acc:', test_acc)
In [ ]:
# 4つ目の数字を表示
digit = train_images[4].reshape((28,28))

import matplotlib.pyplot as plt
%matplotlib inline
plt.imshow(digit, cmap=plt.cm.binary)
plt.show()

同様のネットワークを今度はFunctional APIで定義してトレーニングしてみます。

In [ ]:
# Functional APIでの定義
input_tensor = layers.Input(shape=(784,))
x = layers.Dense(32, activation='relu')(input_tensor)
output_tensor = layers.Dense(10, activation='softmax')(x)

model = models.Model(inputs=input_tensor, outputs=output_tensor)
In [ ]:
from keras import optimizers

model.compile(optimizer=optimizers.RMSprop(lr=0.001),
                         loss='mse',
                         metrics=['accuracy'])
In [ ]:
model.fit(train_images, train_labels, epochs=5, batch_size=128)
Out[ ]:

まとめ

Kerasでニューラルネットワークを実行するコードを描いてみました。

入力データの形式と作成するネットワークの入力の形式を合わせてあげるのがポイントです。

また、入力値を0-1の値に正規化するのもポイントです。

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です