week6:VGG-16算法-Pytorch实现人脸识别实验

VGG-16算法-Pytorch实现人脸识别实验

Ⅰ Ⅰ Introduction:
  • 本文为机器学习人脸识别实验记录:通过VGG-16算法-Pytorch实现人脸识别
  • 学习目标:
    • 学会使用官方自带的vgg16接口
    • 了解VGG
    • 保存过程中的最佳模型权重
Ⅱ Ⅱ Experiment:
  1. 数据准备与任务分析:

下载数据集,并通过transform调整图片尺寸,划分好训练集与测试集

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

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

    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("./48-data/", transform=train_transforms)
    print(total_data)
    print(total_data.class_to_idx)
    # 划分数据集
    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])
    print(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

可以看到数据集:

Dataset ImageFolder
    Number of datapoints: 1800
    Root location: ./48-data/
    StandardTransform
Transform: Compose(
               Resize(size=[224, 224], interpolation=bilinear, max_size=None, antialias=warn)
               ToTensor()
               Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
           )
{'Angelina Jolie': 0, 'Brad Pitt': 1, 'Denzel Washington': 2, 'Hugh Jackman': 3, 'Jennifer Lawrence': 4, 'Johnny Depp': 5, 'Kate Winslet': 6, 'Leonardo DiCaprio': 7, 'Megan Fox': 8, 'Natalie Portman': 9, 'Nicole Kidman': 10, 'Robert Downey Jr': 11, 'Sandra Bullock': 12, 'Scarlett Johansson': 13, 'Tom Cruise': 14, 'Tom Hanks': 15, 'Will Smith': 16}

  1. 配置环境:
  • 语言环境:python 3.8
  • 编译器: pycharm
  • 深度学习环境:
    • torch==2.11
    • cuda12.1
    • torchvision==0.15.2a0
  1. 构建网络:
    这里直接调用官方的接口,通过:
from torchvision.models import vgg16

VGG16是一种卷积神经网络(Convolutional Neural Network,CNN),由牛津大学的视觉几何组(Visual Geometry Group, VGG)在2014年提出,并在ImageNet挑战赛中表现优异。VGG16以其深层网络结构和较小的卷积核尺寸而著称,是深度学习领域的经典模型之一。

VGG16的结构
VGG16的网络结构由16个权重层(13个卷积层和3个全连接层)组成,具体结构如下:

输入层:

输入图像大小为224x224x3(宽度x高度x通道数)。
卷积层和池化层:

第1段:两个3x3卷积层(64个过滤器),后接一个2x2最大池化层(stride为2)。
第2段:两个3x3卷积层(128个过滤器),后接一个2x2最大池化层(stride为2)。
第3段:三个3x3卷积层(256个过滤器),后接一个2x2最大池化层(stride为2)。
第4段:三个3x3卷积层(512个过滤器),后接一个2x2最大池化层(stride为2)。
第5段:三个3x3卷积层(512个过滤器),后接一个2x2最大池化层(stride为2)。
全连接层:

三个全连接层:第一个和第二个全连接层有4096个神经元,最后一个全连接层有1000个神经元(对应ImageNet的1000个类别)。
激活函数:

所有隐藏层的激活函数均为ReLU(Rectified Linear Unit)。
Softmax层:

输出层使用Softmax激活函数,将网络的输出转换为概率分布,用于分类任务。
VGG16的特点
小卷积核:

使用多个3x3的小卷积核而不是大卷积核,这样可以增加网络的深度,提高模型的表达能力,同时减少参数量。
深层网络:

通过增加网络层数,VGG16比浅层网络具有更强的特征提取能力。
全局参数共享:

卷积层中的过滤器参数在整个图像上共享,使得模型具有平移不变性和较少的参数量。
VGG16的应用
VGG16广泛应用于各种计算机视觉任务,包括但不限于:

图像分类
物体检测
图像分割
特征提取
由于其结构简单且效果优异,VGG16常被用作其他复杂模型的基准或预训练模型。

VGG16的优缺点
优点:

结构简单明了,便于理解和实现。
深层结构和小卷积核的组合使其在特征提取方面表现出色。
在ImageNet等大规模数据集上表现优异,具有较强的迁移学习能力。
缺点:

计算量较大,训练和推理速度较慢,尤其是与后来的更高效的模型相比。
参数量较大,存储和计算资源需求高。
总体而言,VGG16是深度学习领域的重要模型,为后续的卷积神经网络研究和发展奠定了坚实的基础。

通过一下代码

    model.classifier._modules['6'] = nn.Linear(4096, len(classeNames))  
    model.to(device)
    print(model)
VGG(
  (features): Sequential(
    (0): Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (1): ReLU(inplace=True)
    (2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (3): ReLU(inplace=True)
    (4): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (5): Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (6): ReLU(inplace=True)
    (7): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (8): ReLU(inplace=True)
    (9): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (10): Conv2d(128, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (11): ReLU(inplace=True)
    (12): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (13): ReLU(inplace=True)
    (14): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (15): ReLU(inplace=True)
    (16): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (17): Conv2d(256, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (18): ReLU(inplace=True)
    (19): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (20): ReLU(inplace=True)
    (21): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (22): ReLU(inplace=True)
    (23): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (24): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (25): ReLU(inplace=True)
    (26): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (27): ReLU(inplace=True)
    (28): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (29): ReLU(inplace=True)
    (30): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  )
  (avgpool): AdaptiveAvgPool2d(output_size=(7, 7))
  (classifier): Sequential(
    (0): Linear(in_features=25088, out_features=4096, bias=True)
    (1): ReLU(inplace=True)
    (2): Dropout(p=0.5, inplace=False)
    (3): Linear(in_features=4096, out_features=4096, bias=True)
    (4): ReLU(inplace=True)
    (5): Dropout(p=0.5, inplace=False)
    (6): Linear(in_features=4096, out_features=17, bias=True)
  )
)

  1. 训练模型:

设置优化器,损失函数,学习率等:

    learn_rate = 1e-4  # 初始学习率
    # 调用官方动态学习率接口时使用
    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)

    loss_fn = nn.CrossEntropyLoss()  # 创建损失函数

编写主函数,设置训练轮次为40:

    epochs = 40

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

训练函数如下:

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
  1. 测试模型:

训练过程中,需要编写测试函数来做评估:

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
  1. 实验结果及可视化:

绘制实验结果的图像:

    PATH = './best_model.pth'  # 保存的参数文件名
    torch.save(model.state_dict(), PATH)

    print('Done')
    plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
    plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号
    plt.rcParams['figure.dpi'] = 100  # 分辨率

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

实验结果如下:
在这里插入图片描述

  1. 保存模型及测试:
    保存模型的代码如下
    PATH = './best_model.pth'  # 保存的参数文件名
    torch.save(model.state_dict(), PATH)

这里我们选用一张测试集的图片对模型进行测试

    classes = list(total_data.class_to_idx)

    predict_one_image(image_path='./48-data/Angelina Jolie/001_fe3347c0.jpg',
                      model=model,
                      transform=train_transforms,
                      classes=classes)

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}')
预测结果是:Angelina Jolie

打印出模型的数据:
在这里插入图片描述

Ⅲ Ⅲ Conclusion:

通过调用官方预训练的VGG16接口,我们进行了人脸识别实验,学到了VGG16的基本框架和使用方法。实验完成并取得了预期效果,增强了对深度学习模型的理解。未来计划结合更先进的模型和数据增强技术,以提高识别精度和鲁棒性。

  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值