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)形成的。 過擬合是指機器學習模型在新數據上的性能每每比在訓練數據上要差數組