Pytorch入门实战 P4-猴痘图片,精确度提升

2024-03-29 20:12

本文主要是介绍Pytorch入门实战 P4-猴痘图片,精确度提升,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

目录

一、前言:

二、前期准备:

1、设备查看

2、导入收集到的数据集

3、数据预处理

4、划分数据集(8:2)

5、加载数据集

三、搭建神经网络

四、训练模型

1、设置超参数

2、编写训练函数

3、编写测试函数

4、正式训练

五、可视化结果

六、预测

1、预测函数

2、指定图片进行预测

七、模型保存

八、运行结果展示:

①使用原有的网络模型,测试集的精确度基本上在82%左右。

②在原有网络模型的基础上,添加了relu激活函数,

③减小学习率,

④增大学习率,


  • 🍨 本文为🔗365天深度学习训练营 中的学习记录博客
  • 🍖 原作者:K同学啊 | 接辅导、项目定制

一、前言:

本篇博文,主要使用猴痘数据集,来训练模型,大部分的代码还是之前的很类似,不同的地方在意,使用的模型参数不同,模型也都是类似的。这篇文章里面,你可以学会如何保存训练好的模型,如何使用保存的的模型进行预测。

如以往一样,可以先大概看下目录,你的脑海会有大概得流程。

二、前期准备:

1、设备查看

# 1、设备相关
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
print(device)

2、导入收集到的数据集

我的数据集文件夹是这样的:

①一个是带有猴痘的图片的文件夹;②一个是其他痘的文件夹;

# 2、导入数据
data_dir = './data'
data_dir = pathlib.Path(data_dir)  # 获取到文件data的名称data_paths = list(data_dir.glob('*'))  # 获取到文件夹data下面子文件夹的名称  [PosixPath('data/Others'), PosixPath('data/Monkeypox')]
classNames = [str(path).split('/')[1] for path in data_paths]  # 获取到子文件夹的名称  ['Others', 'Monkeypox']

3、数据预处理

# 3、数据处理
train_transforms = transforms.Compose([transforms.Resize([224, 224]),transforms.ToTensor(),transforms.Normalize(mean=[0.485, 0.456, 0.406],std=[0.229, 0.224, 0.225])
])total_data = datasets.ImageFolder('./data',transform=train_transforms)
# print(total_data.class_to_idx)  # {'Monkeypox': 0, 'Others': 1}  total_data.class_to_idx 是一个存储了数据集类别和对应索引的字典。

4、划分数据集(8:2)

# 4、划分数据集
train_size = int(0.8*len(total_data))
test_size = len(total_data) - train_size
train_dataset, test_dataset = torch.utils.data.random_split(total_data,[train_size, test_size])
# print(len(train_dataset), len(test_dataset))   # 1713  429

5、加载数据集

# 5、加载数据集
batch_size = 32
train_dl = torch.utils.data.DataLoader(train_dataset,batch_size=batch_size,shuffle=True,num_workers=1)
test_dl = torch.utils.data.DataLoader(test_dataset,batch_size=batch_size,shuffle=True,num_workers=1)
print('准备工作结束。。。。')

三、搭建神经网络

网络图如下:

# 猴痘的模型
class Network_bn(nn.Module):def __init__(self):super(Network_bn, self).__init__()'''默认stride为1;  padding为0'''self.conv1 = nn.Conv2d(in_channels=3, out_channels=12, kernel_size=5, stride=1, padding=0)self.bn1 = nn.BatchNorm2d(12)self.conv2 = nn.Conv2d(in_channels=12, out_channels=12, kernel_size=5, stride=1, padding=0)self.bn2 = nn.BatchNorm2d(12)self.pool1 = nn.MaxPool2d(2, 2)self.conv3 = nn.Conv2d(in_channels=12, out_channels=24, kernel_size=5, stride=1, padding=0)self.bn3 = nn.BatchNorm2d(24)self.conv4 = nn.Conv2d(in_channels=24, out_channels=24, kernel_size=5, stride=1, padding=0)self.bn4 = nn.BatchNorm2d(24)self.pool2 = nn.MaxPool2d(2, 2)self.fc = nn.Linear(24*50*50, 2)self.relu = nn.ReLU(inplace=True)def forward(self, x):x = F.relu(self.bn1(self.conv1(x)))x = F.relu(self.bn2(self.conv2(x)))x = self.pool1(x)x = F.relu(self.bn3(self.conv3(x)))x = F.relu(self.bn4(self.conv4(x)))x = self.pool2(x)x = x.view(-1, 24*50*50)x = self.fc(x)x = self.relu(x)return xmodel = Network_bn().to(device)
print(model)

