卷积神经网络(CNN)服装图像分类

卷积神经网络(CNN)服装图像分类

## 1. 设置GPU

import tensorflow as tf 
gpus=tf.config.list_physical_devices("GPU")
if gpus:
    gpu0 =gpus[0]
    tf.config.experimental.set_memory_growth(gpu0,True)
    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. 归一化

train_images,test_images=train_images/255.0 ,test_images/255.0
train_images.shape,test_images.shape,train_labels.shape,test_labels.shape

在这里插入图片描述

## 4.调整图片格式

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

## 5. 可视化

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=plt.cm.binary)
    plt.xlabel(class_names[train_labels[i]])
plt.show()

在这里插入图片描述

# 二、构建CNN网络

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()  # 打印网络结构

在这里插入图片描述

# 三、编译

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))
 

在这里插入图片描述

# 五、预测

plt.imshow(test_images[1])

在这里插入图片描述

import numpy as np
 
pre = model.predict(test_images)
print(class_names[np.argmax(pre[1])])
 

在这里插入图片描述

# 六、模型评估

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
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
神经网络(Convolutional Neural Network,CNN)是一类包含卷计算且具有深度结构的前馈神经网络,是深度学习中应用最广泛的一种模型之一。下面以一个基于PyTorch实现的CNN实例应用为例,详细说明CNN的实现过程。 ## 数据集 本例使用的是Fashion-MNIST数据集,该数据集包含了10个类别的服装图片,每个类别包含6000张28x28像素的灰度图像,其中训练集包含了60000张图片,测试集包含了10000张图片。可以使用PyTorch内置的函数`torchvision.datasets.FashionMNIST`来获取该数据集。 ## 模型结构 本例使用了一个较为简单的CNN模型,包含两个卷层和两个全连接层,具体结构如下: ``` CNN( (conv1): Conv2d(1, 16, kernel_size=(5, 5), stride=(1, 1)) (pool1): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False) (conv2): Conv2d(16, 32, kernel_size=(5, 5), stride=(1, 1)) (pool2): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False) (fc1): Linear(in_features=512, out_features=128, bias=True) (fc2): Linear(in_features=128, out_features=10, bias=True) ) ``` 其中`Conv2d`表示卷层,`MaxPool2d`表示最大池化层,`Linear`表示全连接层。`conv1`用于提取图像的低级特征,`pool1`用于降低特征图的分辨率,`conv2`用于进一步提取图像的高级特征,`pool2`再次降低特征图的分辨率,最后通过两个全连接层进行分类。 ## 实现过程 ### 1. 导入相关库 ``` import torch import torch.nn as nn import torch.optim as optim import torchvision import torchvision.transforms as transforms ``` ### 2. 加载数据集 ``` transform = transforms.Compose( [transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))]) trainset = torchvision.datasets.FashionMNIST(root='./data', train=True, download=True, transform=transform) trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True, num_workers=2) testset = torchvision.datasets.FashionMNIST(root='./data', train=False, download=True, transform=transform) testloader = torch.utils.data.DataLoader(testset, batch_size=64, shuffle=False, num_workers=2) ``` ### 3. 定义CNN模型 ``` class CNN(nn.Module): def __init__(self): super(CNN, self).__init__() self.conv1 = nn.Conv2d(1, 16, kernel_size=5) self.pool1 = nn.MaxPool2d(kernel_size=2) self.conv2 = nn.Conv2d(16, 32, kernel_size=5) self.pool2 = nn.MaxPool2d(kernel_size=2) self.fc1 = nn.Linear(512, 128) self.fc2 = nn.Linear(128, 10) def forward(self, x): x = self.conv1(x) x = nn.functional.relu(x) x = self.pool1(x) x = self.conv2(x) x = nn.functional.relu(x) x = self.pool2(x) x = x.view(-1, 512) x = self.fc1(x) x = nn.functional.relu(x) x = self.fc2(x) return x net = CNN() ``` ### 4. 定义损失函数和优化器 ``` criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9) ``` ### 5. 训练模型 ``` for epoch in range(10): # 进行10轮训练 running_loss = 0.0 for i, data in enumerate(trainloader, 0): inputs, labels = data optimizer.zero_grad() # 梯度清零 outputs = net(inputs) # 前向传播 loss = criterion(outputs, labels) # 计算损失函数 loss.backward() # 反向传播 optimizer.step() # 更新参数 running_loss += loss.item() if i % 200 == 199: # 每200个batch输出一次损失函数 print('epoch[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, running_loss / 200)) running_loss = 0.0 ``` ### 6. 测试模型 ``` correct = 0 total = 0 with torch.no_grad(): for data in testloader: images, labels = data outputs = net(images) _, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted == labels).sum().item() print('Accuracy on test set: %d %%' % (100 * correct / total)) ``` 以上就是一个基于PyTorch实现的CNN模型的实现过程,如果有需要可以根据实际情况进行修改和优化。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

AI自修室

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

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

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

打赏作者

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

抵扣说明:

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

余额充值