目录
一、前期准备
1.1设置GPU
1.2导入数据集
1.3划分数据集
二、网络结构
2.1思路解析
2.2模型代码
三、训练运行
3.1训练
3.2指定图片进行预测
本文为[365天深度学习训练营]内部限免文章(版权归 *K同学啊* 所有)
作者:[K同学啊]
任务类型:自主探索
●任务难度:偏难
●任务描述:
○请根据J1~J3周的内容自由探索ResNet与DenseNet结合的可能性
○是否可以根据两种的特性构建一个新的模型框架?
○请用之前的任一图像识别任务验证改进后模型的效果
使用pytorch框架,还用前两周的数据集:百度网盘 请输入提取码(提取码:0mhm)
这部分与J2周内容基本一致:深度学习第J2周:ResNet50V2算法实战与解析_牛大了2022的博客-CSDN博客
如果设备上支持GPU就使用GPU,否则使用CPU。尽量配置好GPU使用。
import os,PIL,random,pathlib
import torch
import torch.nn as nn
import torchvision.transforms as transforms
import torchvision
from torchvision import transforms, datasets
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(device)
本地数据集位于./data/bird_photos/目录下。
data_dir = './data/bird_photos/'
data_dir = pathlib.Path(data_dir)
data_paths = list(data_dir.glob('*'))
classeNames = [str(path).split("\\")[2] for path in data_paths]
print(classeNames)
image_count = len(list(data_dir.glob('*/*')))
print("图片总数为:",image_count)
数据预处理一下,图形变换,输出:用到torchvision.transforms.Compose()
类,有兴趣的朋友可以参考这篇博客:torchvision.transforms.Compose()详解【Pytorch手册】
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("./data/bird_photos/", transform=train_transforms)
print(total_data.class_to_idx)
{'Bananaquit': 0, 'Black Skimmer': 1, 'Black Throated Bushtiti': 2, 'Cockatoo': 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])
batch_size = 32
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
Shape of X [N, C, H, W]: torch.Size([32, 3, 224, 224])
Shape of y: torch.Size([32]) torch.int64
通过网上查阅相关资料,发现了一个ResNet与DenseNet结合的网络框架DPN,第二部分实现这个DPN(Dual Path Networks)
Dual Path Networks(DPN)是通过High Order RNN(HORNN)将ResNet和DenseNet进行了融合,所谓的dual path,即一条path是ResNet,另一条path是DenseNet。相关论文的Motivation是通过对ResNet和DenseNet的分解,证明了ResNet更侧重于特征的复用,而DenseNet则更侧重于特征的生成,通过分析两个模型的优劣,将两个模型有针对性的组合起来,提出了DPN。
论文名称:NIPS-2017-dual-path-networks-Paper(谷粉学术上搜Dual Path Networks即可下载)
Dual Path Net:ResNet +DenseNet
DPN把ResNet和DenseNet的优点结合起来,给ResNet加上了薄薄的DenseNet结构,保持了二者复用特征+挖掘特征的能力,同时避免了像原始DenseNet那样臃肿的结构。
上图1是ResNet, 图2 是DenseNet,变粗的部分就是新的网络层的特征,不断与之前的特征concate,注意有多个1x1卷积核。同一个颜色的卷积核代表的是同一个尺度的1x1卷积核,比如,绿色的1x1卷积核代表了是指对第一层的特征进行1x1卷积。而带下划线的1x1卷积核则是为了对concate后的特征进行维度上的整理。图3是对DenseNet的一个改动,假设所有相同颜色的1x1卷积核是共享的,那么图2就可以整理成为图3的格式。图3的左半部分是DenseNet,右半部分是ResNet。回忆在核心论点一中,提到concate是可以等价成为相加的,所以在图2中绿色1x1卷积核、桔色1x1卷积核分别对第一层特征、新特征处理后,再concate进行后面的操作,也就等价于图3中右边通道中二者相加。
图4是提出的DPN,一方面,这个网络结构可以直接从DPN的定义公式得到;另一方面,可以发现,只要把图3 里面的1x1卷积核拆分、整理、变形,也可以得到图4的结构。
上图最右边DPN结构把每个block中每个通道的第一个1x1卷积核合并的结果,和图4的最大不同在于ResNet和DenseNet共享了第一个 1×1 卷积。在实际计算 3×3 卷积时,使用了分组卷积来提升网络的性能。在设计网络的超参时,ResNet的通道数也比DenseNet的通道数多点,防止DenseNet随着层数的增加引发的显存消耗速度过快的问题。和其它网络一样,我们也可以通过堆叠网络块的方式来提升模型的容量。
效果对比:
网络参数
分类效果对比
检测与分割的效果
class Block(nn.Module):
def __init__(self, in_channel, mid_channel, out_channel, dense_channel, stride, groups, is_shortcut=False):
# in_channel,是输入通道数,mid_channel是中间经历的通道数,out_channels是经过一次板块之后的输出通道数。
# dense_channels设置这个参数的原因就是一边进行着resnet方式的卷积运算,另一边也同时进行着dense的卷积计算,之后特征图融合形成新的特征图
super().__init__()
self.is_shortcut = is_shortcut
self.out_channel = out_channel
self.conv1 = nn.Sequential(
nn.Conv2d(in_channel, mid_channel, kernel_size=1, bias=False),
nn.BatchNorm2d(mid_channel),
nn.ReLU()
)
self.conv2 = nn.Sequential(
nn.Conv2d(mid_channel, mid_channel, kernel_size=3, stride=stride, padding=1, groups=groups, bias=False),
nn.BatchNorm2d(mid_channel),
nn.ReLU()
)
self.conv3 = nn.Sequential(
nn.Conv2d(mid_channel, out_channel+dense_channel, kernel_size=1, bias=False),
nn.BatchNorm2d(out_channel+dense_channel)
)
if self.is_shortcut:
self.shortcut = nn.Sequential(
nn.Conv2d(in_channel, out_channel+dense_channel, kernel_size=3, padding=1, stride=stride, bias=False),
nn.BatchNorm2d(out_channel+dense_channel)
)
self.relu = nn.ReLU(inplace=True)
def forward(self, x):
a = x
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
if self.is_shortcut:
a = self.shortcut(a)
d = self.out_channel
x = torch.cat([a[:,:d,:,:] + x[:,:d,:,:], a[:,d:,:,:], x[:,d:,:,:]], dim=1)
x = self.relu(x)
return x
class DPN(nn.Module):
def __init__(self, cfg):
super(DPN, self).__init__()
self.group = cfg['group']
self.in_channel = cfg['in_channel']
mid_channels = cfg['mid_channels']
out_channels = cfg['out_channels']
dense_channels = cfg['dense_channels']
num = cfg['num']
self.conv1 = nn.Sequential(
nn.Conv2d(3, self.in_channel, 7, stride=2, padding=3, bias=False, padding_mode='zeros'),
nn.BatchNorm2d(self.in_channel),
nn.ReLU(),
nn.MaxPool2d(kernel_size=3, stride=2, padding=0)
)
self.conv2 = self._make_layers(mid_channels[0], out_channels[0], dense_channels[0], num[0], stride=1)
self.conv3 = self._make_layers(mid_channels[1], out_channels[1], dense_channels[1], num[1], stride=2)
self.conv4 = self._make_layers(mid_channels[2], out_channels[2], dense_channels[2], num[2], stride=2)
self.conv5 = self._make_layers(mid_channels[3], out_channels[3], dense_channels[3], num[3], stride=2)
self.pool = nn.AdaptiveAvgPool2d((1, 1))
self.fc = nn.Linear(cfg['out_channels'][3] + (num[3]+1) * cfg['dense_channels'][3], cfg['classes']) # fc层需要计算
def _make_layers(self, mid_channel, out_channel, dense_channel, num, stride=2):
layers = []
layers.append(Block(self.in_channel, mid_channel, out_channel, dense_channel, stride=stride, groups=self.group, is_shortcut=True))
# block_1里面is_shortcut=True就是resnet中的shortcut连接,将浅层的特征进行一次卷积之后与进行三次卷积的特征图相加
# 后面几次相同的板块is_shortcut=False简单的理解就是一个多次重复的板块,第一次利用就可以满足浅层特征的利用,后面重复的不在需要
self.in_channel = out_channel + dense_channel*2
# 由于里面包含dense这种一直在叠加的特征图计算,
# 所以第一次是2倍的dense_channel,后面每次一都会多出1倍,所以有(i+2)*dense_channel
for i in range(1, num):
layers.append(Block(self.in_channel, mid_channel, out_channel, dense_channel, stride=1, groups=self.group))
self.in_channel = self.in_channel + dense_channel
#self.in_channel = out_channel + (i+2)*dense_channel
return nn.Sequential(*layers)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
x = self.conv4(x)
x = self.conv5(x)
x = self.pool(x)
x = torch.flatten(x, start_dim=1)
x = self.fc(x)
return x
def DPN92(n_class=10):
cfg = {
'group': 32,
'in_channel': 64,
'mid_channels': (96, 192, 384, 768),
'out_channels': (256, 512, 1024, 2048),
'dense_channels': (16, 32, 24, 128),
'num': (3, 4, 20, 3),
'classes': (n_class)
}
return DPN(cfg)
def DPN98(n_class=10):
cfg = {
'group': 40,
'in_channel': 96,
'mid_channels': (160, 320, 640, 1280),
'out_channels': (256, 512, 1024, 2048),
'dense_channels': (16, 32, 32, 128),
'num': (3, 6, 20, 3),
'classes': (n_class)
}
return DPN(cfg)
打印模型
x = torch.randn(2, 3, 224, 224)
model = DPN98(4)
model.to(device)
import torchsummary as summary
summary.summary(model, (3, 224, 224))
代码和以前的差不多,不再细说
# 训练循环
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
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)
# 计算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
跑十轮并保存模型
import copy
optimizer = torch.optim.Adam(model.parameters(), lr=1e-4)
loss_fn = nn.CrossEntropyLoss() # 创建损失函数
epochs = 10
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')
可以打印训练记录图
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()
有个报错:RuntimeError: CUDA out of memory. Tried to allocate 54.00 MiB (GPU 0; 4.00 G。原因是我的显卡太lj了(3050ti),GPU算力不够,被迫把batchsize从32调低为4了
运行训练
把训练部分注释掉
from PIL import Image
classes = list(total_data.class_to_idx)
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}')
# 预测训练集中的某张照片
predict_one_image(image_path='./data/bird_photos/Cockatoo/011.jpg',
model=model,
transform=train_transforms,
classes=classes)