深度学习笔记16-VGG-16算法-Pytorch实现人脸识别

news/2025/2/22 17:37:03

目录

前言

一、 前期准备

1. 设置GPU

2. 导入数据

3. 划分数据集

二、调用官方的VGG-16模型

三、 训练模型

1. 编写训练函数

2. 编写测试函数

3. 设置动态学习率

4. 正式训练

四、 结果可视化

1. Loss与Accuracy图

2. 指定图片进行预测

3. 模型评估

五、总结

前言

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

一、 前期准备

1. 设置GPU

如果设备上支持GPU就使用GPU,否则使用CPU

import torch
import torch.nn as nn
import torchvision.transforms as transforms
import torchvision
from torchvision import transforms, datasets
import os,PIL,pathlib,warnings

warnings.filterwarnings("ignore")             #忽略警告信息

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

2. 导入数据

import os,PIL,random,pathlib

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

data_paths  = list(data_dir.glob('*'))
classeNames = [str(path).split("\\")[1] for path in data_paths]
classeNames
# 关于transforms.Compose的更多介绍可以参考:https://blog.csdn.net/qq_38251616/article/details/124878863
train_transforms = transforms.Compose([
    transforms.Resize([224, 224]),  # 将输入图片resize成统一尺寸
    # transforms.RandomHorizontalFlip(), # 随机水平翻转
    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("./6-data/",transform=train_transforms)
total_data
total_data.class_to_idx

3. 划分数据集

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


二、调用官方的VGG-16模型


VGG-16(Visual Geometry Group-16)是由牛津大学视觉几何组(Visual Geometry Group)提出的一种深度卷积神经网络架构,用于图像分类和对象识别任务。VGG-16在2014年被提出,是VGG系列中的一种。VGG-16之所以备受关注,是因为它在ImageNet图像识别竞赛中取得了很好的成绩,展示了其在大规模图像识别任务中的有效性。

以下是VGG-16的主要特点:

1深度:VGG-16由16个卷积层和3个全连接层组成,因此具有相对较深的网络结构。这种深度有助于网络学习到更加抽象和复杂的特征。
2卷积层的设计:VGG-16的卷积层全部采用3x3的卷积核和步长为1的卷积操作,同时在卷积层之后都接有ReLU激活函数。这种设计的好处在于,通过堆叠多个较小的卷积核,可以提高网络的非线性建模能力,同时减少了参数数量,从而降低了过拟合的风险。
3池化层:在卷积层之后,VGG-16使用最大池化层来减少特征图的空间尺寸,帮助提取更加显著的特征并减少计算量。
4全连接层:VGG-16在卷积层之后接有3个全连接层,最后一个全连接层输出与类别数相对应的向量,用于进行分类。

VGG-16结构说明:

●13个卷积层(Convolutional Layer),分别用blockX_convX表示;
●3个全连接层(Fully connected Layer),用classifier表示;
●5个池化层(Pool layer)。

VGG-16包含了16个隐藏层(13个卷积层和3个全连接层),故称为VGG-16

image.png

from torchvision.models import vgg16

device = "cuda" if torch.cuda.is_available() else "cpu"
print("Using {} device".format(device))
    
# 加载预训练模型,并且对模型进行微调
model = vgg16(pretrained = True).to(device) # 加载预训练的vgg16模型

for param in model.parameters():
    param.requires_grad = False # 冻结模型的参数,这样子在训练的时候只训练最后一层的参数

# 修改classifier模块的第6层(即:(6): Linear(in_features=4096, out_features=2, bias=True))
# 注意查看我们下方打印出来的模型
model.classifier._modules['6'] = nn.Linear(4096,len(classeNames)) # 修改vgg16模型中最后一层全连接层,输出目标类别个数
model.to(device)  
model

 


三、 训练模型

1. 编写训练函数

# 训练循环
def train(dataloader, model, loss_fn, optimizer):
    size = len(dataloader.dataset)  # 训练集的大小
    num_batches = len(dataloader)   # 批次数目, (size/batch_size,向上取整)

    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

2. 编写测试函数


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

def test (dataloader, model, loss_fn):
    size        = len(dataloader.dataset)  # 测试集的大小
    num_batches = len(dataloader)          # 批次数目, (size/batch_size,向上取整)
    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

3. 设置动态学习率
 

# def adjust_learning_rate(optimizer, epoch, start_lr):
#     # 每 2 个epoch衰减到原来的 0.98
#     lr = start_lr * (0.92 ** (epoch // 2))
#     for param_group in optimizer.param_groups:
#         param_group['lr'] = lr

learn_rate = 1e-4 # 初始学习率
# optimizer  = torch.optim.SGD(model.parameters(), lr=learn_rate)

✨调用官方动态学习率接口
与上面方法是等价的

# 调用官方动态学习率接口时使用
lambda1 = lambda epoch: 0.92 ** (epoch // 4)
optimizer = torch.optim.SGD(model.parameters(), lr=learn_rate)
scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda1) #选定调整方法

👉调用官方接口示例:
该代码块仅为代码讲解示例,不是整体程序的一部分

model = [torch.nn.Parameter(torch.randn(2, 2, requires_grad=True))]
optimizer = SGD(model, 0.1)
scheduler = ExponentialLR(optimizer, gamma=0.9)

for epoch in range(20):
    for input, target in dataset:
        optimizer.zero_grad()
        output = model(input)
        loss = loss_fn(output, target)
        loss.backward()
        optimizer.step()
    scheduler.step()

4. 正式训练


model.train()、model.eval()训练营往期文章中有详细的介绍。请注意观察我是如何保存最佳模型,与TensorFlow2的保存方式有何异同。

import copy
from datetime import datetime
import os

# 导入必要的PyTorch组件
import torch
import torch.nn as nn
from torch.optim import lr_scheduler

# 创建交叉熵损失函数
loss_fn = nn.CrossEntropyLoss()
# 设置训练的轮数(epoch)
epochs = 40

# 初始化训练和测试的损失和准确率列表
train_loss = []
train_acc = []
test_loss = []
test_acc = []

# 初始化最佳准确率和最佳模型参数
best_acc = 0
best_model_params = None

# 定义模型保存的根目录
model_root_dir = './model'

# 假设你的模型是一个包含卷积层的模型,下面是一个示例
class SimpleModel(nn.Module):
    def __init__(self):
        super(SimpleModel, self).__init__()
        # 假设输入是一个 (224, 224) 大小的图像,通道数为 3
        self.layer1 = nn.Conv2d(3, 32, kernel_size=3, stride=1, padding=1)
        self.layer2 = nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=1)
        self.layer3 = nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1)
        
        # 计算展平后线性层的输入特征数
        self.fc1 = nn.Linear(128 * 224 * 224, 512)  # 根据输入尺寸计算展平后的特征数
        self.fc2 = nn.Linear(512, 10)  # 假设分类任务是10类

    def forward(self, x):
        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        x = x.view(x.size(0), -1)  # 展平操作
        x = self.fc1(x)
        x = self.fc2(x)
        return x

