from keras.datasets import mnist (train_images, train_labels), (test_images, test_labels) = mnist.load_data() #train_images 和 train_labels 是訓練集
train_images.shape#第一個數字表示圖片張數,後面表示圖片尺寸,和以前我在opencv上遇到的有所不一樣 #opencv上是前面表示圖片尺寸,後面表示圖片的通道數量
輸出:網絡
(60000, 28, 28)
len(train_labels)
輸出:
60000測試
from keras import models from keras import layers
下面開始構造神經網絡:lua
network = models.Sequential() network.add(layers.Dense(512, activation='relu', input_shape=(28 * 28,)))#果真shape是28*28!!! network.add(layers.Dense(10, activation='softmax'))
預編譯:spa
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
開始訓練模型:code
network.fit(train_images, train_labels, epochs=5, batch_size=128)
輸出:blog
Epoch 1/5 60000/60000 [==============================] - 7s 111us/step - loss: 0.2523 - acc: 0.9274 Epoch 2/5 60000/60000 [==============================] - 7s 111us/step - loss: 0.1029 - acc: 0.9689 5s - loss: 0.1212 Epoch 3/5 60000/60000 [==============================] - 7s 116us/step - loss: 0.0677 - acc: 0.9795 Epoch 4/5 60000/60000 [==============================] - 8s 130us/step - loss: 0.0504 - acc: 0.9848 Epoch 5/5 60000/60000 [==============================] - 7s 119us/step - loss: 0.0374 - acc: 0.9886 2s - loss: 0.0370 - Out[12]: <keras.callbacks.History at 0x1c6e30c1828>
所以可得識別準確度爲98%圖片
進行測試集的驗證:input
test_loss, test_acc = network.evaluate(test_images, test_labels)
輸出準確度:it
print('識別準確度爲:', test_acc)
識別準確度爲:
0.9807io