学习目的:学会提升模型效能

一、 前期准备

关于环境

  • 语言环境: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,random

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

device

运行结果:

2. 导入数据

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

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

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

代码解读:

  • glob('*') 获取所有子文件夹路径,然后提取文件夹名作为类别名称。

代码运行结果:

3. 数据可视化

import matplotlib.pyplot as plt
from PIL import Image

# 指定图像文件夹路径
image_folder = './data/cloudy/'

# 获取文件夹中的所有图像文件
image_files = [f for f in os.listdir(image_folder) if f.endswith((".jpg", ".png", ".jpeg"))]

# 创建Matplotlib图像
fig, axes = plt.subplots(3, 8, figsize=(16, 6))

# 使用列表推导式加载和显示图像
for ax, img_file in zip(axes.flat, image_files):
    img_path = os.path.join(image_folder, img_file)
    img = Image.open(img_path)
    ax.imshow(img)
    ax.axis('off')

# 显示图像
plt.tight_layout()
plt.show()

代码运行结果:

4.图片预处理

total_datadir = './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

代码解读:

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

  • 模型要求输入尺寸一致 → 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

代码运行结果:

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

代码解读:

之前两周联系的原始数据均已划分好训练集和测试集因此无需划分,本周则以8:2的比例进行随机划分数据集

代码运行结果:

train_size,test_size

代码运行结果:

根据运行结果可知训练集900各样本;测试集225个样本

batch_size = 32

train_dl = torch.utils.data.DataLoader(train_dataset,
                                       batch_size=batch_size,
                                       shuffle=True)
test_dl = torch.utils.data.DataLoader(test_dataset,
                                      batch_size=batch_size,
                                      shuffle=True)
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.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.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.pool1(x)                        
        x = F.relu(self.bn4(self.conv4(x)))     
        x = F.relu(self.bn5(self.conv5(x)))  
        x = self.pool2(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

代码解读:

torch.nn.Flatten()与TensorFlow中的Flatten()层类似,前两者则仅仅是一种数据集拉伸操作(将二维数据拉伸为一维),torch.flatten()方法不会改变x本身,而是返回一个新的张量。而x.view()方法则是直接在原有数据上进行操作。

代码运行结果:

三、训练模型

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

代码运行结果:

四、 结果可视化

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到达93%

五、提高模型效能

对于如何提升模型准确率,deep seek回答:

  1. 数据增强:当前只有resize和归一化,没有随机翻转、旋转、裁剪等。添加数据增强可以提升泛化。

  2. 模型改进:当前模型较浅,可以增加深度、增加卷积核数量、使用更先进的架构(如ResNet、预训练模型)。但因为是CPU/GPU小数据集,可以先尝试增加复杂度。

  3. 学习率调整:可以使用学习率调度器,如余弦退火、ReduceLROnPlateau。

  4. 正则化:添加Dropout、权重衰减(L2正则)防止过拟合。

  5. 优化器更换:SGD可以尝试Adam,但通常SGD+动量也不错。可以调整学习率。

  6. 更长的训练:epochs=20可能不足,可增加到50-100,结合早停。

  7. 使用预训练模型:如ResNet18在ImageNet上预训练后微调,通常能大幅提升准确率。

  8. 类别平衡:检查数据集是否平衡,若不平衡可使用加权损失。

1、进行延长训练

根据deep seek建议,我首先将epochs延长为30

代码运行结果:

部分运行已可达93%,但是最终模型结果准确率为88%,并未达到要求

2、进行数据增强

考虑延长训练无法满足要求,因此在图片预处理上进行了改动:

train_transforms = transforms.Compose([
    transforms.RandomResizedCrop(224, scale=(0.8, 1.0)),  # 随机裁剪并缩放到224
    transforms.RandomHorizontalFlip(p=0.5),              # 随机水平翻转
    transforms.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2, hue=0.1),
    transforms.RandomRotation(15),                       # 随机旋转
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])

代码运行结果:

依然未满足要求

3、进行优化器更换

原始代码优化器选择SGD,这里尝试使用Adam

opt        = torch.optim.AdamW(model.parameters(), lr=learn_rate, weight_decay=1e-4)

代码运行结果:

运行两次,最终模型都未达要求,考虑在训练过程中有出现满足要求的参数,因此根据deep seek意见在训练过程中加入早停

4、加入早停

早停是一种防止过拟合的技术:当模型在验证集上的表现不再提升时,提前终止训练,并恢复最佳模型参数。

基本原理

  1. 每个 epoch 结束后,在验证集上评估模型(不用测试集!)。

  2. 如果当前验证集准确率比历史最佳更高,就保存当前模型参数。

  3. 如果连续多个 epoch(patience)验证集准确率都没有提升,就停止训练,并加载之前保存的最佳模型。

这样能确保最终得到的是验证集上表现最好的那个 epoch 的模型,而不是最后一轮可能过拟合的模型。

epochs     = 20
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')

代码运行结果:

最终我选择的提升方法为:更换优化器+早停获得测试集准测率≥93%的模型,但是对于95%准确率仍未满足,后续还需尝试其他办法

结果可视化:

六、识别本地图片

在百度上随便下载了一张图片用于识别:

def preprocess_image(image_path):
    # 与训练时相同的 transform
    transform = transforms.Compose([
        transforms.Resize([224, 224]),
        transforms.ToTensor(),
        transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
    ])
    image = Image.open(image_path).convert('RGB')   # 确保 RGB 三通道
    image_tensor = transform(image).unsqueeze(0)    # 增加 batch 维度
    return image_tensor.to(device)

# -------------------- 4. 预测单张图片 --------------------
def predict_image(image_path, model, class_names):
    model.eval()
    with torch.no_grad():
        input_tensor = preprocess_image(image_path)
        output = model(input_tensor)          # shape: (1, num_classes)
        probabilities = F.softmax(output, dim=1)  # 转换为概率
        pred_class_idx = torch.argmax(probabilities, dim=1).item()
        confidence = probabilities[0][pred_class_idx].item()
        pred_class_name = class_names[pred_class_idx]
        return pred_class_name, confidence

# -------------------- 5. 使用示例 --------------------
if __name__ == '__main__':
    # 类别名称(请根据你的实际文件夹顺序调整)
    class_names = ['cloudy', 'rain', 'shine', 'sunrise']   # 与训练时的 classeNames 顺序一致
    
    # 本地图片路径(换成你自己的图片路径)
    image_path = r'C:\Users\hsq\Desktop\train\test.jpg'
    
    # 预测
    pred_name, conf = predict_image(image_path, model, class_names)
    print(f"预测类别: {pred_name}, 置信度: {conf:.4f}")

运行结果:

模型对图片识别成功。

七、感悟

本次学习最重要的一个就是学会对模型参数进行调整,因为在模型训练过程中我们不可能每次运气都很好一次就可以把模型训练成功,因此需要学习如何对模块进行调整来达到训练出好模型的目的。在这个过程中还发现本次的神经网路不同于前两次,是经过两个卷积层后再进行池化,然后又经过两个卷积层再池化一次获得最终参数,在进行调优的时候对神经网络的模块进行达到目的应该也是可行的,有待后续尝试。此外,训练模型过程中发现模型的准确率在到达最高点后再往下训练会出现准确率下降的现象,这是说明模型出现了过拟合,因此过度延长训练过程也是不可取的。

Logo

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

更多推荐