DAY3-深度学习100例-卷积神经网络(CNN)服装图像分类

本文介绍了如何使用TensorFlow构建卷积神经网络(CNN)对FashionMNIST数据集进行衣物分类,涵盖了GPU设置、数据预处理、模型构建、编译、训练与评估的全过程,展示了从数据导入到模型精度测试的详细步骤。
摘要由CSDN通过智能技术生成


活动地址:CSDN21天学习挑战赛

一、前期工作

1、设置GPU

import tensorflow as tf
gpus = tf.config.list_physical_devices("GPU")

if gpus:
    gpu0 = gpus[0]                                        #如果有多个GPU,仅使用第0个GPU
    tf.config.experimental.set_memory_growth(gpu0, True)  #设置GPU显存用量按需使用
    tf.config.set_visible_devices([gpu0],"GPU")

2、导入数据

import tensorflow as tf
from tensorflow.keras import datasets, layers, models
import matplotlib.pyplot as plt

(train_images, train_labels), (test_images, test_labels) = datasets.fashion_mnist.load_data()

3、归一化

# 将像素的值标准化至0到1的区间内。
train_images, test_images = train_images / 255.0, test_images / 255.0

train_images.shape,test_images.shape,train_labels.shape,test_labels.shape

加载数据集会返回四个Numpy数组:

train_images和train_labels数组是训练集,用于模型学习的数据;
test_images和test_labels数组是测试集,用于对模型进行测试。

图像是28 * 28的Numpy数组,像素值介于0-255之间。标签是整数数组,介于0-9之间。这些标签对应于图像所代表的服装类:
在这里插入图片描述

4、可视化

class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
               'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']

plt.figure(figsize=(20,10))
for i in range(20):
    plt.subplot(5,10,i+1)
    plt.xticks([])
    plt.yticks([])
    plt.grid(False)
    plt.imshow(train_images[i], cmap='gray')
    plt.xlabel(class_names[train_labels[i]])
plt.show()

在这里插入图片描述

5、调整图片格式

#调整数据到我们需要的格式
train_images = train_images.reshape((60000, 28, 28, 1))
test_images = test_images.reshape((10000, 28, 28, 1))

train_images.shape,test_images.shape,train_labels.shape,test_labels.shape

二、构建CNN网络

卷积神经网络 (CNN) 的输入是张量(Tensor)形式的(image height, image. width, color. channels), 包含了图像高度、宽度及颜色信息。不需要输入batch size。color channels 为(R,G,B)分别对应RGB的三个颜色通道(color channel)。在此示例中,我们的CNN输入,fashion mnist 数据集中的图片,形状是(28, 28,1) 即灰度图像。我们需要在声明第一层时将形状赋值给参数input_shape。

model = models.Sequential([
    layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)), #卷积层1,卷积核3*3
    layers.MaxPooling2D((2, 2)),                   #池化层1,2*2采样
    layers.Conv2D(64, (3, 3), activation='relu'),  #卷积层2,卷积核3*3
    layers.MaxPooling2D((2, 2)),                   #池化层2,2*2采样
    layers.Conv2D(64, (3, 3), activation='relu'),  #卷积层3,卷积核3*3
    
    layers.Flatten(),                      #Flatten层,连接卷积层与全连接层
    layers.Dense(64, activation='relu'),   #全连接层,特征进一步提取
    layers.Dense(10)                       #输出层,输出预期结果
])

model.summary()  # 打印网络结构

在这里插入图片描述
在这里插入图片描述

三、编译

在准备对模型进行训练之前,还需要再对其进行一些设置。以下内容是在模型的编译步骤中添加的:

●损失函数(loss) :用于测量模型在训练期间的准确率。我们希望最小化此函数,以便将模型“引导”到正确的方向上。

●优化器(optimizer) :决定模型如何根据其看到的数据和自身的损失函数进行更新。

●指标(metrics) :用于监控训练和测试步骤。以下示例使用了准确率,即被正确分类的图像的比率。

model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])

四、训练模型

history = model.fit(train_images, train_labels, epochs=10, 
                    validation_data=(test_images, test_labels))

在这里插入图片描述

五、预测

预测结果是一个包含10个数字的数组。它们代表模型对10种不同服装中每种服装的“置信度”,我们可以看到哪个标签的置信度值最大。

plt.imshow(test_images[1].reshape(28,28))

在这里插入图片描述

import numpy as np

pre = model.predict(test_images)
print(class_names[np.argmax(pre[1])])
Pullover

六、模型评估

plt.plot(history.history['accuracy'], label='accuracy')
plt.plot(history.history['val_accuracy'], label = 'val_accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.ylim([0.5, 1])
plt.legend(loc='lower right')
plt.show()

test_loss, test_acc = model.evaluate(test_images,  test_labels, verbose=2)

在这里插入图片描述

print("测试准确率为:",test_acc)
测试准确率为: 0.9017000198364258

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Never give up

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值