学习目的:学会调整模块提升准确率

一、 前期准备

关于环境

  • 语言环境:Python3.13
  • 编译器:vsCode
  • 深度学习环境:torch==2.11.0+cu130;torchvision==0.26.0+cu130

1.设置GPU

设置分析环境:

import torch
import torch.nn as nn
import torchvision.transforms as transforms
import torchvision
from torchvision import transforms, datasets

import os,PIL,pathlib

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

device

代码运行结果:

2. 导入数据

由于本次是本地数据,因此不需要有download代码,只需读取路径里的数据集即可

import os,PIL,random,pathlib

data_dir = './4-data/'
data_dir = pathlib.Path(data_dir)

data_paths = list(data_dir.glob('*'))
classeNames = [str(path).split("\\")[1] for path in data_paths]
classeNames

代码解读:

在进行图片识别前,为提高模型的泛化能力,一般要对图片进行统一的预处理以保证图片的基本格式一致

模型要求输入尺寸一致 → Resize。

PyTorch 模型要求输入是张量 → ToTensor。

标准化有助于模型更快收敛 → Normalize。

mean与std数值是怎么来的?

这些均值和标准差是通过计算ImageNet数据集中所有训练图像的RGB通道均值和标准差得出的。具体计算过程如下:

获取ImageNet数据集:ImageNet包含120万张训练图像,每张图像通常具有RGB三个通道。
计算均值(Mean):
遍历所有图像,分别计算每个通道(R、G、B)的像素值平均值,得到:
Red 通道均值 ≈ 0.485
Green 通道均值 ≈ 0.456
Blue 通道均值 ≈ 0.406
计算标准差(Standard Deviation):
遍历所有图像,计算每个通道的像素值标准差,得到:
Red 通道标准差 ≈ 0.229
Green 通道标准差 ≈ 0.224
Blue 通道标准差 ≈ 0.225

代码运行结果:

3.图片预处理

total_datadir = './4-data/'

# 关于transforms.Compose的更多介绍可以参考:https://blog.csdn.net/qq_38251616/article/details/124878863
train_transforms = transforms.Compose([
    transforms.Resize([224, 224]),  # 将输入图片resize成统一尺寸
    transforms.ToTensor(),          # 将PIL Image或numpy.ndarray转换为tensor,并归一化到[0,1]之间
    transforms.Normalize(           # 标准化处理-->转换为标准正太分布(高斯分布),使模型更容易收敛
        mean=[0.485, 0.456, 0.406], 
        std=[0.229, 0.224, 0.225])  # 其中 mean=[0.485,0.456,0.406]与std=[0.229,0.224,0.225] 从数据集中随机抽样计算得到的。
])

total_data = datasets.ImageFolder(total_datadir,transform=train_transforms)
total_data

代码运行结果:

total_data.class_to_idx

代码解读:

total_data.class_to_idx是一个存储了数据集类别和对应索引的字典。在PyTorch的ImageFolder数据加载器中,根据数据集文件夹的组织结构,每个文件夹代表一个类别,class_to_idx字典将每个类别名称映射为一个数字索引。

具体来说,如果数据集文件夹包含两个子文件夹,比如Monkeypox和Others,class_to_idx字典将返回类似以下的映射关系:{'Monkeypox': 0, 'Others': 1}

相当于将0赋值于'Monkeypox';1赋值于'Others'

代码运行结果

5.划分数据集

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])
train_dataset, test_dataset

代码运行结果:

train_size,test_size

代码运行结果:

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

代码运行结果:

根据运行结果可知图片以32张为一组,每一张图片的形状为[3,224,224]

二、构建简单的CNN网络
对于一般的CNN网络来说,都是由特征提取网络和分类网络构成,其中特征提取网络用于提取图片的特征,分类网络用于将图片进行分类。

⭐1. torch.nn.Conv2d()详解

函数原型:torch.nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, padding_mode='zeros', device=None, dtype=None)

关键参数说明:

in_channels ( int ) – 输入图像中的通道数
out_channels ( int ) – 卷积产生的通道数
kernel_size ( int or tuple ) – 卷积核的大小
stride ( int or tuple , optional ) -- 卷积的步幅。默认值:1
padding ( int , tuple或str , optional ) – 添加到输入的所有四个边的填充。默认值:0
dilation (int or tuple, optional) - 扩张操作:控制kernel点(卷积核点)的间距,默认值:1。
groups(int,可选):将输入通道分组成多个子组,每个子组使用一组卷积核来处理。默认值为 1,表示不进行分组卷积。
padding_mode (字符串,可选) – 'zeros', 'reflect', 'replicate'或'circular'. 默认:'zeros'

2. torch.nn.Linear()详解

函数原型:torch.nn.Linear(in_features, out_features, bias=True, device=None, dtype=None)