四、训练模型

1、设置超参数

# 三、训练模型
# 1、 设置超参数
loss_fn = nn.CrossEntropyLoss()  # 创建损失函数
learn_rate = 1e-4  # 学习率
opt = torch.optim.SGD(model.parameters(), lr=learn_rate)

2、编写训练函数

# 2、编写训练函数
def train(dataloader, model, loss_fn, optimizer):size = len(dataloader.dataset)   # 训练集大小num_batches = len(dataloader)    # 批次数目train_acc, train_loss = 0, 0for X, y in dataloader:  # 获取图片及其标签X, y = X.to(device), y.to(device)# 计算预测误差pred = model(X)   # 网络输出loss = loss_fn(pred, y)  # 计算网络输出与真实值之间的差距。# 反向传播optimizer.zero_grad()  # grad属性归零loss.backward()   # 反向传播optimizer.step()  # 每一步自动更新# 记录acc与losstrain_acc += (pred.argmax(1) == y).type(torch.float).sum().item()train_loss += loss.item()train_acc /= sizetrain_loss /= num_batchesreturn train_acc, train_loss

3、编写测试函数

# 3、 编写测试函数def test(dataloader, model, loss_fn):size = len(dataloader.dataset)  # 测试集大小num_batches = len(dataloader)  # 批次数目test_acc, test_loss = 0, 0# 当不进行训练时,停止梯度更新,节省计算内存消耗with torch.no_grad():for imgs, target in dataloader:imgs, target = imgs.to(device), target.to(device)# 计算损失target_pred = model(imgs)loss = loss_fn(target_pred, target)test_acc += (target_pred.argmax(1) == target).type(torch.float).sum().item()test_loss += loss.item()test_acc /= sizetest_loss /= num_batchesreturn test_acc, test_loss

4、正式训练

# 正式训练
epochs = 20
train_loss = []
train_acc = []
test_loss = []
test_acc = []for epoch in range(epochs):model.train()epoch_train_acc, epoch_train_loss = train(train_dl, model, loss_fn, opt)model.eval()epoch_test_acc, epoch_test_loss = test(test_dl, model, loss_fn)train_acc.append(epoch_train_acc)train_loss.append(epoch_train_loss)test_acc.append(epoch_test_acc)test_loss.append(epoch_test_loss)template = 'Epoch:{:2d}, Train_acc:{:.1f}%, Train_loss:{:.3f}, Test_acc:{:.1f}%, Test_loss:{:.3f}'print(template.format(epoch+1, epoch_train_acc*100, epoch_train_loss, epoch_test_acc*100, epoch_test_loss))
print('Done')

五、可视化结果

# 结果可视化
warnings.filterwarnings('ignore')  # 忽略警告信息
plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号
plt.rcParams['figure.dpi'] = 100  # 分辨率epochs_range = range(epochs)plt.figure(figsize=(12,3))
plt.subplot(1, 2, 1)
plt.plot(epochs_range, train_acc, label="Training Acc")
plt.plot(epochs_range, test_acc, label="Test Acc")
plt.legend(loc='lower right')
plt.title('Training and Validation Acc')plt.subplot(1, 2, 2)
plt.plot(epochs_range, train_loss, label="Training Loss")
plt.plot(epochs_range, test_loss, label='Test Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')plt.savefig("/data/jupyter/deepinglearning_train_folder/p04_weather/resultImg.jpg")
plt.show()

六、预测

1、预测函数

classes = list(total_data.class_to_idx)
print('classes:', classes)# 预测训练集中的某张图片
predict_one_image(image_path='./data/Monkeypox/M01_01_00.jpg',model=model,transform=train_transforms,classes=classes)

2、指定图片进行预测

# 预测函数
def predict_one_image(image_path, model, transform, classes):test_img = Image.open(image_path).convert('RGB')test_img = transform(test_img)img = test_img.to(device).unsqueeze(0)model.eval()output = model(img)_, pred = torch.max(output, 1)pred_class = classes[pred]print(f'预测结果是:{pred_class}')

七、模型保存

# 模型保存
PATH = './model.pth'  # 保存的模型
torch.save(model.state_dict(), PATH)# 将参数加载到model当中
model.load_state_dict(torch.load(PATH, map_location=device))

(我是在具有GPU的服务器上训练的模型)

