从Keras自带MNIST数据集中读取数据
MNIST dataset, a large database of handwritten digits that is commonly used for training various image processing systems. MNIST dataset has 60,000 training images, plus 10,000 test images, assembled by the National Institute of Standards and Technology in the 1980s.
参考链接:
https://en.wikipedia.org/wiki/MNIST_database
https://github.com/mbornet-hl/MNIST
import warnings
warnings.filterwarnings('ignore')
from keras.datasets import mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz
11490434/11490434 [==============================] - 1s 0us/step
train_images.shape
(60000, 28, 28)
test_labels
array([7, 2, 1, ..., 4, 5, 6], dtype=uint8)
设计神经网络架构
首先将训练数据导入神经网络,网络学习图片和label之间的关系,最终生成模型。模型可以用于预测测试图片的label,最终我们通过测试label和预测的label比较来评估模型。
from keras import models
from keras import layers
warnings.filterwarnings('ignore')
network = models.Sequential()
network.add(layers.Dense(512, activation='relu', input_shape=(28*28,)))
network.add(layers.Dense(10, activation='softmax'))
网络编译
network.compile(optimizer='rmsprop',
loss='categorical_crossentropy',
metrics=['accuracy'])
warnings.filterwarnings('ignore')
数据转换和重组
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
warnings.filterwarnings('ignore')
模型训练
from keras.utils import to_categorical
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)
network.fit(train_images, train_labels, epochs=5, batch_size=128)
warnings.filterwarnings('ignore')
Epoch 1/5
469/469 [==============================] - 4s 8ms/step - loss: 0.0286 - accuracy: 0.9915
Epoch 2/5
469/469 [==============================] - 4s 7ms/step - loss: 0.0210 - accuracy: 0.9939
Epoch 3/5
469/469 [==============================] - 3s 7ms/step - loss: 0.0160 - accuracy: 0.9959
Epoch 4/5
469/469 [==============================] - 3s 7ms/step - loss: 0.0122 - accuracy: 0.9968
Epoch 5/5
469/469 [==============================] - 3s 7ms/step - loss: 0.0089 - accuracy: 0.9979
模型评估
test_loss, test_acc = network.evaluate(test_images, test_labels)
print("Model test accuracy: ", test_acc)
313/313 [==============================] - 1s 3ms/step - loss: 0.0582 - accuracy: 0.9832
Model test accuracy: 0.9832000136375427
参考:
Francois Chollet, Deep Learning with Python