import torch
from torch import nn
from torch.nn import functional as F
class ResBlk(nn.Module):
"""
resnet block
"""
def __init__(self, ch_in, ch_out,stride=1):
"""
:param ch:
:param ch_out:
"""
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)
self.extra = nn.Sequential()
# x : [b, ch_in, h, w] => [b, ch_out, h, w]
if ch_out != ch_in:
self.extra = nn.Sequential(
nn.Conv2d(ch_in, ch_out, kernel_size=1, stride=stride),# 因为是作用于x,也就是说要和out相加,而out是[b, 128, 16, 16]
nn.BatchNorm2d(ch_out)# 所以x本来是[b, 64, 32, 32] => [b, 128, 16, 16]
)
def forward(self, x):
"""
:param x: [b, ch, h, w]
:return:
"""
out = F.relu(self.bn1(self.conv1(x)))
out = F.relu(self.bn2(self.conv2(out)))
#short cut
#element-wise add
# x : [b, ch_in, h, w] with [b, ch_out, h, w]
# 因为x的通道数和g(x)的不一样,所以要用一个1x1的卷积,在不改变h和w的前提下改变通道数
out = self.extra(x) + out
return out
class Resnet18(nn.Module):
def __init__(self):
super(Resnet18, self).__init__()
#预处理层,把3 => 64
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)
self.blk2 = ResBlk(128, 256, stride=2)
self.blk3 = ResBlk(256, 512, stride=2)
self.blk4 = ResBlk(512, 512, stride=2)
self.outlayer = nn.Linear(512, 10) #输入可以一开始瞎几把输, 输出为10类
#self.outlayer = nn.Linear(102, 10) #输入可以一开始瞎几把输, 输出为10类
#网络目前的趋势:通道数越来越多, 而图片越变越小(提取特征)
def forward(self, x):
"""
:param x:
:return:
"""
#[b, 64, h, w] => [b, 64, h, w]
x = F.relu(self.conv1(x))
x = self.blk1(x)
x = self.blk2(x)
x = self.blk3(x)
x = self.blk4(x)
print("after blk x.shape", x.shape)
#[b, 512, 2, 2]
x = F.adaptive_max_pool2d(x, [1, 1])
# [b, 512, h, w] => [b, 512, 1, 1]
#不管你的输入是多少,最终都会变成hw的均值
print("after pool x.shape:", x.shape)
x = x.view(x.size(0), -1)
print("after view x.shape:", x.shape)
x = self.outlayer(x)
return x
def main():
blk = ResBlk(64, 128)
tmp = torch.randn(2, 64, 32, 32)
out = blk(tmp)
print("block:", out.shape) #[2, 128, 32, 32] 这表明resblk会把长宽保持不变,但是通道数变大,这会使得数据变臃肿
#----------------接下来实现长宽减半的操作-----------------
#----------------主要通过stride的操作,2就是1/2,3就是1/3, 4就是1/4---------
blk2 = ResBlk(64, 128, stride = 2)
tmp2 = torch.randn(2, 64, 32, 32)
out2 = blk2(tmp2)
print("block2:", out2.shape)
# [2, 128, 16, 16]
#-----------------测试resnet---------------
x = torch.randn(2, 3, 32, 32)#网络的输入若是改变了,也就是32*32,那网络内部的这些参数都需要改变哦
model = Resnet18()
out = model(x)
print("resnet:", out.shape)
if __name__ == '__main__':
main()
|