- 🍨 本文为🔗365天深度学习训练营 中的学习记录博客
- 🍖 原作者:K同学啊
我的环境
语言环境:python 3.7.12
编译器:pycharm
深度学习环境:tensorflow 2.7.0
数据:本地数据集
一、代码
# 第P6周:VGG-16算法-Pytorch实现人脸识别
# 数据集:dataset_facerecognition
# 任务:1. 保存训练过程中的最佳模型权重
# 2. 调用官方的VGG-16网络框架# 设置GPU
import torch
import torch.nn as nn
import torchvision.transforms as transforms
import torchvision
from torchvision import transforms, datasets
import os,PIL,pathlib,warningswarnings.filterwarnings("ignore") #忽略警告信息device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(device)# 导数据
import os,PIL,random,pathlibdata_dir = './dataset_facerecognition/'
data_dir = pathlib.Path(data_dir) # 其下封装了很多功能,使用方便安全data_paths = list(data_dir.glob('*'))
classNames = [str(path).split("/")[1] for path in data_paths] #获取子目录名称
print(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(data_dir,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 = 32train_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# 调用官方得VGG16
from torchvision.models import vgg16device = "cuda" if torch.cuda.is_available() else "cpu"
print("Using {} device".format(device))# 加载预训练模型,并且对模型进行微调
model = vgg16(pretrained=True).to(device) # 加载预训练的vgg16模型。模型移动到GPUfor 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.to(device)
print(model)#编写训练函数
# 训练循环
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) #数据移动到 GPU# 计算预测误差pred = model(X) # 网络输出loss = loss_fn(pred, y) # 计算网络输出和真实值之间的差距,targets为真实值,计算二者差值即为损失# 反向传播optimizer.zero_grad() # grad属性归零loss.backward() # 反向传播optimizer.step() # 每一步自动更新# 记录acc与losstrain_acc += (pred.argmax(1) == y).type(torch.float).sum().item()train_loss += loss.item()train_acc /= sizetrain_loss /= num_batchesreturn train_acc, train_loss# 编写测试函数
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) # 数据移动到 GPU# 计算losstarget_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 /= sizetest_loss /= num_batchesreturn test_acc, test_loss# 设置动态学习率
# 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'] = lrlearn_rate = 1e-4 # 初始学习率
# optimizer = torch.optim.SGD(model.parameters(), lr=learn_rate)# 或者调用官方得动态学习率
# 调用官方动态学习率接口时使用更多的官方动态学习率设置方式可参考:https://pytorch.org/docs/stable/optim.html
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.train()、model.eval()训练营往期文章中有详细的介绍。请注意观察我是如何保存最佳模型,与TensorFlow2的保存方式有何异同。
import copyloss_fn = nn.CrossEntropyLoss() # 创建损失函数
epochs = 40train_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_modelif epoch_test_acc > best_acc:best_acc = epoch_test_accbest_model = copy.deepcopy(model) #这里保存的是最佳模型的深拷贝,如果 model 已经在 GPU 上,那么 best_model 也会在 GPU 上print(f"Best model updated at Epoch {epoch + 1} with Test Acc: {best_acc:.4f}")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' # 保存的参数文件名
if best_model is not None:# 将模型移动到 CPU 上保存,确保兼容性best_model.to('cpu')torch.save(best_model.state_dict(), PATH)print(f"Best model saved to {PATH}")
else:print("No best model found. Training did not improve test accuracy.")print('Done')# 进阶要求:调整代码使测试集准确率达到60%
# 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()# 指定图片进行预测
from PIL import Imageclasses = 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)#在预测单张图片时,输入图像也被显式地移动到了 device 上,所以预测也是在GPU上进行model.eval()output = model(img)_, pred = torch.max(output, 1)pred_class = classes[pred]print(f'预测结果是:{pred_class}')# 预测训练集中的某张照片
predict_one_image(image_path=data_dir+'001_fe3347c0.jpg',model=model,transform=train_transforms,classes=classes)# 模型评估
best_model.eval() # 将模型设置成评估模式
epoch_test_acc, epoch_test_loss = test(test_dl, best_model, loss_fn)print(epoch_test_acc, epoch_test_loss)# 查看是否与我们记录的最高准确率一致
print(epoch_test_acc)
二、结果
精度太低了,预测错误
三、总结
保存最佳模型
代码1
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_modelif epoch_test_acc > best_acc:best_acc = epoch_test_accbest_model = copy.deepcopy(model) #这里保存的是最佳模型的深拷贝,如果 model 已经在 GPU 上,那么 best_model 也会在 GPU 上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)
修正后的代码如下
代码2
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_modelif epoch_test_acc > best_acc:best_acc = epoch_test_accbest_model = copy.deepcopy(model) #这里保存的是最佳模型的深拷贝,如果 model 已经在 GPU 上,那么 best_model 也会在 GPU 上print(f"Best model updated at Epoch {epoch + 1} with Test Acc: {best_acc:.4f}")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' # 保存的参数文件名
if best_model is not None:# 将模型移动到 CPU 上保存,确保兼容性best_model.to('cpu')torch.save(best_model.state_dict(), PATH)print(f"Best model saved to {PATH}")
else:print("No best model found. Training did not improve test accuracy.")
其中修改有:1.在每次更新最佳模型时,打印相关信息,便于跟踪训练过程中的最佳模型变化。2.确保 best_model 在 GPU 或 CPU 上的兼容性。如果模型在 GPU 上运行,best_model 也会在 GPU 上。这不会影响保存过程,但在加载模型时需要特别注意设备的匹配。如果你希望保存的模型能够在任何设备上加载,可以将 best_model 移动到 CPU 上再保存。
1.:
if epoch_test_acc > best_acc:best_acc = epoch_test_accbest_model = copy.deepcopy(model)print(f"Best model updated at Epoch {epoch + 1} with Test Acc: {best_acc:.4f}")
2:
if best_model is not None:# 将模型移动到 CPU 上保存,确保兼容性best_model.to('cpu')torch.save(best_model.state_dict(), PATH)print(f"Best model saved to {PATH}")
else:print("No best model found. Training did not improve test accuracy.")
VGG16
VGG-16(Visual Geometry Group-16)是由牛津大学视觉几何组(Visual Geometry Group)提出的一种深度卷积神经网络架构,用于图像分类和对象识别任务。VGG-16在2014年被提出,是VGG系列中的一种。VGG-16之所以备受关注,是因为它在ImageNet图像识别竞赛中取得了很好的成绩,展示了其在大规模图像识别任务中的有效性。名称中的16是指隐藏层的层数,VGG-16包含了16个隐藏层(13个卷积层和3个全连接层),故称为VGG-16
以下是VGG-16的主要特点:
- 深度:VGG16 拥有 16 层权重层(13 个卷积层 + 3 个全连接层),这种深度有助于网络学习到更加抽象和复杂的特征。
- 卷积层的设计:VGG-16的卷积层全部采用3x3的卷积核和步长为1的卷积操作,同时在卷积层之后都接有ReLU激活函数。这种设计的好处在于,通过堆叠多个较小的卷积核,可以提高网络的非线性建模能力,同时减少了参数数量,从而降低了过拟合的风险。
- 池化层:在卷积层之后,VGG-16使用最大池化层来减少特征图的空间尺寸,帮助提取更加显著的特征并减少计算量。
- 全连接层:VGG-16在卷积层之后接有3个全连接层,最后一个全连接层输出与类别数相对应的向量,用于进行分类。
VGG-16结构说明:
● 13个卷积层(Convolutional Layer),分别用blockX_convX表示;
● 3个全连接层(Fully connected Layer),用classifier表示;
● 5个池化层(Pool layer)。