【深さ学習フレームワークKeras】最初の簡単な例

4805 ワード

一、MNISTデータセットは手書きデジタル画像のデータセットであり、60000枚の訓練画像と10000枚のテスト画像を含み、これらの画像は28である。× × 28の階調画像には、0~9の合計10個の数字が含まれています。

import keras
from keras.datasets import mnist
(train_images,train_labels),(test_images,test_labels) = mnist.load_data() # 

二、データセットの関連情報

print('shape of train images is ',train_images.shape)
print('shape of train labels is ',train_labels.shape)
print('train labels is ',train_labels)
print('shape of test images is ',test_images.shape)
print('shape of test labels is',test_labels.shape)
print('test labels is',test_labels)
shape of train images is  (60000, 28, 28)
shape of train labels is  (60000,)
train labels is  [5 0 4 ... 5 6 8]
shape of test images is  (10000, 28, 28)
shape of test labels is (10000,)
test labels is [7 2 1 ... 4 5 6]

三、設計ネットワーク構造(Kerasではlayersはネットワーク構造の礎である)

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

四、optimizer、loss function、metricsを指定し、ネットワークをコンパイルする

network.compile(optimizer='rmsprop',loss='categorical_crossentropy',metrics=['accuracy'])

五、データの処理


元のデータは、shapeが(60000,28,28)のNumpy配列に格納され、データ要素は[0255]の整数です。一方、shapeが(60000,28*28)であり、要素の区間[0,1]に介在する浮動小数点数として処理する必要がある。

#  
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
#  
from keras.utils import to_categorical
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)

六、トレーニングモデル

network.fit(train_images,train_labels,epochs=5,batch_size=128)
Epoch 1/5
60000/60000 [==============================] - 4s 58us/step - loss: 0.2554 - acc: 0.9266
Epoch 2/5
60000/60000 [==============================] - 4s 61us/step - loss: 0.1018 - acc: 0.9700
Epoch 3/5
60000/60000 [==============================] - 4s 72us/step - loss: 0.0665 - acc: 0.9806
Epoch 4/5
60000/60000 [==============================] - 5s 76us/step - loss: 0.0486 - acc: 0.9850
Epoch 5/5
60000/60000 [==============================] - 5s 80us/step - loss: 0.0359 - acc: 0.9889







七、評価テストセット

test_loss,test_acc = network.evaluate(test_images,test_labels)
print("test_loss:",test_loss)
print("test_acc:",test_acc)
10000/10000 [==============================] - 0s 38us/step
test_loss: 0.06354748234406579
test_acc: 0.9804