当前位置: 首页 > article >正文

深度学习基础案例4--构建CNN卷积神经网络实现对猴痘病的识别(测试集准确率86.5%)

  • 🍨 本文为🔗365天深度学习训练营 中的学习记录博客
  • 🍖 原作者:K同学啊

前言

  • 下一周会很忙,更新可能不及时,请大家见谅
  • 这个项目我感觉是一个很好的入门案例,但是自己测试的时候测试集准确率只比较稳定的达到了86.5%附近,说明对神经网络结构的添加还不是很熟,后期还需要多看论文积累😢​😢​😢​😢​😢​😢​😢​😢​😢​
  • 图片看着有点渗人​😨​​😨​​😨​​😨​​😨​​😨​
  • 最后说一句:看论文、复现好难啊!!!😢​😢​😢​😢​😢​

目标

  • 测试集准确率达到88%以上

结果

  • 通过调整卷积核大小、通道大小,有一次准确率达到了88.1%,但是不太稳定,最后,经过反复调整,将测试集准确率稳定在86.5%附近,没有达到预期大小,主要原因是不会设置网络结构。

环境

  • 语言环境:Python3.8.19

  • 编译器:Jupyter、VsCode

  • 深度学习环境:Pytorch

文章目录

  • 1、前期准备
    • 1、导入库
    • 2、查看数据文件夹
    • 3、显示部分图像
    • 4、导入数据
    • 5、划分数据集
    • 6、动态加载数据
  • 2、构建CNN神经网络
  • 3、模型训练
    • 1、设置超参数
    • 2、编写训练函数
    • 3、编写测试函数
    • 4、开始训练
  • 4、结果可视化
  • 5、预测
  • 6、模型保存
  • 7、总结
    • CNN神经网络总结
    • 准确率和损失率总结

1、前期准备

1、导入库

import numpy as np 
import torch 
import torch.nn as nn 
import torchvision 

import PIL, os, pathlib

device = ('cuda' if torch.cuda.is_available() else 'cpu')
device

结果:

'cuda'

2、查看数据文件夹

# 设置根目录
data_dir = './data/'
data_dir = pathlib.Path(data_dir)  # 转化为 pathlib 对象

# 查看data下的文件
data_path = data_dir.glob('*')   # 获取data文件下的所有文件夹
classNames = [str(path).split('\\')[1] for path in data_path] 
classNames

结果:

['Monkeypox', 'Others']

3、显示部分图像

import matplotlib.pyplot as plt 
from PIL import Image 

# 设置目录
image_dir = './data/Monkeypox/'
image_paths = [f for f in os.listdir(image_dir) if f.endswith((".jpg", ".png", ".jpeg"))]

# 创建画板
fig, axes = plt.subplots(3, 8, figsize=(16, 6))  # fig:画板,ases子图

for ax, img_file in zip(axes.flat, image_paths):
    img_path = os.path.join(image_dir, img_file)   # 拼接完整路径
    img = Image.open(img_path)
    ax.imshow(img)
    ax.axis('off')
    
plt.show()


在这里插入图片描述

4、导入数据

from torchvision import transforms, datasets

# 加载所有图像
total_data = './data/'

# 图像统一化
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(total_data, transform=train_transforms)   
total_data

结果:

Dataset ImageFolder
    Number of datapoints: 2142
    Root location: ./data/
    StandardTransform
Transform: Compose(
               Resize(size=[224, 224], interpolation=bilinear, max_size=None, antialias=True)
               ToTensor()
               Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
           )

5、划分数据集

  • 训练集:0.8,测试集:0.2
  • 划分顺序:随机划分
train_size = int(len(total_data) * 0.8)
test_size = len(total_data) - train_size

train_dataset, test_dataset =  torch.utils.data.random_split(total_data, [train_size, test_size])

print(train_dataset)
print(train_dataset)
<torch.utils.data.dataset.Subset object at 0x000001B7222E6EE0>
<torch.utils.data.dataset.Subset object at 0x000001B7222E6EE0>

查看训练集和测试集大小:

train_size, test_size

结果:

(1713, 429)

6、动态加载数据

# 每一批次的大小
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
                                      )
# 随机选取一张,查看图片参数
for X, y in test_dl:
    print("Shape of X [N, C, H, W]: ", X.shape)
    print("Shape of y: ", y.shape, y.dtype)
    break