关键参数说明:

in_features:每个输入样本的大小
out_features:每个输出样本的大小

⭐3. torch.nn.MaxPool2d()详解

函数原型:torch.nn.MaxPool2d(kernel_size, stride=None, padding=0, dilation=1, return_indices=False, ceil_mode=False)

关键参数说明:

kernel_size:最大的窗口大小
stride:窗口的步幅,默认值为kernel_size
padding:填充值,默认为0
dilation:控制窗口中元素步幅的参数

import torch.nn.functional as F

class Network_bn(nn.Module):
    def __init__(self):
        super(Network_bn, self).__init__()
     
        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.pool = nn.MaxPool2d(2,2)
        self.conv4 = nn.Conv2d(in_channels=12, out_channels=24, kernel_size=5, stride=1, padding=0)
        self.bn4 = nn.BatchNorm2d(24)
        self.conv5 = nn.Conv2d(in_channels=24, out_channels=24, kernel_size=5, stride=1, padding=0)
        self.bn5 = nn.BatchNorm2d(24)
        self.fc1 = nn.Linear(24*50*50, len(classeNames))

    def forward(self, x):
        x = F.relu(self.bn1(self.conv1(x)))      
        x = F.relu(self.bn2(self.conv2(x)))     
        x = self.pool(x)                        
        x = F.relu(self.bn4(self.conv4(x)))     
        x = F.relu(self.bn5(self.conv5(x)))  
        x = self.pool(x)                        
        x = x.view(-1, 24*50*50)
        x = self.fc1(x)

        return x

device = "cuda" if torch.cuda.is_available() else "cpu"
print("Using {} device".format(device))

model = Network_bn().to(device)
model

代码运行结果:

三、 训练模型

1. 设置超参数

loss_fn    = nn.CrossEntropyLoss() # 创建损失函数
learn_rate = 1e-4 # 学习率
opt        = torch.optim.SGD(model.parameters(),lr=learn_rate)

2. 编写训练函数

# 训练循环
def train(dataloader, model, loss_fn, optimizer):
    size = len(dataloader.dataset)  # 训练集的大小,一共60000张图片
    num_batches = len(dataloader)   # 批次数目,1875(60000/32)

    train_loss, train_acc = 0, 0  # 初始化训练损失和正确率
    
    for X, y in dataloader:  # 获取图片及其标签
        X, y = X.to(device), y.to(device)
        
        # 计算预测误差
        pred = model(X)          # 网络输出
        loss = loss_fn(pred, y)  # 计算网络输出和真实值之间的差距,targets为真实值,计算二者差值即为损失
        
        # 反向传播
        optimizer.zero_grad()  # grad属性归零
        loss.backward()        # 反向传播
        optimizer.step()       # 每一步自动更新
        
        # 记录acc与loss
        train_acc  += (pred.argmax(1) == y).type(torch.float).sum().item()
        train_loss += loss.item()
            
    train_acc  /= size
    train_loss /= num_batches

    return train_acc, train_loss

3. 编写测试函数

测试函数和训练函数大致相同,但是由于不进行梯度下降对网络权重进行更新,所以不需要传入优化器

def test (dataloader, model, loss_fn):
    size        = len(dataloader.dataset)  # 测试集的大小,一共10000张图片
    num_batches = len(dataloader)          # 批次数目,313(10000/32=312.5,向上取整)
    test_loss, test_acc = 0, 0
    
    # 当不进行训练时,停止梯度更新,节省计算内存消耗
    with torch.no_grad():
        for imgs, target in dataloader:
            imgs, target = imgs.to(device), target.to(device)
            
            # 计算loss
            target_pred = model(imgs)
            loss        = loss_fn(target_pred, target)
            
            test_loss += loss.item()
            test_acc  += (target_pred.argmax(1) == target).type(torch.float).sum().item()

    test_acc  /= size
    test_loss /= num_batches

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

代码运行结果:

四、 结果可视化

1. Loss与Accuracy图

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        #分辨率

from datetime import datetime
current_time = datetime.now() # 获取当前时间

epochs_range = range(epochs)

plt.figure(figsize=(12, 3))
plt.subplot(1, 2, 1)

plt.plot(epochs_range, train_acc, label='Training Accuracy')
plt.plot(epochs_range, test_acc, label='Test Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')
plt.xlabel(current_time) # 打卡请带上时间戳,否则代码截图无效

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.show()

可视化:

未满足学习要求:测试集accuracy到达88%

五、提高模型效能

根据学习要求:调整网络结构使测试集accuracy到达88%)。

1.网络结构调整

