1.加载相关包:
# TensorFlow and tf.keras
import tensorflow as tf
from tensorflow import keras
# Helper libraries
import numpy as np
import matplotlib.pyplot as plt
2.加载数据集并把图像和标签赋值给训练集和测试集:
fashion_mnist = keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
3. 制作分类标签:
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
4.查看某一幅图像:
plt.figure()
plt.imshow(train_images[0])
plt.colorbar()
plt.grid(False)
plt.show()
5.归一化处理:
train_images = train_images / 255.0
test_images = test_images / 255.0
6.可以查看一下原图片:
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]])
plt.show()
7.搭建模型:
model = keras.Sequential([
keras.layers.Flatten(input_shape=(28, 28)),
keras.layers.Dense(128, activation='relu'),
keras.layers.Dense(10)
])
8.定义优化器和损失函数:
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
9.开始训练,这里训练次数为10轮:
model.fit(train_images, train_labels, epochs=10)
10.训练完毕查看损失值和准确率:
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
print('\nTest accuracy:', test_acc)
11. softmax进行分类:
probability_model = tf.keras.Sequential([model,
tf.keras.layers.Softmax()])
12.用测试集进行预测并查看第一个预测结果:
predictions = probability_model.predict(test_images)
predictions[0]