深度学习笔记17-VGG-16算法(Pytorch)

一、前期工作

1.导入数据并读取

import torch.nn as nn
import torch
from torchvision import datasets
import os,PIL,pathlib
import torchvision
import torchvision.transforms as transforms
data_dir='D:/TensorFlow1/T6'
data_dir=pathlib.Path(data_dir)
data_path=list(data_dir.glob('*'))
classnames=[path.name for path in data_path if path.is_dir()]
classnames

# 关于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("D:/TensorFlow1/T6",transform=train_transforms)
total_data

total_data.class_to_idx

2.划分数据集

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)是由牛津大学视觉几何组提出的一种深度卷积神经网络架构,用于图像分类和对象识别任务。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个全连接层,最后一个全连接层输出与类别数相对应的向量,用于进行分类。

    from torchvision.models import vgg16
        
    # 加载预训练模型,并且对模型进行微调
    model = vgg16(pretrained = True) # 加载预训练的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(classNames)) # 修改vgg16模型中最后一层全连接层,输出目标类别个数
    model

       

    import torchsummary as summary
    
    summary.summary(model,(3,224,224))

    三、训练模型

    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:  # 获取图片及其标签        
            # 计算预测误差
            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:        
                # 计算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.设置动态学习率

    # 调用官方动态学习率接口时使用
    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) #选定调整方法

    4.正式训练 

    import copy
    
    loss_fn    = nn.CrossEntropyLoss() # 创建损失函数
    epochs     = 30
    
    train_loss = []
    train_acc  = []
    test_loss  = []
    test_acc   = []
    
    best_acc = 0    # 设置一个最佳准确率,作为最佳模型的判别指标
    
    for epoch in range(epochs):
        # 更新学习率(使用自定义学习率时使用)
        # adjust_learning_rate(optimizer, epoch, learn_rate)
        
        model.train()
        epoch_train_acc, epoch_train_loss = train(train_dl, model, loss_fn, optimizer)
        scheduler.step() # 更新学习率(调用官方动态学习率接口时使用)
        
        model.eval()
        epoch_test_acc, epoch_test_loss = test(test_dl, model, loss_fn)
        
        # 保存最佳模型到 best_model
        if epoch_test_acc > best_acc:
            best_acc   = epoch_test_acc
            best_model = copy.deepcopy(model)
        
        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']
        
        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))
        
    # 保存最佳模型到文件中
    PATH = './best_model.pth'  # 保存的参数文件名
    torch.save(model.state_dict(), PATH)
    
    print('Done')

       四、结果可视化

    1.loss与acc图

    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='D:/TensorFlow1/T6/Angelina Jolie/001_fe3347c0.jpg', 
                      model=model, 
                      transform=train_transforms, 
                      classes=classes)

    五、个人总结

    VGG 网络有多个变体,其中最著名的是 VGG16 和 VGG19。这些数字表示网络中卷积层的总数。

    • VGG16

      • 13 个卷积层

      • 3 个全连接层

      • 总共 16 层(包括卷积层和全连接层)

    • VGG19

      • 16 个卷积层

      • 3 个全连接层

      • 总共 19 层

    2. 卷积层
    • 卷积核大小:所有卷积层均使用 3x3 的卷积核。

    • 步幅:步幅为 1。

    • 填充:使用零填充(Zero Padding),保持特征图的尺寸。

    • 激活函数:使用 ReLU(Rectified Linear Unit)作为激活函数。

    3. 池化层
    • 池化方式:使用 2x2 的最大池化(Max Pooling)。

    • 步幅:步幅为 2。

    4. 全连接层
    • 全连接层:VGG 网络在卷积层之后有 3 个全连接层。

      • 第一个全连接层有 4096 个神经元。

      • 第二个全连接层有 4096 个神经元。

      • 第三个全连接层是输出层,有 1000 个神经元(对应 ImageNet 数据集的 1000 个类别)。

    5. 权重初始化

    缺点

    • 权重初始化方法:使用 Xavier 初始化方法(也称为 Glorot 初始化)。

      VGG 网络的优缺点

      优点
    • 简单且有效:VGG 网络结构简单,使用统一的卷积核大小和步幅,便于实现和训练。

    • 性能优异:在 ImageNet 挑战赛中取得了优异的成绩,证明了其在图像分类任务中的有效性。

    • 计算量大:VGG 网络非常深,计算量大,训练和推理速度较慢。

    • 参数量多:VGG16 有约 1.38 亿个参数,VGG19 有约 1.44 亿个参数,模型存储和计算成本高。

    • 过拟合风险:由于参数量多,容易在训练集上过拟合,需要使用 Dropout 等正则化方法来缓解。

      • 通用性:VGG 网络可以作为预训练模型,用于迁移学习,适用于多种图像识别任务。

    评论
    添加红包

    请填写红包祝福语或标题

    红包个数最小为10个

    红包金额最低5元

    当前余额3.43前往充值 >
    需支付:10.00
    成就一亿技术人!
    领取后你会自动成为博主和红包主的粉丝 规则
    hope_wisdom
    发出的红包
    实付
    使用余额支付
    点击重新获取
    扫码支付
    钱包余额 0

    抵扣说明:

    1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
    2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

    余额充值