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
下面开始构造神经网络:
network = models.Sequential() network.add(layers.Dense(512, activation='relu', input_shape=(28 * 28,)))#果然shape是28*28!!! network.add(layers.Dense(10, activation='softmax'))
预编译:
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
开始训练模型:
network.fit(train_images, train_labels, epochs=5, batch_size=128)
输出:
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%
进行测试集的验证:
test_loss, test_acc = network.evaluate(test_images, test_labels)
输出准确度:
print('识别准确度为:', test_acc)
识别准确度为:
0.9807
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:利用keras进行手写数字识别模型训练,并输出训练准确度 - Python技术站