各位朋友,大家好!在本教程中,我们将看看如何在TensorFlow的帮助下用Python编程语言对各种服装图片进行分类。
社交媒体平台Instagram、YouTube和Twitter已经占据了我们的日常生活。特别是模特和名人,如果他们想让自己看起来最漂亮,就需要知道如何将服装归入几个类别。
照片中时尚物品的分类包括识别个别服装。同样在社交网络、电子商务和刑法方面也有应用。
第一步:导入模块
每个项目的第一步是导入所有需要的模块。我们将与Tensorflow以及numpy和matplotlib一起工作。
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
第2步:加载和预处理数据
我们要加载到我们的程序中的数据集可以在这里看到。
这个数据集包括60,000 灰度照片,每张照片都测量28x28 pixels ,来自十个不同的时尚类别,加上一组假的10,000图片。
MNIST 可以用这个数据集来代替。下面的代码行实现了数据的加载。
fashion_data=tf.keras.datasets.fashion_mnist
第三步:训练和测试数据分割
任何机器学习模型的主要部分都包括根据80-20规则将数据分成两部分。
80-20法则指出,80%的数据被送往训练数据,20%被送往测试数据。下面的代码将数据分成了训练和测试。
(inp_train,out_train),(inp_test,out_test)=fashion_data.load_data()
inp_train = inp_train/255.0
inp_test = inp_test/255.0
print("Shape of Input Training Data: ", inp_train.shape)
print("Shape of Output Training Data: ", out_train.shape)
print("Shape of Input Testing Data: ", inp_test.shape)
print("Shape of Output Testing Data: ", out_test.shape)
该代码对加载的数据集进行标准化处理。
Shape of Input Training Data: (60000, 28, 28)
Shape of Output Training Data: (60000,)
Shape of Input Testing Data: (10000, 28, 28)
Shape of Output Testing Data: (10000,)
第四步:数据可视化
plt.figure(figsize=(10,10))
for i in range(100):
plt.subplot(10,10,i+1)
plt.imshow(inp_train[i])
plt.xticks([])
plt.yticks([])
plt.xlabel(out_train[i])
plt.tight_layout()
plt.show()
第5步:将标签改成实际名称
我们已经看到了可视化,但我们也希望标签有明确的名称。下面提到的代码将达到这个目的。
Labels=['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat','Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
plt.figure(figsize=(10,10))
for i in range(100):
plt.subplot(10,10,i+1)
plt.xticks([])
plt.yticks([])
plt.imshow(inp_train[i], cmap=plt.cm.binary)
plt.xlabel(Labels[out_train[i]])
plt.tight_layout()
plt.show()
你现在可以看到,现在的可视化更容易理解了。
第六步:建立、编译和训练模型
TensorFlow和Keras模型的构建、编译和训练的代码显示如下:
my_model = tf.keras.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(10)
])
my_model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
my_model.fit(inp_train, out_train, epochs=20)
第7步:检查最终的损失和准确性
现在,我们的模型已经训练成功,现在转向计算损失,并找到创建和训练的模型的最终准确性。
loss, accuracy = my_model.evaluate(inp_test,out_test,verbose=2)
print('\nAccuracy:',accuracy*100)
在对我们的模型进行整体处理之后,我们得到的最终精确度是 88.8% 这是很不错的。
第8步:进行预测
我们已经来到了程序的最后一步,即使用我们刚刚创建和训练的模型进行预测。
prob=tf.keras.Sequential([my_model,tf.keras.layers.Softmax()])
pred=prob.predict(inp_test)
第9步:可视化最终的预测结果
对于任何分类模型来说,我们进行最后的可视化是很重要的。为了更简单,我们将对数据集的前20张图片进行可视化。
plt.figure(figsize=(20,20))
for i in range(20):
true_label,image = out_test[i],inp_test[i]
pred_label = np.argmax(pred[i])
plt.subplot(10,10,i+1)
plt.xticks([])
plt.yticks([])
plt.imshow(image, cmap=plt.cm.binary)
if pred_label == true_label:
color = 'green'
label="Correct Prediction!"
else:
color = 'red'
label="Wrong Prediction!"
plt.tight_layout()
plt.title(label,color=color)
plt.xlabel(" {} -> {} ".format(Labels[true_label],Labels[pred_label]))
谢谢你阅读本教程。我希望你通过它学到了很多东西。
学习愉快!