基于Pytorch和Vgg16实现图片分类

2024-03-08 09:30

本文主要是介绍基于Pytorch和Vgg16实现图片分类,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

最近在基于Pytorch框架补一些CNN的基础知识,学会自己写简单的卷积神经网络,从加载数据集到训练模型、测试模型、保存模型和输出测试结果,现在来总结一下。

首先基于Pytorch实现Vgg16网络,命名为model.py(可为其他任意名字,但是后续导入时要记得更改)

import torch
import torch.nn as nnclass VGG16(nn.Module):def __init__(self):super(VGG16, self).__init__()self.layer1 = nn.Sequential(nn.Conv2d(3, 64, 3, 1, 1),nn.BatchNorm2d(64),nn.ReLU(),nn.Conv2d(64, 64, 3, 1, 1),nn.BatchNorm2d(64),nn.ReLU(),nn.MaxPool2d(2, 2))self.layer2 = nn.Sequential(nn.Conv2d(64, 128, 3, 1, 1),nn.BatchNorm2d(128),nn.ReLU(),nn.Conv2d(128, 128, 3, 1, 1),nn.BatchNorm2d(128),nn.ReLU(),nn.MaxPool2d(2, 2))self.layer3 = nn.Sequential(nn.Conv2d(128, 256, 3, 1, 1),nn.BatchNorm2d(256),nn.ReLU(),nn.Conv2d(256, 256, 3, 1, 1),nn.BatchNorm2d(256),nn.ReLU(),nn.Conv2d(256, 256, 3, 1, 1),nn.BatchNorm2d(256),nn.ReLU(),nn.MaxPool2d(2, 2))self.layer4 = nn.Sequential(nn.Conv2d(256, 512, 3, 1, 1),nn.BatchNorm2d(512),nn.ReLU(),nn.Conv2d(512, 512, 3, 1, 1),nn.BatchNorm2d(512),nn.ReLU(),nn.Conv2d(512, 512, 3, 1, 1),nn.BatchNorm2d(512),nn.ReLU(),nn.MaxPool2d(2, 2))self.layer5 = nn.Sequential(nn.Conv2d(512, 512, 3, 1, 1),nn.BatchNorm2d(512),nn.ReLU(),nn.Conv2d(512, 512, 3, 1, 1),nn.BatchNorm2d(512),nn.ReLU(),nn.Conv2d(512, 512, 3, 1, 1),nn.BatchNorm2d(512),nn.ReLU(),nn.MaxPool2d(2, 2))self.fc1 = nn.Sequential(nn.Flatten(),nn.Linear(512, 512),nn.ReLU(),nn.Dropout())self.fc2 = nn.Sequential(nn.Linear(512, 256),nn.ReLU(),nn.Dropout())self.fc3 = nn.Linear(256, 10)def forward(self, x):x = self.layer1(x)x = self.layer2(x)x = self.layer3(x)x = self.layer4(x)x = self.layer5(x)x = self.fc1(x)x = self.fc2(x)x = self.fc3(x)return xif __name__ == '__main__':VGG16 = VGG16()input = torch.ones((64, 3, 32, 32))output = VGG16(input)print(output.shape)

然后编写训练文件,导入需要的库(有些库没有的话需要提前安装)。

import torchvision
from torch import optim
from torch.utils.data import DataLoader
import torch.nn as nn
from model import *
import matplotlib.pyplot as plt
import time

下载CIFAR10数据集,并设置batch_size,第一次运行时会自动下载,之后直接加载已经下载好的。当然也可以使用其他数据集,从官方文档https://pytorch.org/vision/stable/datasets.html可以看到有各种用于分类、分割、检测等其他视觉任务的数据集,但是为了方便学习,这里选择较小的CIFAR10数据集。

rain_data = torchvision.datasets.CIFAR10(root="data", train=True, transform=torchvision.transforms.ToTensor(),download=True)
test_data = torchvision.datasets.CIFAR10(root="data", train=False, transform=torchvision.transforms.ToTensor(),download=True)
train_dataloader = DataLoader(train_data, batch_size=64)
test_dataloader = DataLoader(test_data, batch_size=64)

创建记录文档,名字为当下时间,将训练过程和结果保存并打印出来。

t = time.strftime('%Y-%m-%d_%H-%M-%S')  # 切记中间符号不能用冒号,不然会报错
file = open('logs/{}.txt'.format(t), 'w')
train_data_size = len(train_data)
test_data_size = len(test_data)
print('The size of train_data:{}'.format(train_data_size))
file.write('The size of train_data:{}'.format(train_data_size)+'\n')
print('The size of train_data:{}'.format(test_data_size))
file.write('The size of train_data:{}'.format(test_data_size)+'\n')

创建一些中间参数,配置损失函数和优化器,也可从官方文档中选择其他损失函数torch.nn.functional — PyTorch 1.11.0 documentation和优化器torch.optim — PyTorch 1.11.0 documentation

epoch = 10
train_step = 0
test_step = 0vgg16 = VGG16()  # 实例化网络
loss_fn = nn.CrossEntropyLoss()  learning_rate = 1e-2
# optimizer = optim.SGD(vgg16.parameters(), lr=learning_rate, momentum=0.9)
optimizer = optim.Adam(vgg16.parameters(), lr=learning_rate)losses = []  # 用于存储损失值,便于后面画损失变化曲线图

开始训练

