加载mnist数据集
1 | from keras.datasets import mnist |
(60000, 28, 28) <class 'numpy.ndarray'>
(60000,) <class 'numpy.ndarray'>
(10000, 28, 28) <class 'numpy.ndarray'>
(10000,) <class 'numpy.ndarray'>
数据处理:规范化
1 | # 将图形从[28,28]变为[784,] |
(60000, 784) (10000, 784)
1 | # 将数据转换为float32,为了进行归一化,不然/255得到全部是0 |
统计训练数据中个标签数量
1 | import numpy as np |
[0 1 2 3 4 5 6 7 8 9] [5923 6742 5958 6131 5842 5421 5918 6265 5851 5949]
1 | fig = plt.figure(figsize=(8, 5)) |
对标签进行one-hot编码
1 | # import tensorflow as tf |
(60000, 10)
1 | print(y_train[0]) |
5
[0. 0. 0. 0. 0. 1. 0. 0. 0. 0.]
使用Keras sequential model 定义神经网络
1 | # 使用keras定义线性网络很方便 |
编译模型
1 | model.compile(loss='categorical_crossentropy',optimizer='adam', metrics=['accuracy']) |
训练模型,并将指标保存到history中
1 | history = model.fit(X_train, Y_train, batch_size=128, epochs=5, |
Train on 60000 samples, validate on 10000 samples
Epoch 1/5
- 7s - loss: 0.2156 - acc: 0.9373 - val_loss: 0.0970 - val_acc: 0.9710
Epoch 2/5
- 7s - loss: 0.0804 - acc: 0.9758 - val_loss: 0.0769 - val_acc: 0.9770
Epoch 3/5
- 7s - loss: 0.0504 - acc: 0.9838 - val_loss: 0.0791 - val_acc: 0.9746
Epoch 4/5
- 7s - loss: 0.0350 - acc: 0.9891 - val_loss: 0.0659 - val_acc: 0.9804
Epoch 5/5
- 8s - loss: 0.0264 - acc: 0.9913 - val_loss: 0.0734 - val_acc: 0.9794
可视化指标
1 | fig = plt.figure() |
保存模型
1 | import os |
Saved trained model at .\model\keras_mnist.h5
加载模型
1 | from keras.models import load_model |
统计模型在测试集上的分类结果
1 | loss_and_metrics = mnist_model.evaluate(X_test, Y_test, verbose=2) |
Test Loss: 0.07340353026344673
Test Accuracy: 97.94%
Classified correctly count: 9794
Classified incorrectly count: 206