基本分类:对服装图像进行分类
1.导入基本的库
import tensorflow as tf
from tensorflow import keras
import numpy as np
import matplotlib.pyplot as plt
2. 导入 Fashion MNIST 数据集
fashion_mnist = keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
该数据集包含 10 个类别的 70000 个灰度图像。这些图像以低分辨率(28x28 像素)展示了单件衣物
我们使用 60,000 个图像来训练网络,使用 10,000 个图像来评估网络学习对图像分类的准确率。
图像是 28x28 的 NumPy 数组,像素值介于 0 到 255 之间。标签是整数数组,介于 0 到 9
之间。这些标签对应于图像所代表的服装类:
0-T恤/上衣 1-裤子 2-套头衫 3-连衣裙 4-外套 5-凉鞋 6-衬衫 7-运动鞋 8-包 9-短靴
每个图像都会被映射到一个标签。我们将每一个标签命名,用于后面作图。
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat','Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
3.预处理数据
在训练网络之前,必须对数据进行预处理。图像像素值处于 0 到 255 之间,将这些值缩小至 0 到 1 之间,然后将其馈送到神经网络模型。为此,需这些值除以 255。
plt.figure()
plt.imshow(train_images[0])
plt.colorbar()
plt.grid(False)
train_images = train_images / 255.0
test_images = test_images / 255.0
4. 构建模型
构建神经网络需要先配置模型的层,然后再编译模型。
4.1 设置层
model = keras.Sequential([
keras.layers.Flatten(input_shape=(28, 28)),
keras.layers.Dense(128, activation='relu'),
keras.layers.Dense(10)
])
tf.keras.layers.Flatten
将图像格式从二维数组(28 x 28 像素)转换成一维数组(28 x 28 = 784 像素)。
tf.keras.layers.Dense
它们是密集连接或全连接神经层。
第一个 `Dense` 层有 128 个节点(或神经元)。
第二个(也是最后一个)层会返回一个长度为 10 的 logits 数组。每个节点都包含一个得分,用来表示当前图像属于 10 个类中的哪一类。
4.2 编译模型
在准备对模型进行训练之前,还需要再对其进行一些设置。以下内容是在模型的编译步骤中添加的:
- 损失函数 - 用于测量模型在训练期间的准确率。您会希望最小化此函数,以便将模型“引导”到正确的方向上。
- 优化器 - 决定模型如何根据其看到的数据和自身的损失函数进行更新。
- 指标 - 用于监控训练和测试步骤。以下示例使用了准确率,即被正确分类的图像的比率。
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
5. 训练模型
训练神经网络模型需要执行以下步骤:
- 将训练数据馈送给模型。在本例中,训练数据位于
train_images
和train_labels
数组中。 - 模型学习将图像和标签关联起来。
- 要求模型对测试集(在本例中为
test_images
数组)进行预测。 - 验证预测是否与
test_labels
数组中的标签相匹配。
5.1 向模型馈送数据
要开始训练,请调用 model.fit
方法,这样命名是因为该方法会将模型与训练数据进行“拟合”:
model.fit(train_images, train_labels, epochs=10)
Epoch 1/10
1875/1875 [==============================] - 1s 622us/step - loss: 0.4956 - accuracy: 0.8264
Epoch 2/10
1875/1875 [==============================] - 1s 610us/step - loss: 0.3765 - accuracy: 0.8648
Epoch 3/10
1875/1875 [==============================] - 1s 613us/step - loss: 0.3364 - accuracy: 0.8779
Epoch 4/10
1875/1875 [==============================] - 1s 616us/step - loss: 0.3132 - accuracy: 0.8860
Epoch 5/10
1875/1875 [==============================] - 1s 616us/step - loss: 0.2966 - accuracy: 0.8900
Epoch 6/10
1875/1875 [==============================] - 1s 619us/step - loss: 0.2821 - accuracy: 0.8953
Epoch 7/10
1875/1875 [==============================] - 1s 622us/step - loss: 0.2692 - accuracy: 0.8992
Epoch 8/10
1875/1875 [==============================] - 1s 620us/step - loss: 0.2563 - accuracy: 0.9051
Epoch 9/10
1875/1875 [==============================] - 1s 620us/step - loss: 0.2480 - accuracy: 0.9072
Epoch 10/10
1875/1875 [==============================] - 1s 620us/step - loss: 0.2396 - accuracy: 0.9111
<keras.callbacks.History at 0x1b0ab24f988>
在模型训练期间,会显示损失和准确率指标。此模型在训练数据上的准确率达到了 0.91(或 91%)左右。
5.2 评估准确率
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
313/313 - 0s - loss: 0.3656 - accuracy: 0.8692 - 202ms/epoch - 644us/step
5.3 进行预测
在模型经过训练后,您可以使用它对一些图像进行预测。模型具有线性输出,即 logits您可以附加一个 softmax 层,将 logits 转换成更容易理解的概率。
probability_model = tf.keras.Sequential([model, tf.keras.layers.Softmax()])
predictions = probability_model.predict(test_images)
predictions[0]
array([2.6374654e-08, 7.1966273e-11, 2.1397602e-10, 4.3100010e-11,
3.2536853e-09, 2.2600591e-04, 5.4510285e-09, 1.0962544e-03,
2.9261071e-09, 9.9867767e-01], dtype=float32)
第一个图像的预测结果是一个包含 10 个数字的数组。它们代表模型对 10 种不同服装中每种服装的“置信度”。可以看到第九个标签的置信度值最大:
因此,该模型非常确信这个图像是短靴,或 class_names[9]
。通过检查测试标签发现这个分类是正确的:
test_labels[0]
9
6.绘制图表展示预测结果
6.1 定义图表
def plot_image(i, predictions_array, true_label, img):
predictions_array, true_label, img = predictions_array, true_label[i], img[i]
plt.grid(False)
plt.xticks([])
plt.yticks([])
#cmap=plt.cm.binary 图像灰度显示
plt.imshow(img, cmap=plt.cm.binary)
#标签选择输出10个数中置信度最大的一个
predicted_label = np.argmax(predictions_array)
#预测正确
if predicted_label == true_label:
color = 'blue'
#预测错误
else:
color = 'red'
plt.xlabel("{} {:2.0f}% ({})".format(class_names[predicted_label],
100*np.max(predictions_array),
class_names[true_label]),
color=color)
def plot_value_array(i, predictions_array, true_label):
predictions_array, true_label = predictions_array, true_label[i]
plt.grid(False)
plt.xticks(range(10))
plt.yticks([])
thisplot = plt.bar(range(10), predictions_array, color="#777777")##777777为灰色
plt.ylim([0, 1])
predicted_label = np.argmax(predictions_array)
#如果预测正确,预测值和真实值相等,则蓝色会覆盖红色,如果预测错误,两者不冲突,不会相互覆盖
thisplot[predicted_label].set_color('red')
thisplot[true_label].set_color('blue')
6.2 验证预测结果
我们来看看第 0 个图像、预测结果和预测数组。正确的预测标签为蓝色,错误的预测标签为红色。数字表示预测标签的百分比(总计为 100)。
i = 0
plt.figure(figsize=(6,3))
plt.subplot(1,2,1)
plot_image(i, predictions[i], test_labels, test_images)
plt.subplot(1,2,2)
plot_value_array(i, predictions[i], test_labels)
plt.show()
i = 12
plt.figure(figsize=(6,3))
plt.subplot(1,2,1)
plot_image(i, predictions[i], test_labels, test_images)
plt.subplot(1,2,2)
plot_value_array(i, predictions[i], test_labels)
plt.show()
即使置信度很高,模型也可能出错。
7.使用训练好的模型
最后,使用训练好的模型对单个图像进行预测。
#抓取数据集上的第二张图片
img = test_images[1]
img = (np.expand_dims(img,0))#扩维后进行预测
现在预测这个图像的正确标签:
predictions_single = probability_model.predict(img)
print(predictions_single)
[[5.9669791e-04 1.9646879e-13 9.9908233e-01 1.8658164e-11 2.4529127e-04
2.2544250e-06 7.3343697e-05 6.8721829e-19 1.3740149e-11 4.1833949e-15]]
plot_value_array(1, predictions_single[0], test_labels)
_ = plt.xticks(range(10), class_names, rotation=45)