# CIFAR-10 数据集实战——构建ResNet18神经网络

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)

class ResNet18(nn.Module):
def __init__(self):
super(ResNet18, self).__init__()

self.conv1 = nn.Sequential(
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] => [h, 512, h, w]
self.blk3 = ResBlk(256, 512, stride=2)
# [b, 512, h, w] => [h, 1024, 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, 1024, 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

class ResNet18(nn.Module):
def __init__(self):
super(ResNet18, self).__init__()

self.conv1 = nn.Sequential(
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] => [h, 512, h, w]
self.blk3 = ResBlk(256, 512, stride=2)
# [b, 512, h, w] => [h, 1024, 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, 1024, 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 = x.view(x.size(0), -1) # [b, 512, 1, 1] => [b, 512*1*1]
x = self.outlayer(x)

return x

import torch
from torch import nn, optim
import torch.nn.functional as F
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(),

cifar_test = datasets.CIFAR10(root='cifar', train=False, transform=transforms.Compose([
transforms.Resize([32, 32]),
transforms.ToTensor(),

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.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] => [h, 512, h, w]
self.blk3 = ResBlk(256, 512, stride=2)
# [b, 512, h, w] => [h, 1024, 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, 1024, 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 = 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()
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
loss.backward()
optimizer.step()

print('train:', epoch, loss.item())

########## test  ##########
model.eval()
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等