- 🍨 本文为🔗365天深度学习训练营 中的学习记录博客
- 🍦 参考文章:Pytorch实战 | 第P4周:猴痘病识别
- 🍖 原作者:K同学啊|接辅导、项目定制
目录
一、课题背景和开发环境
📌第P3周:猴痘病识别📌
- 难度:新手入门⭐
- 语言:Python3、Pytorch
🍺要求:
- 训练过程中保存效果最好的模型参数。
- 加载最佳模型参数识别本地的一张图片。
- 调整网络结构使测试集accuracy到达88%(重点)。
🍻拔高(可选):
- 调整模型参数并观察测试集的准确率变化。
- 尝试设置动态学习率。
- 测试集accuracy到达90%。
本周的代码相对于上周增加指定图片预测与保存并加载模型这个两个模块,在学习这个两知识点后,时间有余的同学请自由探索更佳的模型结构以提升模型是识别准确率,模型的搭建是深度学习程度的重点。
开发环境
- 电脑系统:Windows 10
- 语言环境:Python 3.8.2
- 编译器:无(直接在cmd.exe内运行)
- 深度学习环境:Pytorch
- 显卡及显存:NVIDIA GeForce GTX 1660 Ti 12G
- CUDA版本:Release 10.0, V10.0.130(
cmd
输入nvcc -V
或nvcc --version
指令可查看) - 数据:🔗百度网盘
二、前期准备
1.设置GPU
如果设备上支持GPU就使用GPU,否则使用CPU
import torch
import torchvision
if __name__=='__main__':
''' 设置GPU '''
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print("Using {} device".format(device))
Using cuda device
2.导入数据并划分数据集
import os
import PIL
import random
import pathlib
import warnings
import numpy as np
import matplotlib.pyplot as plt
''' 读取本地数据集并划分训练集与测试集 '''
def localDataset(data_dir):
data_dir = pathlib.Path(data_dir)
# 读取本地数据集
data_paths = list(data_dir.glob('*'))
classeNames = [str(path).split("\\")[-1] for path in data_paths]
print('ClassName', classeNames, '\n')
# 关于transforms.Compose的更多介绍可以参考:https://blog.csdn.net/qq_38251616/article/details/124878863
train_transforms = torchvision.transforms.Compose([
torchvision.transforms.Resize([224, 224]), # 将输入图片resize成统一尺寸
torchvision.transforms.ToTensor(), # 将PIL Image或numpy.ndarray转换为tensor,并归一化到[0,1]之间
torchvision.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 = torchvision.datasets.ImageFolder(data_dir, transform=train_transforms)
print(total_data, '\n')
print(total_data.class_to_idx)
# 划分训练集与测试集
train_size = int(0.8 * len(total_data))
test_size = len(total_data) - train_size
print('train_size', train_size, ', test_size', test_size, '\n')
train_dataset, test_dataset = torch.utils.data.random_split(total_data, [train_size, test_size])
return classeNames, train_dataset, test_dataset
root = 'data'
data_dir = os.path.join(root, 'skin_photos')
classeNames, train_ds, test_ds = localDataset(data_dir)
ClassName ['Monkeypox', 'Others']
Dataset ImageFolder
Number of datapoints: 2142
Root location: data\skin_photos
StandardTransform
Transform: Compose(
Resize(size=[224, 224], interpolation=bilinear)
ToTensor()
Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
)
{'Monkeypox': 0, 'Others': 1}
train_size 1713 , test_size 429
3.加载数据
''' 加载数据,并设置batch_size '''
def loadData(train_ds, test_ds, batch_size=32, root='', show_flag=False):
# 从 train_ds 加载训练集
train_dl = torch.utils.data.DataLoader(train_ds,
batch_size=batch_size,
shuffle=True,
num_workers=1)
# 从 test_ds 加载测试集
test_dl = torch.utils.data.DataLoader(test_ds,
batch_size=batch_size,
shuffle=True,
num_workers=1)
# 取一个批次查看数据格式
# 数据的shape为:[batch_size, channel, height, weight]
# 其中batch_size为自己设定,channel,height和weight分别是图片的通道数,高度和宽度。
for X, y in test_dl:
print('Shape of X [N, C, H, W]: ', X.shape)
print('Shape of y: ', y.shape, y.dtype, '\n')
break
imgs, labels = next(iter(train_dl))
print('Image shape: ', imgs.shape, '\n')
# torch.Size([32, 3, 224, 224]) # 所有数据集中的图像都是224*224的RGB图
displayData(imgs, root, show_flag)
return train_dl, test_dl
batch_size = 32
train_dl, test_dl = loadData(train_ds, test_ds, batch_size, root, False)
Shape of X [N, C, H, W]: torch.Size([32, 3, 224, 224])
Shape of y: torch.Size([32]) torch.int64
Image shape: torch.Size([32, 3, 224, 224])
这次的图像比较有冲击性,这里就不放可视化的图片了
三、构建简单的CNN网络
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.conv1=nn.Sequential(
nn.Conv2d(3, 12, kernel_size=5, padding=0), # 12*220*220
nn.BatchNorm2d(12),
nn.ReLU()
)
self.conv2=nn.Sequential(
nn.Conv2d(12, 12, kernel_size=5, padding=0), # 12*216*216
nn.BatchNorm2d(12),
nn.ReLU()
)
self.pool3=nn.Sequential(
nn.MaxPool2d(2) # 12*108*108
)
self.conv4=nn.Sequential(
nn.Conv2d(12, 24, kernel_size=5, padding=0), # 24*104*104
nn.BatchNorm2d(24),
nn.ReLU()
)
self.conv5=nn.Sequential(
nn.Conv2d(24, 24, kernel_size=5, padding=0), # 24*100*100
nn.BatchNorm2d(24),
nn.ReLU()
)
self.pool6=nn.Sequential(
nn.MaxPool2d(2) # 24*50*50
)
self.conv7=nn.Sequential(
nn.Conv2d(24, 48, kernel_size=5, padding=0), # 48*46*46
nn.BatchNorm2d(48),
nn.ReLU()
)
self.conv8=nn.Sequential(
nn.Conv2d(48, 48, kernel_size=5, padding=0), # 48*42*42
nn.BatchNorm2d(48),
nn.ReLU()
)
self.pool9=nn.Sequential(
nn.MaxPool2d(2) # 48*21*21
)
self.fc=nn.Sequential(
nn.Linear(48*21*21, num_classes)
)
def forward(self, x):
batch_size = x.size(0)
x = self.conv1(x) # 卷积-BN-激活
x = self.conv2(x) # 卷积-BN-激活
x = self.pool3(x) # 池化
x = self.conv4(x) # 卷积-BN-激活
x = self.conv5(x) # 卷积-BN-激活
x = self.pool6(x) # 池化
x = self.conv7(x) # 卷积-BN-激活
x = self.conv8(x) # 卷积-BN-激活
x = self.pool9(x) # 池化
x = x.view(batch_size, -1) # flatten 变成全连接网络需要的输入 (batch, 24*50*50) ==> (batch, -1), -1 此处自动算出的是21168
x = self.fc(x)
return x
if __name__=='__main__':
''' 设置GPU '''
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print("Using {} device".format(device))
''' 调用并将模型转移到GPU中(我们模型运行均在GPU中进行) '''
model = Model().to(device)
''' 显示网络结构 '''
summary(model)
print(model)
Using cuda device
=================================================================
Layer (type:depth-idx) Param #
=================================================================
Model --
├─Sequential: 1-1 --
│ └─Conv2d: 2-1 912
│ └─BatchNorm2d: 2-2 24
│ └─ReLU: 2-3 --
├─Sequential: 1-2 --
│ └─Conv2d: 2-4 3,612
│ └─BatchNorm2d: 2-5 24
│ └─ReLU: 2-6 --
├─Sequential: 1-3 --
│ └─MaxPool2d: 2-7 --
├─Sequential: 1-4 --
│ └─Conv2d: 2-8 7,224
│ └─BatchNorm2d: 2-9 48
│ └─ReLU: 2-10 --
├─Sequential: 1-5 --
│ └─Conv2d: 2-11 14,424
│ └─BatchNorm2d: 2-12 48
│ └─ReLU: 2-13 --
├─Sequential: 1-6 --
│ └─MaxPool2d: 2-14 --
├─Sequential: 1-7 --
│ └─Conv2d: 2-15 28,848
│ └─BatchNorm2d: 2-16 96
│ └─ReLU: 2-17 --
├─Sequential: 1-8 --
│ └─Conv2d: 2-18 57,648
│ └─BatchNorm2d: 2-19 96
│ └─ReLU: 2-20 --
├─Sequential: 1-9 --
│ └─MaxPool2d: 2-21 --
├─Sequential: 1-10 --
│ └─Linear: 2-22 42,338
=================================================================
Total params: 155,342
Trainable params: 155,342
Non-trainable params: 0
=================================================================
Model(
(conv1): Sequential(
(0): Conv2d(3, 12, kernel_size=(5, 5), stride=(1, 1))
(1): BatchNorm2d(12, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(2): ReLU()
)
(conv2): Sequential(
(0): Conv2d(12, 12, kernel_size=(5, 5), stride=(1, 1))
(1): BatchNorm2d(12, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(2): ReLU()
)
(pool3): Sequential(
(0): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
)
(conv4): Sequential(
(0): Conv2d(12, 24, kernel_size=(5, 5), stride=(1, 1))
(1): BatchNorm2d(24, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(2): ReLU()
)
(conv5): Sequential(
(0): Conv2d(24, 24, kernel_size=(5, 5), stride=(1, 1))
(1): BatchNorm2d(24, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(2): ReLU()
)
(pool6): Sequential(
(0): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
)
(conv7): Sequential(
(0): Conv2d(24, 48, kernel_size=(5, 5), stride=(1, 1))
(1): BatchNorm2d(48, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(2): ReLU()
)
(conv8): Sequential(
(0): Conv2d(48, 48, kernel_size=(5, 5), stride=(1, 1))
(1): BatchNorm2d(48, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(2): ReLU()
)
(pool9): Sequential(
(0): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
)
(fc): Sequential(
(0): Linear(in_features=21168, out_features=2, bias=True)
)
)
四、训练模型
1.设置超参数
loss_fn = nn.CrossEntropyLoss() # 创建损失函数
learn_rate = 1e-4 # 学习率
opt = torch.optim.Adam(model.parameters(),lr=learn_rate)
2.编写训练函数
optimizer.zero_grad()
loss.backward()
optimizer.step()
关于以上三个函数,我在之前的文章中有做说明,这里不再赘述
# 训练循环
def train(dataloader, model, loss_fn, optimizer):
size = len(dataloader.dataset) # 训练集的大小
num_batches = len(dataloader) # 批次数目
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
3.编写测试函数
测试函数和训练函数大致相同,但是由于不进行梯度下降对网络权重进行更新,所以不需要传入优化器
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
4.正式训练
model.train()
model.eval()
关于以上两个个函数,我在之前的文章中有做说明,这里不再赘述
import time
start_epoch = 0
epochs = 50
train_loss = []
train_acc = []
test_loss = []
test_acc = []
''' 加载之前保存的模型 '''
if not os.path.exists(output) or not os.path.isdir(output):
os.makedirs(output)
if start_epoch > 0:
resumeFile = os.path.join(output, 'epoch'+str(start_epoch)+'.pkl')
if not os.path.exists(resumeFile) or not os.path.isfile(resumeFile):
start_epoch = 0
else:
model.load_state_dict(torch.load(resumeFile)) # 加载模型参数
''' 开始训练模型 '''
epoch_best_acc = 0
print('\nStart training...')
for epoch in range(start_epoch, epochs):
model.train()
epoch_train_acc, epoch_train_loss = train(train_dl, model, loss_fn, opt)
model.eval()
epoch_test_acc, epoch_test_loss = test(test_dl, model, loss_fn)
train_acc.append(epoch_train_acc)
train_loss.append(epoch_train_loss)
test_acc.append(epoch_test_acc)
test_loss.append(epoch_test_loss)
template = ('Epoch:{:2d}, Train_acc:{:.1f}%, Train_loss:{:.3f}, Test_acc:{:.1f}%,Test_loss:{:.3f}')
print(time.strftime('[%Y-%m-%d %H:%M:%S]'), template.format(epoch+1, epoch_train_acc*100, epoch_train_loss, epoch_test_acc*100, epoch_test_loss))
if epoch_test_acc>epoch_best_acc:
epoch_best_acc = epoch_test_acc
print(('acc = {:.1f}%, saving model to best.pkl').format(epoch_best_acc*100))
saveFile = os.path.join(output, 'best.pkl')
torch.save(model.state_dict(), saveFile)
print('Done\n')
''' 保存模型参数 '''
saveFile = os.path.join('output', 'epoch'+str(epochs)+'.pkl')
torch.save(model.state_dict(), saveFile)
Start training...
[2022-10-18 14:12:53] Epoch: 1, Train_acc:65.5%, Train_loss:0.631, Test_acc:70.6%,Test_loss:0.669
acc = 70.6%, saving model to best.pkl
[2022-10-18 14:13:21] Epoch: 2, Train_acc:76.8%, Train_loss:0.483, Test_acc:80.2%,Test_loss:0.467
acc = 80.2%, saving model to best.pkl
[2022-10-18 14:13:48] Epoch: 3, Train_acc:86.5%, Train_loss:0.335, Test_acc:84.1%,Test_loss:0.404
acc = 84.1%, saving model to best.pkl
[2022-10-18 14:14:16] Epoch: 4, Train_acc:89.9%, Train_loss:0.267, Test_acc:85.3%,Test_loss:0.348
acc = 85.3%, saving model to best.pkl
[2022-10-18 14:14:44] Epoch: 5, Train_acc:94.2%, Train_loss:0.204, Test_acc:86.0%,Test_loss:0.348
acc = 86.0%, saving model to best.pkl
[2022-10-18 14:15:11] Epoch: 6, Train_acc:95.7%, Train_loss:0.157, Test_acc:86.5%,Test_loss:0.324
acc = 86.5%, saving model to best.pkl
[2022-10-18 14:15:38] Epoch: 7, Train_acc:97.1%, Train_loss:0.145, Test_acc:89.0%,Test_loss:0.284
acc = 89.0%, saving model to best.pkl
[2022-10-18 14:16:06] Epoch: 8, Train_acc:97.0%, Train_loss:0.115, Test_acc:88.1%,Test_loss:0.295
[2022-10-18 14:16:33] Epoch: 9, Train_acc:98.3%, Train_loss:0.090, Test_acc:88.1%,Test_loss:0.299
[2022-10-18 14:17:01] Epoch:10, Train_acc:99.1%, Train_loss:0.069, Test_acc:89.5%,Test_loss:0.266
acc = 89.5%, saving model to best.pkl
[2022-10-18 14:17:28] Epoch:11, Train_acc:98.7%, Train_loss:0.069, Test_acc:87.9%,Test_loss:0.307
[2022-10-18 14:17:56] Epoch:12, Train_acc:99.2%, Train_loss:0.056, Test_acc:89.3%,Test_loss:0.289
[2022-10-18 14:18:23] Epoch:13, Train_acc:99.4%, Train_loss:0.045, Test_acc:88.3%,Test_loss:0.299
[2022-10-18 14:18:51] Epoch:14, Train_acc:99.6%, Train_loss:0.037, Test_acc:90.2%,Test_loss:0.286
acc = 90.2%, saving model to best.pkl
[2022-10-18 14:19:18] Epoch:15, Train_acc:99.6%, Train_loss:0.036, Test_acc:87.6%,Test_loss:0.327
[2022-10-18 14:19:46] Epoch:16, Train_acc:99.4%, Train_loss:0.043, Test_acc:88.1%,Test_loss:0.320
[2022-10-18 14:20:14] Epoch:17, Train_acc:99.9%, Train_loss:0.026, Test_acc:88.3%,Test_loss:0.321
[2022-10-18 14:20:42] Epoch:18, Train_acc:100.0%, Train_loss:0.019, Test_acc:89.5%,Test_loss:0.274
[2022-10-18 14:21:09] Epoch:19, Train_acc:100.0%, Train_loss:0.016, Test_acc:88.6%,Test_loss:0.297
[2022-10-18 14:21:37] Epoch:20, Train_acc:99.9%, Train_loss:0.013, Test_acc:89.5%,Test_loss:0.288
[2022-10-18 14:22:04] Epoch:21, Train_acc:100.0%, Train_loss:0.014, Test_acc:90.2%,Test_loss:0.275
[2022-10-18 14:22:31] Epoch:22, Train_acc:100.0%, Train_loss:0.012, Test_acc:90.0%,Test_loss:0.276
[2022-10-18 14:22:59] Epoch:23, Train_acc:99.9%, Train_loss:0.011, Test_acc:89.3%,Test_loss:0.268
[2022-10-18 14:23:26] Epoch:24, Train_acc:100.0%, Train_loss:0.012, Test_acc:90.0%,Test_loss:0.326
[2022-10-18 14:23:54] Epoch:25, Train_acc:99.9%, Train_loss:0.011, Test_acc:90.2%,Test_loss:0.291
[2022-10-18 14:24:21] Epoch:26, Train_acc:100.0%, Train_loss:0.009, Test_acc:89.0%,Test_loss:0.312
[2022-10-18 14:24:49] Epoch:27, Train_acc:99.9%, Train_loss:0.016, Test_acc:89.3%,Test_loss:0.338
[2022-10-18 14:25:16] Epoch:28, Train_acc:100.0%, Train_loss:0.008, Test_acc:90.2%,Test_loss:0.306
[2022-10-18 14:25:44] Epoch:29, Train_acc:100.0%, Train_loss:0.007, Test_acc:89.0%,Test_loss:0.334
[2022-10-18 14:26:11] Epoch:30, Train_acc:99.9%, Train_loss:0.008, Test_acc:88.8%,Test_loss:0.371
[2022-10-18 14:26:38] Epoch:31, Train_acc:99.9%, Train_loss:0.017, Test_acc:89.7%,Test_loss:0.313
[2022-10-18 14:27:06] Epoch:32, Train_acc:99.8%, Train_loss:0.015, Test_acc:89.3%,Test_loss:0.351
[2022-10-18 14:27:34] Epoch:33, Train_acc:99.9%, Train_loss:0.010, Test_acc:90.4%,Test_loss:0.302
acc = 90.4%, saving model to best.pkl
[2022-10-18 14:28:01] Epoch:34, Train_acc:100.0%, Train_loss:0.006, Test_acc:89.7%,Test_loss:0.328
[2022-10-18 14:28:29] Epoch:35, Train_acc:100.0%, Train_loss:0.006, Test_acc:89.5%,Test_loss:0.326
[2022-10-18 14:28:56] Epoch:36, Train_acc:100.0%, Train_loss:0.007, Test_acc:88.6%,Test_loss:0.356
[2022-10-18 14:29:24] Epoch:37, Train_acc:100.0%, Train_loss:0.005, Test_acc:91.4%,Test_loss:0.310
acc = 91.4%, saving model to best.pkl
[2022-10-18 14:29:51] Epoch:38, Train_acc:100.0%, Train_loss:0.003, Test_acc:90.2%,Test_loss:0.321
[2022-10-18 14:30:18] Epoch:39, Train_acc:100.0%, Train_loss:0.003, Test_acc:90.0%,Test_loss:0.307
[2022-10-18 14:30:46] Epoch:40, Train_acc:100.0%, Train_loss:0.005, Test_acc:90.0%,Test_loss:0.348
[2022-10-18 14:31:13] Epoch:41, Train_acc:100.0%, Train_loss:0.005, Test_acc:90.9%,Test_loss:0.304
[2022-10-18 14:31:41] Epoch:42, Train_acc:100.0%, Train_loss:0.003, Test_acc:90.4%,Test_loss:0.348
[2022-10-18 14:32:08] Epoch:43, Train_acc:100.0%, Train_loss:0.002, Test_acc:90.4%,Test_loss:0.322
[2022-10-18 14:32:36] Epoch:44, Train_acc:100.0%, Train_loss:0.002, Test_acc:90.7%,Test_loss:0.320
[2022-10-18 14:33:03] Epoch:45, Train_acc:100.0%, Train_loss:0.002, Test_acc:90.9%,Test_loss:0.310
[2022-10-18 14:33:31] Epoch:46, Train_acc:100.0%, Train_loss:0.002, Test_acc:91.6%,Test_loss:0.312
acc = 91.6%, saving model to best.pkl
[2022-10-18 14:33:58] Epoch:47, Train_acc:100.0%, Train_loss:0.003, Test_acc:89.5%,Test_loss:0.374
[2022-10-18 14:34:25] Epoch:48, Train_acc:100.0%, Train_loss:0.004, Test_acc:90.7%,Test_loss:0.328
[2022-10-18 14:34:53] Epoch:49, Train_acc:100.0%, Train_loss:0.003, Test_acc:90.7%,Test_loss:0.338
[2022-10-18 14:35:20] Epoch:50, Train_acc:99.8%, Train_loss:0.014, Test_acc:87.4%,Test_loss:0.498
Done
最终结果,最优模型的训练集准确率达到100.0%,测试集准确率达到91.6%。
五、结果可视化
''' 结果可视化 '''
def displayResult(train_acc, test_acc, train_loss, test_loss, start_epoch, epochs, output=''):
# 隐藏警告
warnings.filterwarnings("ignore") # 忽略警告信息
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
plt.rcParams['figure.dpi'] = 100 # 分辨率
epochs_range = range(start_epoch, epochs)
plt.figure('Result Visualization', 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.savefig(os.path.join(output, 'AccuracyLoss.png'))
plt.show()
''' 绘制准确率&损失率曲线图 '''
displayResult(train_acc, test_acc, train_loss, test_loss, start_epoch, epochs, output)
六、保存并加载模型&指定图片进行预测
⭐torch.squeeze()
详解
对数据的维度进行压缩,去掉维数为1的的维度
函数原型:
torch.squeeze(input, dim=None, *, out=None)
参数说明:
- input (Tensor):输入Tensor
- dim (int, optional):如果给定,输入将只在这个维度上被压缩
⭐torch.unsqueeze()
详解
对数据维度进行扩充。给指定位置加上维数为一的维度
函数原型:
torch.unsqueeze(input, dim)
参数说明:
- input (Tensor):输入Tensor
- dim (int):插入单例维度的索引
''' 预测函数 '''
def predict(model, img_path):
img = Image.open(img_path)
train_transforms = torchvision.transforms.Compose([
torchvision.transforms.Resize([224, 224]), # 将输入图片resize成统一尺寸
torchvision.transforms.ToTensor(), # 将PIL Image或numpy.ndarray转换为tensor,并归一化到[0,1]之间
torchvision.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] 从数据集中随机抽样计算得到的。
])
img = train_transforms(img)
img = img.to(device).unsqueeze(0)
output = model(img)
#print(output.argmax(1))
_, indices = torch.max(output, 1)
percentage = torch.nn.functional.softmax(output, dim=1)[0] * 100
perc = percentage[int(indices)].item()
result = classeNames[indices]
print('predicted:', result, perc)
if __name__=='__main__':
''' 设置GPU '''
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print("Using {} device".format(device))
classeNames = ['Monkeypox', 'Others']
''' 保存模型参数 '''
# saveFile = os.path.join(output, 'epoch'+str(epochs)+'.pkl')
# torch.save(model.state_dict(), saveFile)
''' 加载模型参数 '''
new_model = Model().to(device)
new_model.load_state_dict(torch.load(os.path.join('output', 'best.pkl')))
new_model.eval()
''' 指定图片进行预测 '''
img_path = 'data/skin_photos/Monkeypox/M01_01_05.jpg'
# img_path = 'data/skin_photos/Others/NM04_01_00.jpg'
predict(new_model, img_path)
Using cuda device
predicted: Monkeypox 99.92399597167969
七、总结
这次课题用的网络是上次课题的最终优化版本的网络,没有做任何修改。在训练过程中可以明显看到模型在测试集的准确率达到90%左右时,训练集的准确率已经接近100%了,导致后面无法很好的继续收敛下去。增大数据集或者对训练集和测试集做重新划分,能在一定程度上缓解这种状况。
另外,关于动态学习率的设置,目前只做了初步了解。
在优化器内设置 momentum
动量参数,即可对学习率进行动态调整,下面是我找到的一个简单小例子
optimizer = torch.optim.SGD(model.parameters(), lr=1e-4, momentum=0.9)
scheduler = ExponentialLR(optimizer, gamma=0.99)
for epoch in range(start_epoch, epochs):
...
scheduler.step()