resnet18和resnet34用的是basicblock,renset50、resnet101、resnet152用的是bottleneck

BasicBlock

Resnet - 图1

BottleNeck

Resnet - 图2

Resnet

本图为当输入为3x224x224时推算的结果,每一层都有padding,第一层输出为224 / stide = 112

Resnet - 图3

代码

  1. def resnet18():
  2. """ return a ResNet 18 object
  3. """
  4. return ResNet(BasicBlock, [2, 2, 2, 2])
  5. def resnet34():
  6. """ return a ResNet 34 object
  7. """
  8. return ResNet(BasicBlock, [3, 4, 6, 3])
  9. def resnet50():
  10. """ return a ResNet 50 object
  11. """
  12. return ResNet(BottleNeck, [3, 4, 6, 3])
  13. def resnet101():
  14. """ return a ResNet 101 object
  15. """
  16. return ResNet(BottleNeck, [3, 4, 23, 3])
  17. def resnet152():
  18. """ return a ResNet 152 object
  19. """
  20. return ResNet(BottleNeck, [3, 8, 36, 3])
  1. class BasicBlock(nn.Module):
  2. """Basic Block for resnet 18 and resnet 34
  3. """
  4. # BasicBlock and BottleNeck block
  5. # have different output size
  6. # we use class attribute expansion
  7. # to distinct
  8. expansion = 1
  9. def __init__(self, in_channels, out_channels, stride=1):
  10. super().__init__()
  11. # residual function
  12. self.residual_function = nn.Sequential(
  13. nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=False),
  14. nn.BatchNorm2d(out_channels),
  15. nn.ReLU(inplace=True),
  16. nn.Conv2d(out_channels, out_channels * BasicBlock.expansion, kernel_size=3, padding=1, bias=False),
  17. nn.BatchNorm2d(out_channels * BasicBlock.expansion)
  18. )
  19. # shortcut
  20. self.shortcut = nn.Sequential()
  21. # the shortcut output dimension is not the same with residual function
  22. # use 1*1 convolution to match the dimension
  23. if stride != 1 or in_channels != BasicBlock.expansion * out_channels:
  24. self.shortcut = nn.Sequential(
  25. nn.Conv2d(in_channels, out_channels * BasicBlock.expansion, kernel_size=1, stride=stride, bias=False),
  26. nn.BatchNorm2d(out_channels * BasicBlock.expansion)
  27. )
  28. def forward(self, x):
  29. return nn.ReLU(inplace=True)(self.residual_function(x) + self.shortcut(x))
  30. class BottleNeck(nn.Module):
  31. """Residual block for resnet over 50 layers
  32. """
  33. expansion = 4
  34. def __init__(self, in_channels, out_channels, stride=1):
  35. super().__init__()
  36. self.residual_function = nn.Sequential(
  37. nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False),
  38. nn.BatchNorm2d(out_channels),
  39. nn.ReLU(inplace=True),
  40. nn.Conv2d(out_channels, out_channels, stride=stride, kernel_size=3, padding=1, bias=False),
  41. nn.BatchNorm2d(out_channels),
  42. nn.ReLU(inplace=True),
  43. nn.Conv2d(out_channels, out_channels * BottleNeck.expansion, kernel_size=1, bias=False),
  44. nn.BatchNorm2d(out_channels * BottleNeck.expansion),
  45. )
  46. self.shortcut = nn.Sequential()
  47. if stride != 1 or in_channels != out_channels * BottleNeck.expansion:
  48. self.shortcut = nn.Sequential(
  49. nn.Conv2d(in_channels, out_channels * BottleNeck.expansion, stride=stride, kernel_size=1, bias=False),
  50. nn.BatchNorm2d(out_channels * BottleNeck.expansion)
  51. )
  52. def forward(self, x):
  53. return nn.ReLU(inplace=True)(self.residual_function(x) + self.shortcut(x))
  54. class ResNet(nn.Module):
  55. def __init__(self, block, num_block, num_classes=100):
  56. super().__init__()
  57. self.in_channels = 64
  58. self.conv1 = nn.Sequential(
  59. nn.Conv2d(3, 64, kernel_size=3, padding=1, bias=False),
  60. nn.BatchNorm2d(64),
  61. nn.ReLU(inplace=True))
  62. # we use a different inputsize than the original paper
  63. # so conv2_x's stride is 1
  64. self.conv2_x = self._make_layer(block, 64, num_block[0], 1)
  65. self.conv3_x = self._make_layer(block, 128, num_block[1], 2)
  66. self.conv4_x = self._make_layer(block, 256, num_block[2], 2)
  67. self.conv5_x = self._make_layer(block, 512, num_block[3], 2)
  68. self.avg_pool = nn.AdaptiveAvgPool2d((1, 1))
  69. self.fc = nn.Linear(512 * block.expansion, num_classes)
  70. def _make_layer(self, block, out_channels, num_blocks, stride):
  71. """make resnet layers(by layer i didnt mean this 'layer' was the
  72. same as a neuron netowork layer, ex. conv layer), one layer may
  73. contain more than one residual block
  74. Args:
  75. block: block type, basic block or bottle neck block
  76. out_channels: output depth channel number of this layer
  77. num_blocks: how many blocks per layer
  78. stride: the stride of the first block of this layer
  79. Return:
  80. return a resnet layer
  81. """
  82. # we have num_block blocks per layer, the first block
  83. # could be 1 or 2, other blocks would always be 1
  84. strides = [stride] + [1] * (num_blocks - 1)
  85. layers = []
  86. for stride in strides:
  87. layers.append(block(self.in_channels, out_channels, stride))
  88. self.in_channels = out_channels * block.expansion
  89. return nn.Sequential(*layers)
  90. def forward(self, x):
  91. output = self.conv1(x)
  92. output = self.conv2_x(output)
  93. output = self.conv3_x(output)
  94. output = self.conv4_x(output)
  95. output = self.conv5_x(output)
  96. output = self.avg_pool(output)
  97. output = output.view(output.size(0), -1)
  98. output = self.fc(output)
  99. return output