八、运行结果展示:

①使用原有的网络模型,测试集的精确度基本上在82%左右。

②在原有网络模型的基础上,添加了relu激活函数,

可使得精度提高2%左右。但是训练精度减少了。

③减小学习率,

使得测试精度,直线下降

④增大学习率,

也可以使得测试精确度提高2%左右,还会使得训练的精确度更好,达到98.7%

这篇关于Pytorch入门实战 P4-猴痘图片,精确度提升的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

SQL Server跟踪自动统计信息更新实战指南

《SQLServer跟踪自动统计信息更新实战指南》本文详解SQLServer自动统计信息更新的跟踪方法,推荐使用扩展事件实时捕获更新操作及详细信息,同时结合系统视图快速检查统计信息状态,重点强调修... 目录SQL Server 如何跟踪自动统计信息更新:深入解析与实战指南 核心跟踪方法1️⃣ 利用系统目录

Spring WebClient从入门到精通

《SpringWebClient从入门到精通》本文详解SpringWebClient非阻塞响应式特性及优势,涵盖核心API、实战应用与性能优化,对比RestTemplate,为微服务通信提供高效解决... 目录一、WebClient 概述1.1 为什么选择 WebClient?1.2 WebClient 与

java中pdf模版填充表单踩坑实战记录(itextPdf、openPdf、pdfbox)

《java中pdf模版填充表单踩坑实战记录(itextPdf、openPdf、pdfbox)》:本文主要介绍java中pdf模版填充表单踩坑的相关资料,OpenPDF、iText、PDFBox是三... 目录准备Pdf模版方法1:itextpdf7填充表单(1)加入依赖(2)代码(3)遇到的问题方法2:pd

PyTorch中的词嵌入层(nn.Embedding)详解与实战应用示例

《PyTorch中的词嵌入层(nn.Embedding)详解与实战应用示例》词嵌入解决NLP维度灾难,捕捉语义关系,PyTorch的nn.Embedding模块提供灵活实现,支持参数配置、预训练及变长... 目录一、词嵌入(Word Embedding)简介为什么需要词嵌入?二、PyTorch中的nn.Em

在IntelliJ IDEA中高效运行与调试Spring Boot项目的实战步骤

《在IntelliJIDEA中高效运行与调试SpringBoot项目的实战步骤》本章详解SpringBoot项目导入IntelliJIDEA的流程,教授运行与调试技巧,包括断点设置与变量查看,奠定... 目录引言:为良驹配上好鞍一、为何选择IntelliJ IDEA?二、实战:导入并运行你的第一个项目步骤1

Spring Boot3.0新特性全面解析与应用实战

《SpringBoot3.0新特性全面解析与应用实战》SpringBoot3.0作为Spring生态系统的一个重要里程碑,带来了众多令人兴奋的新特性和改进,本文将深入解析SpringBoot3.0的... 目录核心变化概览Java版本要求提升迁移至Jakarta EE重要新特性详解1. Native Ima

Spring Boot 与微服务入门实战详细总结

《SpringBoot与微服务入门实战详细总结》本文讲解SpringBoot框架的核心特性如快速构建、自动配置、零XML与微服务架构的定义、演进及优缺点,涵盖开发环境准备和HelloWorld实战... 目录一、Spring Boot 核心概述二、微服务架构详解1. 微服务的定义与演进2. 微服务的优缺点三

SpringBoot集成MyBatis实现SQL拦截器的实战指南

《SpringBoot集成MyBatis实现SQL拦截器的实战指南》这篇文章主要为大家详细介绍了SpringBoot集成MyBatis实现SQL拦截器的相关知识,文中的示例代码讲解详细,有需要的小伙伴... 目录一、为什么需要SQL拦截器?二、MyBATis拦截器基础2.1 核心接口:Interceptor

从入门到精通详解LangChain加载HTML内容的全攻略

《从入门到精通详解LangChain加载HTML内容的全攻略》这篇文章主要为大家详细介绍了如何用LangChain优雅地处理HTML内容,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录引言:当大语言模型遇见html一、HTML加载器为什么需要专门的HTML加载器核心加载器对比表二

从入门到进阶讲解Python自动化Playwright实战指南

《从入门到进阶讲解Python自动化Playwright实战指南》Playwright是针对Python语言的纯自动化工具,它可以通过单个API自动执行Chromium,Firefox和WebKit... 目录Playwright 简介核心优势安装步骤观点与案例结合Playwright 核心功能从零开始学习