【深度学习】基于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.

你可能感兴趣的:(Deep,Learning)