共计 6211 个字符,预计需要花费 16 分钟才能阅读完成。
文章起源 | 恒源云社区
原文地址 | 数据集实战
原文作者 | Mathor
实不相瞒,小编我对平台社区内的大佬 Mathor 很崇拜!这不,明天又来给大家分享大佬论文笔记了,连忙看看接下来的内容是否有你们须要的知识点吧!
注释开始:
如果不理解 ResNet 的同学能够先看我的这篇博客 ResNet 论文浏览
首先实现一个 Residual Block
import torch
from torch import nn
from torch.nn import functional as F
class ResBlk(nn.Module):
def __init__(self, ch_in, ch_out, stride=1):
super(ResBlk, self).__init__()
self.conv1 = nn.Conv2d(ch_in, ch_out, kernel_size=3, stride=stride, padding=1)
self.bn1 = nn.BatchNorm2d(ch_out)
self.conv2 = nn.Conv2d(ch_out, ch_out, kernel_size=3, stride=1, padding=1)
self.bn2 = nn.BatchNorm2d(ch_out)
if ch_out == ch_in:
self.extra = nn.Sequential()
else:
self.extra = nn.Sequential(
# 1×1 的卷积作用是批改输出 x 的 channel
# [b, ch_in, h, w] => [b, ch_out, h, w]
nn.Conv2d(ch_in, ch_out, kernel_size=1, stride=stride),
nn.BatchNorm2d(ch_out),
)
def forward(self, x):
out = F.relu(self.bn1(self.conv1(x)))
out = self.bn2(self.conv2(out))
# short cut
out = self.extra(x) + out
out = F.relu(out)
return out
Block 中进行了正则化解决,以使 train 过程更快更稳固。同时要思考,如果两元素的 ch_in 和 ch_out 不匹配,进行加法时会报错,因而须要判断一下,如果不想等,就用 1×1 的卷积调整一下
测试一下
blk = ResBlk(64, 128, stride=2)
tmp = torch.randn(2, 64, 32, 32)
out = blk(tmp)
print(out.shape)
输入的 shape 大小是torch.Size([2, 128, 16, 16])
这里解释一下,为什么有的层要专门设置 stride。先不思考别的层,对于一个 Residual block,channel 从 64 增大到 128,如果所有的 stride 都是 1,padding 也是 1,那么图片的 w 和 h 也不会变,然而 channel 增大了,此时就会导致整个网络的参数增多。而这才仅仅一个 Block,更不用说前面的 FC 以及更多 Block 了,所以 stride 不能全副设置为 1,不要让网络的参数始终增大
而后咱们搭建残缺的 ResNet-18
class ResNet18(nn.Module):
def __init__(self):
super(ResNet18, self).__init__()
self.conv1 = nn.Sequential(nn.Conv2d(3, 64, kernel_size=3, stride=3, padding=0),
nn.BatchNorm2d(64),
)
# followed 4 blocks
# [b, 64, h, w] => [b, 128, h, w]
self.blk1 = ResBlk(64, 128, stride=2)
# [b, 128, h, w] => [b, 256, h, w]
self.blk2 = ResBlk(128, 256, stride=2)
# [b, 256, h, w] => [b, 512, h, w]
self.blk3 = ResBlk(256, 512, stride=2)
# [b, 512, h, w] => [b, 512, h, w]
self.blk4 = ResBlk(512, 512, stride=2)
self.outlayer = nn.Linear(512*1*1, 10)
def forward(self, x):
x = F.relu(self.conv1(x))
# 通过四个 blk 当前 [b, 64, h, w] => [b, 512, h, w]
x = self.blk1(x)
x = self.blk2(x)
x = self.blk3(x)
x = self.blk4(x)
x = self.outlayer(x)
return x
测试一下
x = torch.randn(2, 3, 32, 32)
model = ResNet18()
out = model(x)
print("ResNet:", out.shape)
后果报错了,错误信息如下
size mismatch, m1: [2048 x 2], m2: [512 x 10] at /pytorch/aten/src/TH/generic/THTensorMath.cpp:961
问题在于咱们最初定义线性层的输出维度,和上一层 Block 的输入维度不匹配,在 ResNet18 的最初一个 Block 运行完结后打印一下以后 x 的 shape,后果是torch.Size([2, 512, 2, 2])
解决办法有很多,能够批改线性层的输出进行匹配,也能够在最初一层 Block 前面再进行一些操作,使其与 512 匹配
先给出批改后的代码,在做解释
class ResNet18(nn.Module):
def __init__(self):
super(ResNet18, self).__init__()
self.conv1 = nn.Sequential(nn.Conv2d(3, 64, kernel_size=3, stride=3, padding=0),
nn.BatchNorm2d(64),
)
# followed 4 blocks
# [b, 64, h, w] => [b, 128, h, w]
self.blk1 = ResBlk(64, 128, stride=2)
# [b, 128, h, w] => [b, 256, h, w]
self.blk2 = ResBlk(128, 256, stride=2)
# [b, 256, h, w] => [b, 512, h, w]
self.blk3 = ResBlk(256, 512, stride=2)
# [b, 512, h, w] => [b, 512, h, w]
self.blk4 = ResBlk(512, 512, stride=2)
self.outlayer = nn.Linear(512*1*1, 10)
def forward(self, x):
x = F.relu(self.conv1(x))
# 通过四个 blk 当前 [b, 64, h, w] => [b, 512, h, w]
x = self.blk1(x)
x = self.blk2(x)
x = self.blk3(x)
x = self.blk4(x)
# print("after conv:", x.shape) # [b, 512, 2, 2]
# [b, 512, h, w] => [b, 512, 1, 1]
x = F.adaptive_avg_pool2d(x, [1, 1])
x = x.view(x.size(0), -1) # [b, 512, 1, 1] => [b, 512*1*1]
x = self.outlayer(x)
return x
这里我采纳的是第二种办法,在最初一个 Block 完结当前,接了一个自适应的 pooling 层,这个 pooling 的作用是将不管输出的宽高是多少,全副输入称宽高都是 1 的 tensor,其余维度放弃不变。而后再做一个 reshape 操作,将 [batchsize, 512, 1, 1]reshape
成[batchsize, 512*1*1]
大小的 tensor,这样就和接下来的线性层对上了,线性层的输出大小是 512,输入是 10。因而整个网络最终输入的 shape 就是[batchsize, 10]
最初咱们把之前训练 LeNet5 的代码拷贝过去,将外面的 model=LeNet5()
改为 model=ResNet18()
就行了。残缺代码如下
import torch
from torch import nn, optim
import torch.nn.functional as F
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
batch_size=32
cifar_train = datasets.CIFAR10(root='cifar', train=True, transform=transforms.Compose([transforms.Resize([32, 32]),
transforms.ToTensor(),]), download=True)
cifar_train = DataLoader(cifar_train, batch_size=batch_size, shuffle=True)
cifar_test = datasets.CIFAR10(root='cifar', train=False, transform=transforms.Compose([transforms.Resize([32, 32]),
transforms.ToTensor(),]), download=True)
cifar_test = DataLoader(cifar_test, batch_size=batch_size, shuffle=True)
class ResBlk(nn.Module):
def __init__(self, ch_in, ch_out, stride=1):
super(ResBlk, self).__init__()
self.conv1 = nn.Conv2d(ch_in, ch_out, kernel_size=3, stride=stride, padding=1)
self.bn1 = nn.BatchNorm2d(ch_out)
self.conv2 = nn.Conv2d(ch_out, ch_out, kernel_size=3, stride=1, padding=1)
self.bn2 = nn.BatchNorm2d(ch_out)
if ch_out == ch_in:
self.extra = nn.Sequential()
else:
self.extra = nn.Sequential(
# 1×1 的卷积作用是批改输出 x 的 channel
# [b, ch_in, h, w] => [b, ch_out, h, w]
nn.Conv2d(ch_in, ch_out, kernel_size=1, stride=stride),
nn.BatchNorm2d(ch_out),
)
def forward(self, x):
out = F.relu(self.bn1(self.conv1(x)))
out = self.bn2(self.conv2(out))
# short cut
out = self.extra(x) + out
out = F.relu(out)
return out
class ResNet18(nn.Module):
def __init__(self):
super(ResNet18, self).__init__()
self.conv1 = nn.Sequential(nn.Conv2d(3, 64, kernel_size=3, stride=3, padding=0),
nn.BatchNorm2d(64),
)
# followed 4 blocks
# [b, 64, h, w] => [b, 128, h, w]
self.blk1 = ResBlk(64, 128, stride=2)
# [b, 128, h, w] => [b, 256, h, w]
self.blk2 = ResBlk(128, 256, stride=2)
# [b, 256, h, w] => [b, 512, h, w]
self.blk3 = ResBlk(256, 512, stride=2)
# [b, 512, h, w] => [b, 512, h, w]
self.blk4 = ResBlk(512, 512, stride=2)
self.outlayer = nn.Linear(512*1*1, 10)
def forward(self, x):
x = F.relu(self.conv1(x))
# 通过四个 blk 当前 [b, 64, h, w] => [b, 512, h, w]
x = self.blk1(x)
x = self.blk2(x)
x = self.blk3(x)
x = self.blk4(x)
# print("after conv:", x.shape) # [b, 512, 2, 2]
# [b, 512, h, w] => [b, 512, 1, 1]
x = F.adaptive_avg_pool2d(x, [1, 1])
x = x.view(x.size(0), -1) # [b, 512, 1, 1] => [b, 512*1*1]
x = self.outlayer(x)
return x
def main():
########## train ##########
#device = torch.device('cuda')
#model = ResNet18().to(device)
criteon = nn.CrossEntropyLoss()
model = ResNet18()
optimizer = optim.Adam(model.parameters(), 1e-3)
for epoch in range(1000):
model.train()
for batchidx, (x, label) in enumerate(cifar_train):
#x, label = x.to(device), label.to(device)
logits = model(x)
# logits: [b, 10]
# label: [b]
loss = criteon(logits, label)
# backward
optimizer.zero_grad()
loss.backward()
optimizer.step()
print('train:', epoch, loss.item())
########## test ##########
model.eval()
with torch.no_grad():
total_correct = 0
total_num = 0
for x, label in cifar_test:
# x, label = x.to(device), label.to(device)
# [b]
logits = model(x)
# [b]
pred = logits.argmax(dim=1)
# [b] vs [b]
total_correct += torch.eq(pred, label).float().sum().item()
total_num += x.size(0)
acc = total_correct / total_num
print('test:', epoch, acc)
if __name__ == '__main__':
main()
ResNet 和 LeNet 相比,准确率晋升的很快,然而因为层数减少,不可避免的会导致运行工夫减少,如果没有 GPU,运行一个 epoch 大略要 15 分钟。读者同样能够在此基础上批改网络结构,使用一些 tricks,比方说一开始就对图片做一个 Normalize 等