Shape of X [N, C, H, W]:  torch.Size([32, 3, 224, 224])
Shape of y:  torch.Size([32]) torch.int64

2、构建CNN神经网络

import torch.nn.functional as F 

class NetWork_bn(nn.Module):
    def __init__(self):
        super(NetWork_bn, self).__init__()
        
        # 构建CNN神经网络
        self.conv1 = nn.Conv2d(in_channels=3, out_channels=24, kernel_size=3, stride=1, padding=0)
        self.bn1 = nn.BatchNorm2d(24)     # 对输出通道数据进行** 归一化 **
        self.conv2 = nn.Conv2d(in_channels=24, out_channels=24, kernel_size=3, stride=1, padding=0)
        self.bn2 = nn.BatchNorm2d(24)
        self.pool1 = nn.MaxPool2d(2, 2)
        self.conv3 = nn.Conv2d(in_channels=24, out_channels=48, kernel_size=3, stride=1, padding=0)
        self.bn3 = nn.BatchNorm2d(48)
        self.conv4 = nn.Conv2d(in_channels=48, out_channels=48, kernel_size=3, stride=1, padding=0)
        self.bn4 = nn.BatchNorm2d(48)
        self.pool2 = nn.MaxPool2d(2, 2)
        self.fc1 = nn.Linear(48 * 53 * 53, len(classNames))
        
    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, 48 * 53 * 53)   # 展开
        x = self.fc1(x)
        
        return x
# 将模型导入cuda中
model = NetWork_bn().to(device)   
model

结果:

