此实战来源于TensorFlow Keras官方教程
Fashion-MNIST是一个替代MNIST手写数字集的图像数据集。 它是由Zalando(一家德国的时尚科技公司)旗下的研究部门提供。其涵盖了来自10种类别的共7万个不同商品的正面图片。Fashion-MNIST的大小、格式和训练集/测试集划分与原始的MNIST完全一致。60000/10000的训练测试数据划分,28x28的灰度图片。你可以直接用它来测试你的机器学习和深度学习算法性能,且不需要改动任何的代码。
# TensorFlow and tf.keras
import os
os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
import tensorflow as tf
from tensorflow import keras
# Helper libraries
import numpy as np
import matplotlib.pyplot as plt
print(tf.__version__)
1.12.0
fashion_mnist = keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
train_images.shape
(60000, 28, 28)
len(train_labels)
60000
train_images = train_images / 255.0
test_images = test_images / 255.0
plt.figure()
plt.imshow(train_images[0])
plt.colorbar()
plt.grid(False)
plt.figure(figsize=(10,10))
for i in range(25):
plt.subplot(5,5,i+1)
plt.xticks([])
plt.yticks([])
plt.grid(False)
plt.imshow(train_images[i], cmap=plt.cm.binary)
plt.xlabel(class_names[train_labels[i]])
model = keras.Sequential([
#shape转换过程 (-1,28,28)->(-1,28*28)
keras.layers.Flatten(input_shape=(28, 28)),
#shape转换过程 (-1,28*28)->(-1,256)
keras.layers.Dense(256, activation=tf.nn.relu),
#shape转换过程 (-1,256)->(-1,256)
keras.layers.Dropout(0.2,noise_shape=None, seed=None),
#shape转换过程 (-1,256)->(-1,64)
keras.layers.Dense(64, activation=tf.nn.relu),
#shape转换过程 (-1,64)->(-1,10)
keras.layers.Dense(10, activation=tf.nn.softmax)
])
model.compile(optimizer=tf.train.AdamOptimizer(),
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(train_images, train_labels, epochs=5)
Epoch 1/5
60000/60000 [==============================] - 8s 136us/step - loss: 0.4993 - acc: 0.8249
Epoch 2/5
60000/60000 [==============================] - 7s 121us/step - loss: 0.3819 - acc: 0.8627
Epoch 3/5
60000/60000 [==============================] - 8s 127us/step - loss: 0.3429 - acc: 0.8758
Epoch 4/5
60000/60000 [==============================] - 9s 142us/step - loss: 0.3142 - acc: 0.8857
Epoch 5/5
60000/60000 [==============================] - 6s 102us/step - loss: 0.2972 - acc: 0.8908
test_loss, test_acc = model.evaluate(test_images, test_labels)
print('Test accuracy:', test_acc)
10000/10000 [==============================] - 0s 45us/step
Test accuracy: 0.867
plt.figure()
plt.imshow(test_images[1])
plt.colorbar()
plt.grid(False)
predictions = model.predict(test_images[1:2])
class_names[np.argmax(predictions)]
'Pullover'