# 初始化模型
model = SimpleModel()

# 设置初始学习率和优化器
learn_rate = 1e-4
optimizer = torch.optim.Adam(model.parameters(), lr=learn_rate)

# 设置学习率调度器
lambda1 = lambda epoch: 0.92 ** (epoch // 4)
scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda1)

# 假设 train_dl 和 test_dl 已定义为你的训练和测试数据加载器
# 例如:train_dl = DataLoader(train_dataset, batch_size=64, shuffle=True)

# 开始训练循环
for epoch in range(epochs):
    # 将模型设置为训练模式
    model.train()
    # 这里假设有一个函数来执行训练,并返回训练的准确率和损失
    epoch_train_acc, epoch_train_loss = train(train_dl, model, loss_fn, optimizer)
    # 更新学习率(如果是使用PyTorch的学习率调度器)
    scheduler.step()
    
    # 将模型设置为评估模式
    model.eval()
    # 这里假设有一个函数来执行测试,并返回测试的准确率和损失
    epoch_test_acc, epoch_test_loss = test(test_dl, model, loss_fn)
    
    # 如果当前epoch的测试准确率超过了之前的最佳准确率,则保存当前模型参数
    if epoch_test_acc > best_acc:
        best_acc = epoch_test_acc
        best_model_params = copy.deepcopy(model.state_dict())
    
    # 将当前epoch的准确率和损失添加到列表中
    train_acc.append(epoch_train_acc)
    train_loss.append(epoch_train_loss)
    test_acc.append(epoch_test_acc)
    test_loss.append(epoch_test_loss)
    
    # 获取当前的学习率
    lr = optimizer.state_dict()['param_groups'][0]['lr']
    
    # 打印当前epoch的信息
    template = ('Epoch:{:2d}, Train_acc:{:.1f}%, Train_loss:{:.3f}, Test_acc:{:.1f}%, Test_loss:{:.3f}, Lr:{:.2E}')
    print(template.format(epoch+1, epoch_train_acc*100, epoch_train_loss, 
                          epoch_test_acc*100, epoch_test_loss, lr))
    
# 创建一个带有时间戳的文件夹用来保存每次训练的最好模型
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
model_dir = os.path.join(model_root_dir, timestamp)
os.makedirs(model_dir, exist_ok=True)

# 保存最佳模型参数
torch.save(best_model_params, os.path.join(model_dir, 'best_model_params.pth'))
print('best_model_params.pth 已保存在:' + model_dir)

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

2. 指定图片进行预测

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='./6-data/Angelina Jolie/001_fe3347c0.jpg', 
                  model=model, 
                  transform=train_transforms, 
                  classes=classes)

 

