YOLOv5-C3模块实现天气识别
- 一、环境配置
- 二、准备数据
- 三、搭建网络结构-YOLO-C3模块
- 四、开始训练
- 五、查看训练结果
- 六、总结(`forward`函数内部没有调用新增加的层,训练所使用的网络结构还是原来的结构,注意通道参数的一致,训练结果待修改)
- 6.1 增加C3模块(网络结构代码已修改,训练结果待修改)
- (1)增加一个C3模块,test_acc=91.6%,增加了4.5%
- (2) 增加两个C3模块,test_acc=92.0%,与(1)相比,增加了0.4%
- 🍨 本文为🔗365天深度学习训练营 中的学习记录博客
- 🍖 原作者:K同学啊 | 接辅导、项目定制
说明:
(1)本次学习着重学习YOLO-C3模块,并比较不同数量下的C3模块对训练结果的test_acc有何影响;
(2)注意:
- 模型每增加一个C3模块,
forward()
函数内部也同步增加一个C3模块;这是因为init
里是定义,forward
是调用;- 每次的训练情况在本文的【总结】部分有详细说明。
一、环境配置
● 语言环境:Python3.7.8
● 编译器:VSCode
● 数据集:天气识别数据集
● 深度学习环境:Pytorch
○ torch 1.13.1
○ torchvision 0.14.1
○ torchsummary 1.5.1
# Yolo-C3模块学习
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") #忽略警告信息print("--------------------------1. 配置环境------------------------")
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print("Device: ", device)
二、准备数据
2.1 打印
classeNames
列表,显示每个文件所属的类别名称
2.2 打印归一化后的类别名称,0
或1
2.3 划分数据集,划分为训练集&测试集,torch.utils.data.DataLoader()
参数详解
2.4 检查数据集的shape
print("--------------------------2.1 导入本地数据------------------------")
import os,PIL,random,pathlib
data_dir = 'D:/jupyter notebook/DL-100-days/datasets/P3-天气识别/weather_photos/'
data_dir = pathlib.Path(data_dir)data_paths = list(data_dir.glob('*'))
classeNames = [str(path).split("\\")[5] for path in data_paths]
print("classesName: ", classeNames)
print("--------------------------2.2 数据集归一化------------------------")
# 关于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] 从数据集中随机抽样计算得到的。
])test_transform = transforms.Compose([transforms.Resize([224, 224]), # 将输入图片resize成统一尺寸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("D:/jupyter notebook/DL-100-days/datasets/P3-天气识别/weather_photos/",transform=train_transforms)
print("tota_data: ", total_data)
print("class_to_idx: ", total_data.class_to_idx)
print("--------------------------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: ", train_dataset)
print("test_dataset: ", test_dataset)batch_size = 4
train_dl = torch.utils.data.DataLoader(train_dataset,batch_size=batch_size,shuffle=True,num_workers=0)
test_dl = torch.utils.data.DataLoader(test_dataset,batch_size=batch_size,shuffle=True,num_workers=0)
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
三、搭建网络结构-YOLO-C3模块
print("--------------------------3.1 创建网络结构------------------------")
import torch.nn.functional as F
'''
定义网络中需要用到的模块
'''
def autopad(k, p=None): # kernel, padding# Pad to 'same'if p is None:p = k // 2 if isinstance(k, int) else [x // 2 for x in k] # auto-padreturn pclass Conv(nn.Module):# Standard convolutiondef __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groupssuper().__init__()self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g, bias=False)self.bn = nn.BatchNorm2d(c2)self.act = nn.SiLU() if act is True else (act if isinstance(act, nn.Module) else nn.Identity())def forward(self, x):return self.act(self.bn(self.conv(x)))class Bottleneck(nn.Module):# Standard bottleneckdef __init__(self, c1, c2, shortcut=True, g=1, e=0.5): # ch_in, ch_out, shortcut, groups, expansionsuper().__init__()c_ = int(c2 * e) # hidden channelsself.cv1 = Conv(c1, c_, 1, 1)self.cv2 = Conv(c_, c2, 3, 1, g=g)self.add = shortcut and c1 == c2def forward(self, x):return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))class C3(nn.Module):# CSP Bottleneck with 3 convolutionsdef __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansionsuper().__init__()c_ = int(c2 * e) # hidden channelsself.cv1 = Conv(c1, c_, 1, 1)self.cv2 = Conv(c1, c_, 1, 1)self.cv3 = Conv(2 * c_, c2, 1) # act=FReLU(c2)self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)))def forward(self, x):return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), dim=1))
'''
用上述模块组建网络
'''
class model_K(nn.Module):def __init__(self):super(model_K, self).__init__()# 卷积模块self.Conv = Conv(3, 32, 3, 2) # C3模块1self.C3_1 = C3(32, 64, 3, 2)# 全连接网络层,用于分类self.classifier = nn.Sequential(nn.Linear(in_features=802816, out_features=100),nn.ReLU(),nn.Linear(in_features=100, out_features=4))def forward(self, x):x = self.Conv(x)x = self.C3_1(x)x = torch.flatten(x, start_dim=1)x = self.classifier(x)return x
'''
打印设备信息、模型结构、模型参数量
'''
device = "cuda" if torch.cuda.is_available() else "cpu"
print("Using {} device".format(device))model = model_K().to(device)
model# 统计模型参数量以及其他指标
import torchsummary as summary
summary.summary(model, (3, 224, 224))
网络结构没有打印出(本来应该打印在
Using cpu device
后边的),原因是没有写成print(model)
(在jupyter notebook
中可以直接打印model的结构),此处只打印了模型参数量信息。
四、开始训练
4.1 设置超参数
4.2 编写训练函数
4.3 编写测试函数
4.4 开始正式训练,epochs==20
📌如果将优化器换成 SGD 会发生什么呢?请自行探索接下来发生的诡异事件的原因。
print("--------------------------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
print("--------------------------4.2 编写测试函数------------------------")
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)# 计算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
print("--------------------------4.3 正式训练------------------------")
import copyoptimizer = torch.optim.Adam(model.parameters(), lr= 1e-4)
loss_fn = nn.CrossEntropyLoss() # 创建损失函数epochs = 20train_loss = []
train_acc = []
test_loss = []
test_acc = []best_acc = 0 # 设置一个最佳准确率,作为最佳模型的判别指标for epoch in range(epochs):model.train()epoch_train_acc, epoch_train_loss = train(train_dl, model, loss_fn, optimizer)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 = './P8_best_model.pth' # 保存的参数文件名
torch.save(model.state_dict(), PATH)
print('Done')
训练20个epoch后,得到的test_acc=87.1%。
五、查看训练结果
print("--------------------------5.1 Accuracy Loss图------------------------")
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.savefig("./P8_Accuracy_Loss.png")
plt.show()
print("--------------------------5.2 模型评估------------------------")
best_model.eval()
epoch_test_acc, epoch_test_loss = test(test_dl, best_model, loss_fn)
epoch_test_acc, epoch_test_loss
# 查看是否与我们记录的最高准确率一致
epoch_test_acc
六、总结(forward
函数内部没有调用新增加的层,训练所使用的网络结构还是原来的结构,注意通道参数的一致,训练结果待修改)
说明:
init
函数内增加或减少层数,forward
函数内部也要统一。注意通道数的计算。
本次学习,总结部分无效。
增加C3模块,forward()函数内部无变化,观察test_acc的值:
C3模块个数 | test_acc |
---|---|
1 | 87.1% |
2 | 91.6% |
3 | 92.0% |
增加C3模块,forward()函数内部也相应增加C3模块,观察test_acc的值:
C3模块个数 | test_acc |
---|---|
1 | 87.1% |
2 | % |
3 | % |
6.1 增加C3模块(网络结构代码已修改,训练结果待修改)
(1)增加一个C3模块,test_acc=91.6%,增加了4.5%
模型定义内容2.0修改如下:
'''
增加一个C3模块
'''
class model_K(nn.Module):def __init__(self):super(model_K, self).__init__()# 卷积模块self.Conv = Conv(3, 32, 3, 2) # C3模块1self.C3_1 = C3(32, 64, 3, 2)# C3模块2self.C3_2 = C3(64, 128, 3, 2)# 全连接网络层,用于分类self.classifier = nn.Sequential(nn.Linear(in_features=802816, out_features=100),nn.ReLU(),nn.Linear(in_features=100, out_features=4))'''此处forward()函数内部没有同步增加一个C3模块'''def forward(self, x):x = self.Conv(x)x = self.C3_1(x)x = self.C3_2(x)x = torch.flatten(x, start_dim=1)x = self.classifier(x)return x
增加一个C3模块后,参数量的变化:
训练结果如下:
可以看到,增加一个C3模块后的test_acc=91.6%,比原来的87.1%增加了4.5%。
Accuracy-Loss图如下所示:
(2) 增加两个C3模块,test_acc=92.0%,与(1)相比,增加了0.4%
epoch=15~17时,test_acc=93.3%;
epoch=18时,test_acc跌至92.0%;
epoch=19时,test_acc跌至88.9%;
epoch=20时,test_acc恢复至92.0%
模型评估得到的epoch_test_acc=93.8%(训练中得到的最高准确率,epoch=14时)
## 6.2 增加C3模块,forward()函数内部同步增加C3模块【报错,通道数对不上,此部分代码需要调整】