resnet50.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. import math
  2. import torch.nn as nn
  3. from torch.hub import load_state_dict_from_url
  4. class Bottleneck(nn.Module):
  5. expansion = 4
  6. def __init__(self, inplanes, planes, stride=1, downsample=None):
  7. super(Bottleneck, self).__init__()
  8. self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, stride=stride, bias=False)
  9. self.bn1 = nn.BatchNorm2d(planes)
  10. self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=1, padding=1, bias=False)
  11. self.bn2 = nn.BatchNorm2d(planes)
  12. self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)
  13. self.bn3 = nn.BatchNorm2d(planes * 4)
  14. self.relu = nn.ReLU(inplace=True)
  15. self.downsample = downsample
  16. self.stride = stride
  17. def forward(self, x):
  18. residual = x
  19. out = self.conv1(x)
  20. out = self.bn1(out)
  21. out = self.relu(out)
  22. out = self.conv2(out)
  23. out = self.bn2(out)
  24. out = self.relu(out)
  25. out = self.conv3(out)
  26. out = self.bn3(out)
  27. if self.downsample is not None:
  28. residual = self.downsample(x)
  29. out += residual
  30. out = self.relu(out)
  31. return out
  32. class ResNet(nn.Module):
  33. def __init__(self, block, layers, num_classes=1000):
  34. #-----------------------------------#
  35. # 假设输入进来的图片是600,600,3
  36. #-----------------------------------#
  37. self.inplanes = 64
  38. super(ResNet, self).__init__()
  39. # 600,600,3 -> 300,300,64
  40. self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False)
  41. self.bn1 = nn.BatchNorm2d(64)
  42. self.relu = nn.ReLU(inplace=True)
  43. # 300,300,64 -> 150,150,64
  44. self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=0, ceil_mode=True)
  45. # 150,150,64 -> 150,150,256
  46. self.layer1 = self._make_layer(block, 64, layers[0])
  47. # 150,150,256 -> 75,75,512
  48. self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
  49. # 75,75,512 -> 38,38,1024 到这里可以获得一个38,38,1024的共享特征层
  50. self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
  51. # self.layer4被用在classifier模型中
  52. self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
  53. self.avgpool = nn.AvgPool2d(7)
  54. self.fc = nn.Linear(512 * block.expansion, num_classes)
  55. for m in self.modules():
  56. if isinstance(m, nn.Conv2d):
  57. n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
  58. m.weight.data.normal_(0, math.sqrt(2. / n))
  59. elif isinstance(m, nn.BatchNorm2d):
  60. m.weight.data.fill_(1)
  61. m.bias.data.zero_()
  62. def _make_layer(self, block, planes, blocks, stride=1):
  63. downsample = None
  64. #-------------------------------------------------------------------#
  65. # 当模型需要进行高和宽的压缩的时候,就需要用到残差边的downsample
  66. #-------------------------------------------------------------------#
  67. if stride != 1 or self.inplanes != planes * block.expansion:
  68. downsample = nn.Sequential(
  69. nn.Conv2d(self.inplanes, planes * block.expansion,kernel_size=1, stride=stride, bias=False),
  70. nn.BatchNorm2d(planes * block.expansion),
  71. )
  72. layers = []
  73. layers.append(block(self.inplanes, planes, stride, downsample))
  74. self.inplanes = planes * block.expansion
  75. for i in range(1, blocks):
  76. layers.append(block(self.inplanes, planes))
  77. return nn.Sequential(*layers)
  78. def forward(self, x):
  79. x = self.conv1(x)
  80. x = self.bn1(x)
  81. x = self.relu(x)
  82. x = self.maxpool(x)
  83. x = self.layer1(x)
  84. x = self.layer2(x)
  85. x = self.layer3(x)
  86. x = self.layer4(x)
  87. x = self.avgpool(x)
  88. x = x.view(x.size(0), -1)
  89. x = self.fc(x)
  90. return x
  91. def resnet50(pretrained = False):
  92. model = ResNet(Bottleneck, [3, 4, 6, 3])
  93. if pretrained:
  94. state_dict = load_state_dict_from_url("https://download.pytorch.org/models/resnet50-19c8e357.pth", model_dir="./model_data")
  95. model.load_state_dict(state_dict)
  96. #----------------------------------------------------------------------------#
  97. # 获取特征提取部分,从conv1到model.layer3,最终获得一个38,38,1024的特征层
  98. #----------------------------------------------------------------------------#
  99. features = list([model.conv1, model.bn1, model.relu, model.maxpool, model.layer1, model.layer2, model.layer3])
  100. #----------------------------------------------------------------------------#
  101. # 获取分类部分,从model.layer4到model.avgpool
  102. #----------------------------------------------------------------------------#
  103. classifier = list([model.layer4, model.avgpool])
  104. features = nn.Sequential(*features)
  105. classifier = nn.Sequential(*classifier)
  106. return features, classifier