1 加载Keras中的MNIST数据集
from keras.datasets import mnist
(train_images,train_labels),(test_images,test_labels)=mnist.load_data()
train_images.shape
(60000, 28, 28)
train_labels.shape
(60000,)
train_labels
array([5, 0, 4, ..., 5, 6, 8], dtype=uint8)
2 网络架构
- 将训练数据输入到神经网络中;
- 网络学习将图像和标签关联在一起;
- 网络对test_image进行预测,验证这些预测是否与test_labels中的标签是否匹配
from keras import layers
from keras import models
networks=models.Sequential()
networks.add(layers.Dense(512,activation='relu',input_shape=(28*28,)))
networks.add(layers.Dense(10,activation='softmax'))
网络含两个Dense层,它们是密集连接(全连接),第二层是一个10路的softmax层,它返回一个由10个概率值(总和为1)组成的数组
3 编译步骤
想训练网络,我们还需要选择编译(compile)步骤的三个参数
- 损失函数
- 优化器
- 在训练和测试过程中需要监控的指标
networks.compile(optimizer='rmsprop',
loss='categorical_crossentropy',
metrics=['accuracy'])
4 准备图像数据
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
5 准备标签
from keras.utils import to_categorical
train_labels=to_categorical(train_labels)
test_labels=to_categorical(test_labels)
networks.fit(train_images,train_labels,epochs=5,batch_size=128)
Epoch 1/5
60000/60000 [==============================] - 5s 89us/step - loss: 0.2607 - accuracy: 0.9248
Epoch 2/5
60000/60000 [==============================] - 5s 82us/step - loss: 0.1047 - accuracy: 0.9693
Epoch 3/5
60000/60000 [==============================] - 5s 82us/step - loss: 0.0686 - accuracy: 0.9792
Epoch 4/5
60000/60000 [==============================] - 6s 98us/step - loss: 0.0512 - accuracy: 0.9843
Epoch 5/5
60000/60000 [==============================] - 5s 91us/step - loss: 0.0380 - accuracy: 0.9887
<keras.callbacks.callbacks.History at 0x177b9fcb748>
版权声明:本文为weixin_43608722原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。