本文主要是介绍pytorch(六):好莱坞明星识别,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
- 🍨 本文为🔗365天深度学习训练营 内部限免文章(版权归 K同学啊 所有)
- 🍦 参考文章地址: 🔗深度学习实战训练 | 第6周:好莱坞明星识别
- 🍖 作者:K同学啊 | 接辅导、程序定制
1 开发环境
电脑系统:Windows 10
编译器:Jupter Lab
语言环境:Python 3.8
深度学习环境:Pytorch
2 前期准备
2.1 设置GPU
由于实验所用电脑显卡维集成显卡(intel(r) UHD graphics),因此无法使用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)
2.2 导入数据
import os,PIL,random,pathlib
data_dir_str = 'data/6-data/'
data_dir = pathlib.Path(data_dir_str)
print("data_dir:", data_dir, "\n")data_paths = list(data_dir.glob('*'))
classNames = [str(path).split('\\')[-1] for path in data_paths]
print('classNames:', classNames , '\n')train_transforms = transforms.Compose([transforms.Resize([224, 224]), # resize输入图片transforms.ToTensor(), # 将PIL Image或numpy.ndarray转换成tensortransforms.Normalize(mean=[0.485, 0.456, 0.406],std=[0.229, 0.224, 0.225]) # 从数据集中随机抽样计算得到
])total_data = datasets.ImageFolder(data_dir_str, transform=train_transforms)
print(total_data)
print(total_data.class_to_idx)
结果输出如下:
2.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])
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
结果输出如下:
3 调用官方的VGG16模型
from torchvision.models import vgg16# 加载预训练模型,并且对模型进行微调
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(classNames)) # 修改vgg16模型中最后一层全连接层,输出目标类别个数
model.to(device)
print(model)
运行后可看到正在下载预训练模型文件
4 训练模型
4.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与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
4.2 编写测试函数
def test(dataloader, model, loss_fn):size = len(dataloader.dataset) # 测试集的大小num_batches = len(dataloader) # 批次数目test_loss, test_acc = 0, 0# 当不进行训练时,停止梯度更新,节省计算内存消耗with torch.no_grad():for imgs, target in dataloader:imgs, target = imgs.to(device), target.to(device)# 计算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
4.3 设置动态学习率
ef adjust_learning_rate(optimizer, epoch, start_lr):# 每4轮epoch衰减到原来的 0.92lr = start_lr * (0.92 ** (epoch //4))for param_group in optimizer.param_groups:param_group['lr'] = lrlearn_rate = 1e-4 # 初始学习率
# 调用官方动态学习率接口 (与上面的adjust_learning_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) # 选定调整方法
4.4 正式训练
import copyloss_fn = nn.CrossEntropyLoss() # 创建损失函数
epochs = 40train_loss = []
train_acc = []
test_loss = []
test_acc = []best_acc = 0for 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)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 = 'data/6_best_model.pth' # 保存的参数文件名
torch.save(model.state_dict(), PATH)print('Done')
训练速度很慢,尤其在cpu中,更换带GPU的PC机进行训练,训练结果如下所示,准确率较低,无论训练集还是测试集基本都在21%左右。
5 结果可视化
5.1 Loss和Accuracy图
import matplotlib.pyplot as plt
#隐藏警告
import warningswarnings.filterwarnings("ignore") #忽略警告信息
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()
结果显示如下所示:
5.2 指定图片进行预测
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)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/Anglelina Jolie/002_8f8da10e.jpg',model=model,transform=train_transforms,classes=classes)
由于之前训练不理想,这里测试了几次都没有预测正确。
5.3 模型评估
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)
输出模型在训练时最好的结果,由之前训练时保存的best_model得出,输出结果如下,test的准确率与上面的训练结果一致,但loss值有点小差异。
6 模型优化
6.1 参数调整
① 初始学习率:之前的梯度下降很慢,因此增大初始学习率,从之前的e-4调整为e-3
② 学习率更新函数:将之前每4轮更新一次学习率更改为每10轮更新
③优化器:将SGD更改为Adam
learn_rate = 1e-3 # 初始学习率
# 调用官方动态学习率接口(与上面的adjust_learning_rate等价)
lambda1 = lambda epoch: 0.92 ** (epoch // 10)
#optimizer = torch.optim.SGD(model.parameters(), lr=learn_rate)
optimizer = torch.optim.Adam(model.parameters(), lr=learn_rate)
scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda1)
调整后训练结果如下所示,训练集准确率提高到80.1%,测试集准确率提高到44.2%
6.2 模型改进
从上面参数修改后的结果图看,测试集的loss始终降不下去,因此对模型进行修改,引入BN层和dropout。
# 修改classifier模型的第6层(即:(6):Linear(in_features=4096, out_features=2, bias=True))
# 注意查看打印的模型
# model.classifier._modules['6'] = nn.Linear(4096, len(classNames)) # 修改vgg16模型中最后一层全连接层,输出目标类别个数
model.classifier = nn.Sequential(# 14nn.Linear(25088, 1024),nn.BatchNorm1d(1024),# nn.ReLU(True),nn.Dropout(0.4),# 15nn.Linear(1024, 128),nn.BatchNorm1d(128),# nn.ReLU(True),nn.Dropout(0.4),# 16nn.Linear(128, len(classNames)),nn.Softmax())
model.to(device)
print(model)
修改后,输出网络模型结果如下:
保留6.1的参数修改,再次进行训练,训练结果如下,其中最好的训练结果为第13个epoch,训练集准确率为100%,测试集准确率为59.2%。
这篇关于pytorch(六):好莱坞明星识别的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!