3. 模型评估

best_model.eval()
epoch_test_acc, epoch_test_loss = test(test_dl, best_model, loss_fn)

五、总结

在进行模型训练时,我遇到了一些常见的错误和挑战,下面总结了几个注意事项和tips,供后续使用:

1. 模型参数和数据维度匹配

报错:“mat1 and mat2 shapes cannot be multiplied”,通常是因为模型的输入数据维度和模型定义的层不匹配。特别是在卷积层后接全连接层时,确保通过展平(flatten)操作正确调整输入的形状。例如,卷积输出的大小和全连接层的输入维度必须匹配。

2. 'list' object has no attribute 'parameters' 错误

• 这通常是因为将模型定义为一个列表(model = [torch.nn.Parameter(...)]),而不是一个 nn.Module 的子类对象。确保模型是一个继承自 nn.Module 的类的实例,并使用 model = MyModel() 的形式来初始化。

3. 学习率调整

• 在使用学习率调度器时,确保传递给调度器的优化器是正确的。例如,scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda1),这里 optimizer 必须是正确初始化的。我的错误是忘记了在定义优化器时直接把学习率衰减的逻辑写到 optimizer 中。

4. 保存模型的参数

• 在训练过程中,常常需要保存模型的最佳参数。如果在 train() 函数中发现了最佳性能,使用 copy.deepcopy(model.state_dict()) 可以确保保存的是参数而不是模型本身,避免了模型结构被修改或丢失。

5. 学习率调度器

• 使用学习率调度器(如 LambdaLR)时,确保每次更新都能正确调用 scheduler.step(),并且学习率的更新函数要根据训练周期进行调整。


http://www.niftyadmin.cn/n/5862582.html

相关文章

什么是矩阵账号?如何高效运营tiktok矩阵账号

‍‌​​‌‌​‌​‍‌​​​‌‌​​‍‌​​​‌​‌​‍‌​​‌​​‌​‍‌​‌‌​‌‌‌‍‌​‌​‌​​​‍‌​​‌​‌‌​‍‌​​​​‌‌​‍‌​‌​​‌‌‌‍‌​​‌‌​‌​‍‌​‌​​‌‌‌‍‌​‌‌‌​​‌‍‌‌​​‌‌‌​‍‌‌​​‌‌​​‍‌…

SpringBoot有几种获取Request对象的方法

HttpServletRequest 简称 Request,它是一个 Servlet API 提供的对象,用于获取客户端发起的 HTTP 请求信息。例如:获取请求参数、获取请求头、获取 Session 会话信息、获取请求的 IP 地址等信息。 那么问题来了,在 Spring Boot 中…

网络安全域管理 网络安全管理体系

🍅 点击文末小卡片 ,免费获取网络安全全套资料,资料在手,涨薪更快 信息安全管理体系 1、这些基于产品、技术与管理层面的标准在某些领域得到了很好的应用,但从组织信息安全的各个角度和整个生命周期来考察&#xff0c…

企业知识管理平台重构数字时代知识体系与智能服务网络

内容概要 现代企业知识管理平台的演进呈现出全生命周期管理与智能服务网络构建的双重特征。通过四库体系(知识采集库、加工库、应用库、评估库)的协同运作,该系统实现了从知识沉淀、结构化处理到价值释放的完整闭环。其中,知识图…

vue3 文件类型传Form Data数据格式给后端

在 Vue 3 中,如果你想将文件(例如上传的 Excel 文件)以 FormData 格式发送到后端,可以通过以下步骤实现。这种方式通常用于处理文件上传,因为它可以将文件和其他数据一起发送到服务器。 首先,创建一个 Vue…

Python常见面试题的详解13

1. 以下X是什么类型 X (i for i in range(10)) 要点 在 Python 中,变量的类型取决于其赋值的对象。 下面代码中的 (i for i in range(10)) 是一个生成器表达式。生成器表达式是一种简洁的创建生成器的方式,它类似于列表推导式,但使用圆括号…

# 嵌入式基础学习|C语言——进程篇综合(含进阶)

进程与多任务编程 进程的概念 进程是进行中的程序,即程序的一次执行过程。它包含了程序在内存中的代码、数据以及CPU的执行状态。进程是程序的实例,是操作系统进行资源分配和调度的基本单位。 程序:静态的代码文件,存储在硬盘上…

windwos与linux环境下Iperf3带宽测试工具的安装、使用

目录 一、前言 二、windows 2.1下载 2.2安装 2.3使用 2.3.1服务端 2.3.2客户端 2.3.3输出内容 1.客户端 2.服务端 2.4.相关命令 三、linux 3.1安装 3.2使用 1.服务端 2.客户端 3.输出内容 1.客户端 2.服务端 一、前言 在数字化浪潮下,网络性能…