1. 程式人生 > >【深度學習】基於Keras的手寫體識別

【深度學習】基於Keras的手寫體識別

from keras import models
from keras import layers
from keras.datasets import mnist

# 搭建網路
network = models.Sequential()
network.add(layers.Dense(512, activation='relu', input_shape=(28*28,)))
network.add(layers.Dense(10,activation='softmax')) # 返回由10個概率值組成的陣列

# 編譯網路
network.compile(optimizer='rmsprop'
, loss='categorical_crossentropy', metrics=['accuracy']) # 載入資料 (train_images, train_labels),(test_images, test_labels) = mnist.load_data() # 對資料進行預處理 train_images = train_images.reshape(60000, 28*28) train_images.astype('float32') / 255 test_images = test_images.reshape(10000, 28*28) test_images = test_images.
astype('float32') / 255 # 準備標籤 -- One-Hot編碼 from keras.utils import to_categorical train_labels = to_categorical(train_labels) test_labels = to_categorical(test_labels) print(train_labels[0]) # array([0., 0., 0., 0., 0., 1., 0., 0., 0., 0.], dtype=float32) # 開始訓練網路:擬合數據 network.fit(train_images, train_labels,
epochs=10, batch_size=128) ''' Epoch 1/10 60000/60000 [==============================] - 2s 39us/step - loss: 5.3171 - acc: 0.6697 Epoch 2/10 60000/60000 [==============================] - 2s 39us/step - loss: 5.2466 - acc: 0.6743 Epoch 3/10 60000/60000 [==============================] - 2s 39us/step - loss: 5.2882 - acc: 0.6716 Epoch 4/10 60000/60000 [==============================] - 2s 38us/step - loss: 5.2737 - acc: 0.6726 Epoch 5/10 60000/60000 [==============================] - 2s 38us/step - loss: 5.2659 - acc: 0.6730 Epoch 6/10 60000/60000 [==============================] - 2s 38us/step - loss: 5.2511 - acc: 0.6740 Epoch 7/10 60000/60000 [==============================] - 2s 38us/step - loss: 5.2200 - acc: 0.6758 Epoch 8/10 60000/60000 [==============================] - 2s 38us/step - loss: 5.2329 - acc: 0.6751 Epoch 9/10 60000/60000 [==============================] - 2s 37us/step - loss: 5.2335 - acc: 0.6750 Epoch 10/10 60000/60000 [==============================] - 2s 37us/step - loss: 5.2414 - acc: 0.6746 '''

案例中訓練5輪即可達到98.9%的精度,我實際用起來效果並不是很好,還沒看哪裡有不同。

訓練完後,直接用於預測:

test_loss, test_acc = network.evaluate(test_images, test_labels)
print('test_acc: ', test_acc)
'''
10000/10000 [==============================] - 1s 52us/step
test_acc:  0.6772
'''

重點還是在於回顧Keras的使用,算是一個簡單的模板,後續再豐富使用場景。

END.