NetWork_bn(
  (conv1): Conv2d(3, 24, kernel_size=(3, 3), stride=(1, 1))
  (bn1): BatchNorm2d(24, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
  (conv2): Conv2d(24, 24, kernel_size=(3, 3), stride=(1, 1))
  (bn2): BatchNorm2d(24, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
  (pool1): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  (conv3): Conv2d(24, 48, kernel_size=(3, 3), stride=(1, 1))
  (bn3): BatchNorm2d(48, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
  (conv4): Conv2d(48, 48, kernel_size=(3, 3), stride=(1, 1))
  (bn4): BatchNorm2d(48, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
  (pool2): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  (fc1): Linear(in_features=134832, out_features=2, bias=True)
)

3、模型训练

1、设置超参数

loss_fn = nn.CrossEntropyLoss()   # 创建损失函数
lr = 1e-4   # 设置学习率
opt = torch.optim.SGD(model.parameters(), lr=lr)   # 梯度下降方法

2、编写训练函数

def train(dataloader, model, loss_fn, optimizer):
    # 获取数据大小
    size = len(dataloader.dataset)
    # 获取批次大小
    batch_size = len(dataloader)  # 总数 / 32
    
    # 准确率和损失率
    train_acc, train_loss = 0, 0
    
    for X, y in dataloader:  # 每一批次的规格请看上面:动态加载数据哪里
        X, y = X.to(device), y.to(device)
        
        # 预测
        pred = model(X)
        # 计算损失
        loss = loss_fn(pred, y)
        
        # 梯度清零
        optimizer.zero_grad()
        # 求导
        loss.backward()
        # 梯度下降法更新
        optimizer.step()
        
        # 记录准确率和误差
        train_acc += (pred.argmax(1) == y).type(torch.float64).sum().item()  # 数据怎么存在的,要做到心中有数
        train_loss += loss.item()   # .item 获取数据项
    
    # 计算损失函数和梯度,注意:数据做到心中有数
    train_acc /= size 
    train_loss /= batch_size
    
    return train_acc, train_loss
        

3、编写测试函数

def test(dataloader, model, loss_fn):
    # 获取数据大小和批次大小
    size = len(dataloader.dataset)
    batch_size = len(dataloader)
    
    # 准确率和损失率
    test_acc, test_loss = 0, 0
    
    with torch.no_grad():
        for X, y in dataloader:
            X, y = X.to(device), y.to(device)
            
            # 预测和计算损失
            pred = model(X)
            loss = loss_fn(pred, y)
            
            test_acc += (pred.argmax(1) == y).type(torch.float64).sum().item()
            test_loss += loss.item()
     
    # 计算损失率和准确率       
    test_acc /= size
    test_loss /= batch_size
    
    return test_acc, test_loss

4、开始训练

train_acc = []
train_loss = []
test_acc = []
test_loss = []

epochs = 30

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))
Epoch: 1, Train_acc:61.0%, Train_loss:0.775, Test_acc:55.0%, Test_loss:0.784
Epoch: 2, Train_acc:68.6%, Train_loss:0.639, Test_acc:61.5%, Test_loss:0.918
Epoch: 3, Train_acc:74.0%, Train_loss:0.540, Test_acc:64.1%, Test_loss:0.703
Epoch: 4, Train_acc:78.9%, Train_loss:0.465, Test_acc:79.7%, Test_loss:0.472
Epoch: 5, Train_acc:82.4%, Train_loss:0.406, Test_acc:76.9%, Test_loss:0.515
Epoch: 6, Train_acc:83.2%, Train_loss:0.387, Test_acc:76.2%, Test_loss:0.495
Epoch: 7, Train_acc:86.3%, Train_loss:0.346, Test_acc:73.9%, Test_loss:0.532
Epoch: 8, Train_acc:87.6%, Train_loss:0.326, Test_acc:74.1%, Test_loss:0.583
Epoch: 9, Train_acc:88.9%, Train_loss:0.308, Test_acc:81.8%, Test_loss:0.421
Epoch:10, Train_acc:90.7%, Train_loss:0.282, Test_acc:81.8%, Test_loss:0.427
Epoch:11, Train_acc:91.9%, Train_loss:0.264, Test_acc:82.5%, Test_loss:0.413
Epoch:12, Train_acc:92.2%, Train_loss:0.260, Test_acc:84.1%, Test_loss:0.385
Epoch:13, Train_acc:91.9%, Train_loss:0.253, Test_acc:76.7%, Test_loss:0.551
Epoch:14, Train_acc:92.8%, Train_loss:0.241, Test_acc:83.4%, Test_loss:0.393
Epoch:15, Train_acc:92.6%, Train_loss:0.232, Test_acc:85.5%, Test_loss:0.372
Epoch:16, Train_acc:92.9%, Train_loss:0.226, Test_acc:83.2%, Test_loss:0.392
Epoch:17, Train_acc:93.6%, Train_loss:0.217, Test_acc:84.4%, Test_loss:0.376
Epoch:18, Train_acc:94.4%, Train_loss:0.207, Test_acc:83.9%, Test_loss:0.374
Epoch:19, Train_acc:94.8%, Train_loss:0.204, Test_acc:85.1%, Test_loss:0.381
Epoch:20, Train_acc:94.7%, Train_loss:0.192, Test_acc:84.4%, Test_loss:0.361
Epoch:21, Train_acc:95.2%, Train_loss:0.189, Test_acc:86.2%, Test_loss:0.358
Epoch:22, Train_acc:95.0%, Train_loss:0.184, Test_acc:85.5%, Test_loss:0.355
Epoch:23, Train_acc:95.2%, Train_loss:0.174, Test_acc:84.8%, Test_loss:0.378
Epoch:24, Train_acc:96.0%, Train_loss:0.169, Test_acc:86.0%, Test_loss:0.349
Epoch:25, Train_acc:96.4%, Train_loss:0.159, Test_acc:86.7%, Test_loss:0.355
Epoch:26, Train_acc:95.9%, Train_loss:0.166, Test_acc:86.9%, Test_loss:0.340
Epoch:27, Train_acc:96.6%, Train_loss:0.153, Test_acc:86.5%, Test_loss:0.334
Epoch:28, Train_acc:96.0%, Train_loss:0.154, Test_acc:86.5%, Test_loss:0.340
Epoch:29, Train_acc:97.3%, Train_loss:0.144, Test_acc:86.0%, Test_loss:0.335
Epoch:30, Train_acc:96.7%, Train_loss:0.150, Test_acc:86.5%, Test_loss:0.343

4、结果可视化

import matplotlib.pyplot as plt
#隐藏警告
import warnings
warnings.filterwarnings("ignore")               # 忽略警告信息
plt.rcParams['font.sans-serif']    = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False      # 用来正常显示负号
plt.rcParams['figure.dpi']         = 100        # 分辨率

epoch_range = range(epochs)

# 创建画布
plt.figure(figsize=(12 ,3))

# 第一个子图
plt.subplot(1, 2, 1)
# 画图
plt.plot(epoch_range, train_acc, label='Training Accurary')
plt.plot(epoch_range, test_acc, label='Test Accurary')
plt.legend(loc='lower right')
plt.title('Accurary')

# 第二个子图
plt.subplot(1, 2, 2)
# 画图
plt.plot(epoch_range, train_loss, label='Training Loss')
plt.plot(epoch_range, test_loss, label='Test Loss')
plt.legend(loc='upper right')
plt.title('Losss')

plt.show()


在这里插入图片描述

5、预测

from PIL import Image 

classes = list(total_data.class_to_idx)    # ./data下的文件类型

def predict_one_image(image_path, model, transform, classes):
    test_img = Image.open(image_path).convert('RGB')   # 打开文件
    # 展示打开的文件
    plt.imshow(test_img) 
    
    test_img = transform(test_img)  # 统一化数据标准
    # 压缩,去除 1
    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}')
# 指定图片进行预测
predict_one_image(image_path='./data/Monkeypox/M01_01_00.jpg',
                  model=model,
                  transform=train_transforms,
                  classes=classes)
预测结果是: Monkeypox

在这里插入图片描述

6、模型保存

# 模型保存
path = './model.pth'
torch.save(model.state_dict(), path)

# 将参数加载到model中
model.load_state_dict(torch.load(path, map_location=device))

结果:

<All keys matched successfully>

7、总结

CNN神经网络总结

  • 卷积层:对特征进行提取,影响因素主要有:通道大小的变化,卷积核大小、卷积步伐大小,填充值等,通道大小和卷积核大小对特征提取上影响很大,卷积核小,通道变大,计算就会变得复杂,当然对特征的提取也更多
  • 池化层:用于降维,卷积层数据提取完毕后,减少维度,可以更好的挖掘数据关系
  • 全连接:将维度全部进行展开,然后进行降维
  • 需要积累不同卷积模型,才能很好的提升精度

准确率和损失率总结

  • 理想状态下

    • 准确率:训练集准确率逐步提高,测试集也是,并且训练集准确率和测试集的相近
    • 损失率:训练集损失率降低,测试集也是,并且训练集损失率和测试集的相近
  • 实际(本案例)

    • 开始测试集的准确率和损失率都不稳定,后面慢慢趋向稳定
    • 准确率:后期相差百分之十
    • 损失率:后期相差0.2附近
    • 总结:如果训练后面,轮数很大,可能出现过拟合的现象

http://www.kler.cn/a/293354.html

相关文章:

  • 速盾:高防 CDN 和 CDN 的缓存机制都一样吗?
  • 基于碎纸片的拼接复原算法及MATLAB实现
  • ubuntu-desktop-24.04上手指南(更新阿里源、安装ssh、安装chrome、设置固定IP、安装搜狗输入法)
  • qt QKeySequence详解
  • 相机光学(四十二)——sony的HDR技术
  • pySpark乱码
  • 【解决bug之路】npm install node-sass(^4.14.1)连环报错解决!!!(Windows)
  • Python 语法糖:让编程更简单
  • redis的持久化RDB和AOF
  • Qt 实战(10)MVD | 10.1、MVD机制详解
  • RabbitMQ 基础架构流程 数据隔离 创建用户
  • 利用深度学习实现验证码识别-2-使用Python导出ONNX模型并在Java中调用实现验证码识别
  • 对极约束及其性质 —— 公式详细推导
  • ElementUI2.x El-Select组件 处理使用远程查找时下拉箭头丢失问题
  • 用 CSS 实现太阳系运行效果
  • XSS 漏洞检测与利用全解析:守护网络安全的关键洞察
  • 微信小程序请求数据接口封装
  • MutationObserver小试牛刀
  • 计算机基础知识-2
  • 微服务--Nacos
  • 前端进阶:JavaScript实现优雅遮罩层下的表单验证技巧
  • AI聊天应用不能上架?Google play对AI类型应用的规则要求是什么?
  • 高效实用的网站ICP备案查询接口
  • VMEMMAP分析
  • Oracle RAC关于多节点访问同一个数据的过程
  • C 语言指针与数组的深度解析