from tensorflow.keras.datasets import mnist# keras做为tf2.0高阶api 如此食用
复制代码
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
复制代码
print(train_images.shape)
print(len(train_labels))
print(train_labels)
复制代码
(60000, 28, 28)
60000
[5 0 4 ... 5 6 8]
复制代码
from tensorflow.keras import models
from tensorflow.keras import layers# layers层,一种数据处理模块,能够当作数据过滤器,过滤出更有用的数据
复制代码
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'])
复制代码
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
复制代码
#对标签进行分类编码
from tensorflow.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)
复制代码
Train on 60000 samples
Epoch 1/5
60000/60000 [==============================] - 4s 74us/sample - loss: 0.2543 - accuracy: 0.9248
Epoch 2/5
60000/60000 [==============================] - 4s 62us/sample - loss: 0.1040 - accuracy: 0.9692
Epoch 3/5
60000/60000 [==============================] - 4s 62us/sample - loss: 0.0686 - accuracy: 0.9791
Epoch 4/5
60000/60000 [==============================] - 4s 64us/sample - loss: 0.0497 - accuracy: 0.9856
Epoch 5/5
60000/60000 [==============================] - 4s 61us/sample - loss: 0.0368 - accuracy: 0.9890
<tensorflow.python.keras.callbacks.History at 0x248802cfd88>
复制代码
一个是网络在训练数据上的损失(loss),另外一个是网络在 训练数据上的精度(acc)。python
检查一下模型在测试集上的性能。 test_loss, test_acc = network.evaluate(test_images, test_labels) print('test_acc:', test_acc)api
训练精度和测试精度之间的这种差距是过拟合(overfit)形成的。 过拟合是指机器学习模型在新数据上的性能每每比在训练数据上要差数组