- 🍨 本文为 🔗365天深度学习训练营中的学习记录博客
- 🍖 原作者: K同学啊
🍺要求:
- 保存训练过程中的最佳模型权重
- 调用官方的VGG-16网络框架
🍻拔高(可选):
- 测试集准确率达到60%(难度有点大,但是这个过程可以学到不少)
- 手动搭建VGG-16网络框架
🏡 我的环境:
- 语言环境:Python3.8
- 编译器:Jupyter Lab
- 深度学习环境:Pytorch
一、 前期准备
1. 设置GPU
如果设备上支持GPU就使用GPU,否则使用CPU。
python
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
device(type='cuda')
2. 导入数据
python
import os,PIL,random,pathlib
data_dir = '/kaggle/input/human-face-recognization/48-data'
data_dir = pathlib.Path(data_dir)
data_paths = list(data_dir.glob('*'))
classeNames = [str(path).split("\\")[0] for path in data_paths]
classeNames
['/kaggle/input/human-face-recognization/48-data/Angelina Jolie',
'/kaggle/input/human-face-recognization/48-data/Sandra Bullock',
'/kaggle/input/human-face-recognization/48-data/Nicole Kidman',
'/kaggle/input/human-face-recognization/48-data/Megan Fox',
'/kaggle/input/human-face-recognization/48-data/Johnny Depp',
'/kaggle/input/human-face-recognization/48-data/Natalie Portman',
'/kaggle/input/human-face-recognization/48-data/Tom Cruise',
'/kaggle/input/human-face-recognization/48-data/Brad Pitt',
'/kaggle/input/human-face-recognization/48-data/Jennifer Lawrence',
'/kaggle/input/human-face-recognization/48-data/Tom Hanks',
'/kaggle/input/human-face-recognization/48-data/Scarlett Johansson',
'/kaggle/input/human-face-recognization/48-data/Kate Winslet',
'/kaggle/input/human-face-recognization/48-data/Will Smith',
'/kaggle/input/human-face-recognization/48-data/Robert Downey Jr',
'/kaggle/input/human-face-recognization/48-data/Denzel Washington',
'/kaggle/input/human-face-recognization/48-data/Hugh Jackman',
'/kaggle/input/human-face-recognization/48-data/Leonardo DiCaprio']
python
# 关于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
Dataset ImageFolder
Number of datapoints: 1800
Root location: /kaggle/input/human-face-recognization/48-data
StandardTransform
Transform: Compose(
Resize(size=[224, 224], interpolation=bilinear, max_size=None, antialias=True)
ToTensor()
Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
)
python
total_data.class_to_idx
{'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}
3. 划分数据集
python
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
(<torch.utils.data.dataset.Subset at 0x7d17fed77eb0>,
<torch.utils.data.dataset.Subset at 0x7d17fed77e50>)
python
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)
python
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
Shape of X [N, C, H, W]: torch.Size([32, 3, 224, 224])
Shape of y: torch.Size([32]) torch.int64
二、调用官方的VGG-16模型
VGG-16(Visual Geometry Group-16)是由牛津大学视觉几何组(Visual Geometry Group)提出的一种深度卷积神经网络架构,用于图像分类和对象识别任务。VGG-16在2014年被提出,是VGG系列中的一种。VGG-16之所以备受关注,是因为它在ImageNet图像识别竞赛中取得了很好的成绩,展示了其在大规模图像识别任务中的有效性。
以下是VGG-16的主要特点:
- **深度:**VGG-16由16个卷积层和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)。
VGG-16****包含了16个隐藏层(13个卷积层和3个全连接层),故称为 VGG-16
python
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
Using cuda device
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. 编写训练函数
python
# 训练循环
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. 编写测试函数
测试函数和训练函数大致相同,但是由于不进行梯度下降对网络权重进行更新,所以不需要传入优化器。
python
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. 设置动态学习率
python
# 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)
✨ 调用官方动态学习率接口
与上面方法是等价的。
python
# 调用官方动态学习率接口时使用
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. 正式训练
model.train()
、model.eval()
训练营往期文章中有详细的介绍。请注意观察我是如何保存最佳模型,与TensorFlow2的保存方式有何异同。
python
import copy
loss_fn = nn.CrossEntropyLoss() # 创建损失函数
epochs = 100
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')
Epoch: 1, Train_acc:5.4%, Train_loss:2.918, Test_acc:3.9%, Test_loss:2.843, Lr:1.00E-04
Epoch: 2, Train_acc:4.8%, Train_loss:2.891, Test_acc:5.6%, Test_loss:2.815, Lr:1.00E-04
Epoch: 3, Train_acc:7.6%, Train_loss:2.863, Test_acc:7.8%, Test_loss:2.792, Lr:1.00E-04
Epoch: 4, Train_acc:8.3%, Train_loss:2.830, Test_acc:11.9%, Test_loss:2.763, Lr:9.20E-05
Epoch: 5, Train_acc:10.6%, Train_loss:2.805, Test_acc:12.8%, Test_loss:2.739, Lr:9.20E-05
Epoch: 6, Train_acc:12.1%, Train_loss:2.759, Test_acc:13.6%, Test_loss:2.724, Lr:9.20E-05
Epoch: 7, Train_acc:14.7%, Train_loss:2.728, Test_acc:14.4%, Test_loss:2.698, Lr:9.20E-05
Epoch: 8, Train_acc:12.9%, Train_loss:2.727, Test_acc:14.4%, Test_loss:2.682, Lr:8.46E-05
Epoch: 9, Train_acc:13.3%, Train_loss:2.701, Test_acc:14.7%, Test_loss:2.672, Lr:8.46E-05
Epoch:10, Train_acc:13.0%, Train_loss:2.678, Test_acc:15.0%, Test_loss:2.650, Lr:8.46E-05
Epoch:11, Train_acc:14.6%, Train_loss:2.672, Test_acc:16.1%, Test_loss:2.639, Lr:8.46E-05
Epoch:12, Train_acc:14.9%, Train_loss:2.651, Test_acc:16.7%, Test_loss:2.633, Lr:7.79E-05
Epoch:13, Train_acc:15.0%, Train_loss:2.648, Test_acc:16.7%, Test_loss:2.622, Lr:7.79E-05
Epoch:14, Train_acc:16.0%, Train_loss:2.624, Test_acc:16.7%, Test_loss:2.603, Lr:7.79E-05
Epoch:15, Train_acc:16.3%, Train_loss:2.619, Test_acc:17.5%, Test_loss:2.598, Lr:7.79E-05
Epoch:16, Train_acc:14.9%, Train_loss:2.611, Test_acc:17.5%, Test_loss:2.590, Lr:7.16E-05
Epoch:17, Train_acc:16.8%, Train_loss:2.593, Test_acc:17.8%, Test_loss:2.576, Lr:7.16E-05
Epoch:18, Train_acc:17.2%, Train_loss:2.591, Test_acc:18.3%, Test_loss:2.558, Lr:7.16E-05
Epoch:19, Train_acc:17.6%, Train_loss:2.590, Test_acc:18.3%, Test_loss:2.558, Lr:7.16E-05
Epoch:20, Train_acc:16.5%, Train_loss:2.560, Test_acc:18.3%, Test_loss:2.557, Lr:6.59E-05
Epoch:21, Train_acc:17.1%, Train_loss:2.548, Test_acc:18.6%, Test_loss:2.529, Lr:6.59E-05
Epoch:22, Train_acc:16.9%, Train_loss:2.556, Test_acc:18.6%, Test_loss:2.540, Lr:6.59E-05
Epoch:23, Train_acc:19.2%, Train_loss:2.527, Test_acc:18.6%, Test_loss:2.527, Lr:6.59E-05
Epoch:24, Train_acc:18.6%, Train_loss:2.512, Test_acc:18.6%, Test_loss:2.520, Lr:6.06E-05
Epoch:25, Train_acc:18.8%, Train_loss:2.518, Test_acc:18.9%, Test_loss:2.502, Lr:6.06E-05
Epoch:26, Train_acc:19.4%, Train_loss:2.513, Test_acc:18.9%, Test_loss:2.510, Lr:6.06E-05
Epoch:27, Train_acc:17.9%, Train_loss:2.509, Test_acc:19.7%, Test_loss:2.508, Lr:6.06E-05
Epoch:28, Train_acc:19.3%, Train_loss:2.482, Test_acc:19.7%, Test_loss:2.495, Lr:5.58E-05
Epoch:29, Train_acc:17.9%, Train_loss:2.498, Test_acc:19.4%, Test_loss:2.492, Lr:5.58E-05
Epoch:30, Train_acc:18.3%, Train_loss:2.472, Test_acc:19.4%, Test_loss:2.494, Lr:5.58E-05
Epoch:31, Train_acc:18.6%, Train_loss:2.472, Test_acc:19.4%, Test_loss:2.495, Lr:5.58E-05
Epoch:32, Train_acc:18.8%, Train_loss:2.476, Test_acc:19.4%, Test_loss:2.471, Lr:5.13E-05
Epoch:33, Train_acc:20.3%, Train_loss:2.469, Test_acc:19.7%, Test_loss:2.479, Lr:5.13E-05
Epoch:34, Train_acc:19.0%, Train_loss:2.472, Test_acc:20.0%, Test_loss:2.478, Lr:5.13E-05
Epoch:35, Train_acc:19.4%, Train_loss:2.453, Test_acc:20.0%, Test_loss:2.461, Lr:5.13E-05
Epoch:36, Train_acc:20.4%, Train_loss:2.453, Test_acc:20.0%, Test_loss:2.463, Lr:4.72E-05
Epoch:37, Train_acc:19.0%, Train_loss:2.440, Test_acc:20.3%, Test_loss:2.465, Lr:4.72E-05
Epoch:38, Train_acc:21.0%, Train_loss:2.434, Test_acc:20.6%, Test_loss:2.460, Lr:4.72E-05
Epoch:39, Train_acc:20.3%, Train_loss:2.432, Test_acc:20.6%, Test_loss:2.445, Lr:4.72E-05
Epoch:40, Train_acc:20.2%, Train_loss:2.421, Test_acc:20.6%, Test_loss:2.432, Lr:4.34E-05
Epoch:41, Train_acc:18.2%, Train_loss:2.430, Test_acc:20.6%, Test_loss:2.438, Lr:4.34E-05
Epoch:42, Train_acc:20.1%, Train_loss:2.431, Test_acc:20.6%, Test_loss:2.428, Lr:4.34E-05
Epoch:43, Train_acc:19.4%, Train_loss:2.431, Test_acc:20.6%, Test_loss:2.437, Lr:4.34E-05
Epoch:44, Train_acc:19.9%, Train_loss:2.428, Test_acc:20.6%, Test_loss:2.435, Lr:4.00E-05
Epoch:45, Train_acc:23.0%, Train_loss:2.391, Test_acc:20.6%, Test_loss:2.431, Lr:4.00E-05
Epoch:46, Train_acc:21.9%, Train_loss:2.402, Test_acc:20.6%, Test_loss:2.435, Lr:4.00E-05
Epoch:47, Train_acc:19.2%, Train_loss:2.421, Test_acc:20.8%, Test_loss:2.422, Lr:4.00E-05
Epoch:48, Train_acc:20.6%, Train_loss:2.408, Test_acc:20.8%, Test_loss:2.408, Lr:3.68E-05
Epoch:49, Train_acc:22.9%, Train_loss:2.387, Test_acc:20.6%, Test_loss:2.417, Lr:3.68E-05
Epoch:50, Train_acc:20.8%, Train_loss:2.403, Test_acc:20.6%, Test_loss:2.412, Lr:3.68E-05
Epoch:51, Train_acc:20.2%, Train_loss:2.408, Test_acc:20.6%, Test_loss:2.416, Lr:3.68E-05
Epoch:52, Train_acc:22.4%, Train_loss:2.394, Test_acc:20.6%, Test_loss:2.400, Lr:3.38E-05
Epoch:53, Train_acc:22.4%, Train_loss:2.388, Test_acc:20.6%, Test_loss:2.405, Lr:3.38E-05
Epoch:54, Train_acc:21.7%, Train_loss:2.403, Test_acc:20.6%, Test_loss:2.403, Lr:3.38E-05
Epoch:55, Train_acc:21.2%, Train_loss:2.387, Test_acc:20.6%, Test_loss:2.408, Lr:3.38E-05
Epoch:56, Train_acc:21.3%, Train_loss:2.365, Test_acc:20.6%, Test_loss:2.398, Lr:3.11E-05
Epoch:57, Train_acc:21.6%, Train_loss:2.378, Test_acc:20.8%, Test_loss:2.404, Lr:3.11E-05
Epoch:58, Train_acc:22.8%, Train_loss:2.368, Test_acc:21.1%, Test_loss:2.399, Lr:3.11E-05
Epoch:59, Train_acc:20.9%, Train_loss:2.380, Test_acc:21.4%, Test_loss:2.380, Lr:3.11E-05
Epoch:60, Train_acc:21.6%, Train_loss:2.374, Test_acc:21.4%, Test_loss:2.383, Lr:2.86E-05
Epoch:61, Train_acc:21.8%, Train_loss:2.379, Test_acc:21.4%, Test_loss:2.379, Lr:2.86E-05
Epoch:62, Train_acc:22.6%, Train_loss:2.370, Test_acc:21.4%, Test_loss:2.400, Lr:2.86E-05
Epoch:63, Train_acc:20.8%, Train_loss:2.387, Test_acc:21.4%, Test_loss:2.377, Lr:2.86E-05
Epoch:64, Train_acc:20.6%, Train_loss:2.380, Test_acc:21.9%, Test_loss:2.386, Lr:2.63E-05
Epoch:65, Train_acc:21.2%, Train_loss:2.371, Test_acc:21.9%, Test_loss:2.374, Lr:2.63E-05
Epoch:66, Train_acc:22.0%, Train_loss:2.350, Test_acc:21.9%, Test_loss:2.396, Lr:2.63E-05
Epoch:67, Train_acc:21.5%, Train_loss:2.357, Test_acc:21.9%, Test_loss:2.383, Lr:2.63E-05
Epoch:68, Train_acc:22.7%, Train_loss:2.357, Test_acc:22.2%, Test_loss:2.379, Lr:2.42E-05
Epoch:69, Train_acc:23.6%, Train_loss:2.335, Test_acc:22.2%, Test_loss:2.382, Lr:2.42E-05
Epoch:70, Train_acc:22.6%, Train_loss:2.363, Test_acc:22.2%, Test_loss:2.374, Lr:2.42E-05
Epoch:71, Train_acc:21.2%, Train_loss:2.355, Test_acc:22.2%, Test_loss:2.365, Lr:2.42E-05
Epoch:72, Train_acc:21.0%, Train_loss:2.357, Test_acc:22.2%, Test_loss:2.361, Lr:2.23E-05
Epoch:73, Train_acc:23.3%, Train_loss:2.346, Test_acc:22.5%, Test_loss:2.379, Lr:2.23E-05
Epoch:74, Train_acc:23.1%, Train_loss:2.345, Test_acc:22.5%, Test_loss:2.368, Lr:2.23E-05
Epoch:75, Train_acc:21.2%, Train_loss:2.356, Test_acc:22.5%, Test_loss:2.362, Lr:2.23E-05
Epoch:76, Train_acc:20.6%, Train_loss:2.366, Test_acc:22.5%, Test_loss:2.351, Lr:2.05E-05
Epoch:77, Train_acc:22.1%, Train_loss:2.344, Test_acc:22.5%, Test_loss:2.365, Lr:2.05E-05
Epoch:78, Train_acc:22.2%, Train_loss:2.351, Test_acc:22.5%, Test_loss:2.333, Lr:2.05E-05
Epoch:79, Train_acc:22.4%, Train_loss:2.343, Test_acc:22.5%, Test_loss:2.370, Lr:2.05E-05
Epoch:80, Train_acc:21.3%, Train_loss:2.340, Test_acc:23.1%, Test_loss:2.369, Lr:1.89E-05
Epoch:81, Train_acc:22.7%, Train_loss:2.333, Test_acc:23.1%, Test_loss:2.339, Lr:1.89E-05
Epoch:82, Train_acc:23.3%, Train_loss:2.335, Test_acc:22.8%, Test_loss:2.372, Lr:1.89E-05
Epoch:83, Train_acc:21.5%, Train_loss:2.340, Test_acc:22.8%, Test_loss:2.346, Lr:1.89E-05
Epoch:84, Train_acc:23.7%, Train_loss:2.329, Test_acc:22.8%, Test_loss:2.372, Lr:1.74E-05
Epoch:85, Train_acc:21.7%, Train_loss:2.339, Test_acc:22.8%, Test_loss:2.348, Lr:1.74E-05
Epoch:86, Train_acc:23.0%, Train_loss:2.318, Test_acc:23.1%, Test_loss:2.362, Lr:1.74E-05
Epoch:87, Train_acc:20.7%, Train_loss:2.339, Test_acc:23.3%, Test_loss:2.358, Lr:1.74E-05
Epoch:88, Train_acc:22.6%, Train_loss:2.347, Test_acc:23.3%, Test_loss:2.342, Lr:1.60E-05
Epoch:89, Train_acc:21.6%, Train_loss:2.325, Test_acc:23.3%, Test_loss:2.343, Lr:1.60E-05
Epoch:90, Train_acc:23.5%, Train_loss:2.329, Test_acc:23.3%, Test_loss:2.351, Lr:1.60E-05
Epoch:91, Train_acc:22.4%, Train_loss:2.326, Test_acc:23.3%, Test_loss:2.359, Lr:1.60E-05
Epoch:92, Train_acc:23.3%, Train_loss:2.317, Test_acc:23.3%, Test_loss:2.347, Lr:1.47E-05
Epoch:93, Train_acc:23.4%, Train_loss:2.310, Test_acc:23.3%, Test_loss:2.347, Lr:1.47E-05
Epoch:94, Train_acc:23.1%, Train_loss:2.322, Test_acc:23.3%, Test_loss:2.359, Lr:1.47E-05
Epoch:95, Train_acc:22.8%, Train_loss:2.321, Test_acc:23.3%, Test_loss:2.348, Lr:1.47E-05
Epoch:96, Train_acc:24.0%, Train_loss:2.319, Test_acc:23.3%, Test_loss:2.349, Lr:1.35E-05
Epoch:97, Train_acc:21.5%, Train_loss:2.336, Test_acc:23.3%, Test_loss:2.329, Lr:1.35E-05
Epoch:98, Train_acc:22.4%, Train_loss:2.321, Test_acc:23.3%, Test_loss:2.340, Lr:1.35E-05
Epoch:99, Train_acc:23.6%, Train_loss:2.329, Test_acc:23.3%, Test_loss:2.347, Lr:1.35E-05
Epoch:100, Train_acc:23.2%, Train_loss:2.314, Test_acc:23.6%, Test_loss:2.350, Lr:1.24E-05
Done
四、 结果可视化
1. Loss与Accuracy图
python
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 #分辨率
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()
2. 指定图片进行预测
python
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}')
python
# 预测训练集中的某张照片
predict_one_image(image_path='/kaggle/input/human-face-recognization/48-data/Scarlett Johansson/004_bb16ac65.jpg',
model=model,
transform=train_transforms,
classes=classes)
预测结果是:Scarlett Johansson
3. 模型评估
python
best_model.eval()
epoch_test_acc, epoch_test_loss = test(test_dl, best_model, loss_fn)
python
epoch_test_acc, epoch_test_loss
(0.2361111111111111, 2.3469764590263367)
python
# 查看是否与我们记录的最高准确率一致
epoch_test_acc
0.2361111111111111
五、个人总结
学会了如何调用官方接口来实现VGG-16模型同时在测试集的准确率上还得提高,比较困难。