对于如何调整网络结构提升模型准确率,deep seek回答:

  1. 增加网络深度:更多的卷积层可以提取更丰富的特征。

  2. 使用更小的卷积核(3×3)并添加padding:保持特征图尺寸,避免过早缩小,同时堆叠多个小核能增加非线性。

  3. 增加通道数:让每一层学习更多的特征模式。

  4. 调整Dropout比例:根据过拟合程度适当增加或减少。

  5. 使用全局平均池化代替展平:大幅减少全连接层参数,降低过拟合风险。

  6. 添加批归一化(已有) 和适当的激活函数。

根据意见,我选择了增加网络深度、增加通道数

加入Dropout正则化并根据过拟合程度适当增加或减少比例,先后尝试了0.3、0.4、0.5、0.6。

import torch.nn.functional as F

class Network_bn(nn.Module):
    def __init__(self):
        super(Network_bn, self).__init__()
        
        self.conv1 = nn.Conv2d(in_channels=3, out_channels=16, kernel_size=5, stride=1, padding=0)
        self.bn1 = nn.BatchNorm2d(16)
        self.conv2 = nn.Conv2d(in_channels=16, out_channels=16, kernel_size=5, stride=1, padding=0)
        self.bn2 = nn.BatchNorm2d(16)
        self.pool = nn.MaxPool2d(2, 2)

        self.conv3 = nn.Conv2d(in_channels=16, out_channels=64, kernel_size=5, stride=1, padding=0)
        self.bn3 = nn.BatchNorm2d(64)
        self.conv4 = nn.Conv2d(in_channels=64, out_channels=64, kernel_size=5, stride=1, padding=0)
        self.bn4 = nn.BatchNorm2d(64)
        self.pool2 = nn.MaxPool2d(2, 2) 

        self.conv5 = nn.Conv2d(in_channels=64, out_channels=128, kernel_size=5, stride=1, padding=0)
        self.bn5 = nn.BatchNorm2d(128)
        self.conv6 = nn.Conv2d(in_channels=128, out_channels=128, kernel_size=5, stride=1, padding=0)
        self.bn6 = nn.BatchNorm2d(128)
        self.pool3 = nn.MaxPool2d(2, 2) 
        self.dropout = nn.Dropout(0.6)
        self.fc1 = nn.Linear(128 * 21 * 21, len(classeNames))

    def forward(self, x):
        x = F.relu(self.bn1(self.conv1(x)))      
        x = F.relu(self.bn2(self.conv2(x)))     
        x = self.pool(x)                        
        x = F.relu(self.bn3(self.conv3(x)))     
        x = F.relu(self.bn4(self.conv4(x)))  
        x = self.pool(x)  
        x = F.relu(self.bn5(self.conv5(x)))     
        x = F.relu(self.bn6(self.conv6(x)))  
        x = self.pool(x)                      
        x = x.view(-1, 128 * 21 * 21)
        x = self.dropout(x)
        x = self.fc1(x)

        return x


device = "cuda" if torch.cuda.is_available() else "cpu"
print("Using {} device".format(device))

model = Network_bn().to(device)
model

代码运行结果:

此后多次运行均未满足要求,因此还对超参数进行了调整

loss_fn    = nn.CrossEntropyLoss() # 创建损失函数
learn_rate = 1e-3# 学习率
opt        = torch.optim.Adam(model.parameters(), lr=learn_rate)

为选择最好模型,延长训练的同时加入早停

epochs     = 30
best_test_acc = 0
patience = 5
counter = 0
best_model_path = 'best_model.pth'
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))
    # 新增:早停判断
    if epoch_test_acc > best_test_acc:
        best_test_acc = epoch_test_acc
        counter = 0
        torch.save(model.state_dict(), best_model_path)
        print(f'  -> New best model saved (test_acc={epoch_test_acc:.3f})')
    else:
        counter += 1
        print(f'  -> No improvement for {counter} epoch(s)')
        if counter >= patience:
            print(f'Early stopping triggered at epoch {epoch+1}')
            break

# 训练结束后,加载最佳模型(可选)
model.load_state_dict(torch.load(best_model_path))
print(f'Final test accuracy using best model: {best_test_acc:.3f}')
print('Done')

代码运行结果:

可视化:

六、指定图片进行预测

from PIL import Image 

classes = list(total_data.class_to_idx)

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)
    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='./4-data/Monkeypox/M01_01_00.jpg', 
                  model=model, 
                  transform=train_transforms, 
                  classes=classes)

代码运行结果

七、感悟

本周继续学习了如何优化模型,在上周尝试调整了优化器加入早停达到预期预测效能。本周主要选择了调整网络结构进行优化模型。在尝试调整过程中,发现对各参数量的理解以及整个网络的运行模式还是不够理解。因此始终无法调整通道数、卷积层达到预期效果。此外,在运行代码中也发现,因为是随机划分数据集的,在没有设置好随机数种子的情况下,每次重新运行代码出现的结果都是不一样的,如果是在正式做项目的时候还是很有影响的。

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