for i in range(epoch):print('-----epoch{}-----'.format(i))file.write('-----epoch{}-----'.format(i)+'\n')# 训练步骤开始vgg16.train()for data in train_dataloader:images, targets = dataoutput = vgg16(images)loss = loss_fn(output, targets)# 优化器优化模型optimizer.zero_grad()loss.backward()optimizer.step()train_step += 1if train_step % 50 == 0:print('train_step:{},loss:{}'.format(train_step, loss.item()))file.write('train_step:{},loss:{}'.format(train_step, loss.item())+'\n')losses.append(loss.item())# 测试步骤开始vgg16.eval()accuracy = 0with torch.no_grad():for data in test_dataloader:images, targets = dataoutput = vgg16(images)current_acc = (output.argmax(1) == targets).sum()accuracy += current_accacc = accuracy / test_data_sizeprint('-------eval accuracy:{}'.format(acc))file.write('-------eval accuracy:{}'.format(acc)+'\n')torch.save(tudui, 'checkpoints/vgg16_{}.pth'.format(i))print('The model has been saved')file.write('The model has been saved')file.close()

保存的记录文档和打印输出如下所示

 

画出损失曲线变化图

plt.subplot(1, 1, 1)
plt.plot(losses, label='Training Loss')
plt.title('Training Loss')
plt.legend()
plt.show()

 编写测试文件,将训练好的模型用于预测任意图片的类别。

import torch
from PIL import Image
from torchvision import transformsimage_path = 'imgs/dog.jpg'  # 随意选择一张图片进行测试
image = Image.open(image_path)
image = image.convert('RGB')
transform = transforms.Compose([transforms.Resize(32, 32), transforms.ToTensor()])  # 将图片大小改为32×32,并转换为Tensor类型
image = transform(image)classes = ['plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']model = torch.load('checkpoints/vgg16_30.pth')  # 加载训练好的模型image = torch.reshape(image, (1, 3, 32, 32))
model.eval()
with torch.no_grad():output = model(image)
index = output.argmax(1)
pred = classes[index]
print(pred)

                                 

这篇关于基于Pytorch和Vgg16实现图片分类的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/786684

相关文章

使用Python实现IP地址和端口状态检测与监控

《使用Python实现IP地址和端口状态检测与监控》在网络运维和服务器管理中,IP地址和端口的可用性监控是保障业务连续性的基础需求,本文将带你用Python从零打造一个高可用IP监控系统,感兴趣的小伙... 目录概述:为什么需要IP监控系统使用步骤说明1. 环境准备2. 系统部署3. 核心功能配置系统效果展

Python实现微信自动锁定工具

《Python实现微信自动锁定工具》在数字化办公时代,微信已成为职场沟通的重要工具,但临时离开时忘记锁屏可能导致敏感信息泄露,下面我们就来看看如何使用Python打造一个微信自动锁定工具吧... 目录引言:当微信隐私遇到自动化守护效果展示核心功能全景图技术亮点深度解析1. 无操作检测引擎2. 微信路径智能获

Python中pywin32 常用窗口操作的实现

《Python中pywin32常用窗口操作的实现》本文主要介绍了Python中pywin32常用窗口操作的实现,pywin32主要的作用是供Python开发者快速调用WindowsAPI的一个... 目录获取窗口句柄获取最前端窗口句柄获取指定坐标处的窗口根据窗口的完整标题匹配获取句柄根据窗口的类别匹配获取句

在 Spring Boot 中实现异常处理最佳实践

《在SpringBoot中实现异常处理最佳实践》本文介绍如何在SpringBoot中实现异常处理,涵盖核心概念、实现方法、与先前查询的集成、性能分析、常见问题和最佳实践,感兴趣的朋友一起看看吧... 目录一、Spring Boot 异常处理的背景与核心概念1.1 为什么需要异常处理?1.2 Spring B

判断PyTorch是GPU版还是CPU版的方法小结

《判断PyTorch是GPU版还是CPU版的方法小结》PyTorch作为当前最流行的深度学习框架之一,支持在CPU和GPU(NVIDIACUDA)上运行,所以对于深度学习开发者来说,正确识别PyTor... 目录前言为什么需要区分GPU和CPU版本?性能差异硬件要求如何检查PyTorch版本?方法1:使用命

Python位移操作和位运算的实现示例

《Python位移操作和位运算的实现示例》本文主要介绍了Python位移操作和位运算的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录1. 位移操作1.1 左移操作 (<<)1.2 右移操作 (>>)注意事项:2. 位运算2.1

如何在 Spring Boot 中实现 FreeMarker 模板

《如何在SpringBoot中实现FreeMarker模板》FreeMarker是一种功能强大、轻量级的模板引擎,用于在Java应用中生成动态文本输出(如HTML、XML、邮件内容等),本文... 目录什么是 FreeMarker 模板?在 Spring Boot 中实现 FreeMarker 模板1. 环

Qt实现网络数据解析的方法总结

《Qt实现网络数据解析的方法总结》在Qt中解析网络数据通常涉及接收原始字节流,并将其转换为有意义的应用层数据,这篇文章为大家介绍了详细步骤和示例,感兴趣的小伙伴可以了解下... 目录1. 网络数据接收2. 缓冲区管理(处理粘包/拆包)3. 常见数据格式解析3.1 jsON解析3.2 XML解析3.3 自定义

SpringMVC 通过ajax 前后端数据交互的实现方法

《SpringMVC通过ajax前后端数据交互的实现方法》:本文主要介绍SpringMVC通过ajax前后端数据交互的实现方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价... 在前端的开发过程中,经常在html页面通过AJAX进行前后端数据的交互,SpringMVC的controll

Spring Security自定义身份认证的实现方法

《SpringSecurity自定义身份认证的实现方法》:本文主要介绍SpringSecurity自定义身份认证的实现方法,下面对SpringSecurity的这三种自定义身份认证进行详细讲解,... 目录1.内存身份认证(1)创建配置类(2)验证内存身份认证2.JDBC身份认证(1)数据准备 (2)配置依