当前位置:   article > 正文

pytorch从零实现resnet50_人群计数resnet50代码

人群计数resnet50代码

pytorch从零实现resnet_pytorch实现resnet_两只蜡笔的小新的博客-CSDN博客

前言:

之前博主写过一个ResNet34, ResNet18的实现方法,对于ResNet50的实现方法有点不太一样,之前的实现方法参考上面的链接。下面介绍ResNet50的实现方法。

基本结构示意图

 发现ResNet50,其基本模块是三个,1*1 3*3 1*1 的卷积层,在向前推进的时候,需要特征图的通道数降维,所以与ResNet34不同的地方是BasicBlock,和make_layer

二、构建BasicBlock

  1. class Bottleneck(nn.Module):
  2. expansion: int = 4
  3. def __init__(
  4. self,
  5. inplanes: int,
  6. planes: int,
  7. stride: int = 1,
  8. downsample = None,
  9. base_width: int = 64,
  10. dilation: int = 1,
  11. norm_layer = None
  12. ) -> None:
  13. super(Bottleneck, self).__init__()
  14. if norm_layer is None:
  15. norm_layer = nn.BatchNorm2d
  16. width = int(planes * (base_width / 64.))
  17. # Both self.conv2 and self.downsample layers downsample the input when stride != 1
  18. self.conv1 = nn.Conv2d(inplanes, width, kernel_size=1, stride=1, bias=False)
  19. self.bn1 = norm_layer(width)
  20. self.conv2 = nn.Conv2d(width, width, kernel_size=3, stride=stride,
  21. padding=dilation, bias=False, dilation=dilation)
  22. self.bn2 = norm_layer(width)
  23. self.conv3 = nn.Conv2d(width, planes * self.expansion, kernel_size=1, stride=1, bias=False)
  24. self.bn3 = norm_layer(planes * self.expansion)
  25. self.relu = nn.ReLU(inplace=True)
  26. self.downsample = downsample
  27. self.stride = stride
  28. def forward(self, x):
  29. identity = x
  30. out = self.conv1(x)
  31. out = self.bn1(out)
  32. out = self.relu(out)
  33. out = self.conv2(out)
  34. out = self.bn2(out)
  35. out = self.relu(out)
  36. out = self.conv3(out)
  37. out = self.bn3(out)
  38. if self.downsample is not None:
  39. identity = self.downsample(x)
  40. out += identity
  41. out = self.relu(out)
  42. return out

三、残差块的实现,

由于renset残差单元可能连接两个不同维度的特征图,所以要接一个降采样操作self.downsample = shortcut,有没有取决于输入维度与输出维度是否相同,还取决于特征图的尺寸是否发生变化。

  1. def _make_layer(self, block, planes: int, blocks: int,
  2. stride: int = 1):
  3. norm_layer = self._norm_layer
  4. downsample = None
  5. previous_dilation = self.dilation
  6. if stride != 1 or self.inplanes != planes * block.expansion:
  7. downsample = nn.Sequential(
  8. nn.Conv2d(self.inplanes, planes * block.expansion, kernel_size=1, stride=stride, bias=False),
  9. norm_layer(planes * block.expansion),)
  10. layers = []
  11. layers.append(block(self.inplanes, planes, stride, downsample,
  12. self.base_width, previous_dilation, norm_layer))
  13. self.inplanes = planes * block.expansion
  14. for _ in range(1, blocks):
  15. layers.append(block(self.inplanes, planes,
  16. base_width=self.base_width, dilation=self.dilation,
  17. norm_layer=norm_layer))
  18. return nn.Sequential(*layers)

四、下面构造类class ResNet50(nn.Module)

1.构造类方法1

  1. class ResNet50_src(nn.Module):
  2. def __init__(self,block = Bottleneck,
  3. layers = [3, 4, 6, 3],
  4. num_classes: int = 1000,
  5. width_per_group: int = 64,
  6. norm_layer = None
  7. ):
  8. super(ResNet50_src, self).__init__()
  9. if norm_layer is None:
  10. norm_layer = nn.BatchNorm2d
  11. self._norm_layer = norm_layer
  12. self.inplanes = 64
  13. self.dilation = 1
  14. self.base_width = width_per_group
  15. self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3,
  16. bias=False)
  17. self.bn1 = norm_layer(self.inplanes)
  18. self.relu = nn.ReLU(inplace=True)
  19. self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
  20. self.layer1 = self._make_layer(block, 64, layers[0])
  21. self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
  22. self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
  23. self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
  24. self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
  25. self.fc = nn.Linear(512 * block.expansion, num_classes)
  26. for m in self.modules():
  27. if isinstance(m, nn.Conv2d):
  28. nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
  29. elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
  30. nn.init.constant_(m.weight, 1)
  31. nn.init.constant_(m.bias, 0)
  32. def _make_layer(self, block, planes: int, blocks: int,
  33. stride: int = 1):
  34. norm_layer = self._norm_layer
  35. downsample = None
  36. previous_dilation = self.dilation
  37. if stride != 1 or self.inplanes != planes * block.expansion:
  38. downsample = nn.Sequential(
  39. nn.Conv2d(self.inplanes, planes * block.expansion, kernel_size=1, stride=stride, bias=False),
  40. norm_layer(planes * block.expansion),)
  41. layers = []
  42. layers.append(block(self.inplanes, planes, stride, downsample,
  43. self.base_width, previous_dilation, norm_layer))
  44. self.inplanes = planes * block.expansion
  45. for _ in range(1, blocks):
  46. layers.append(block(self.inplanes, planes,
  47. base_width=self.base_width, dilation=self.dilation,
  48. norm_layer=norm_layer))
  49. return nn.Sequential(*layers)
  50. def forward(self, x):
  51. x = self.conv1(x)
  52. x = self.bn1(x)
  53. x = self.relu(x)
  54. x = self.maxpool(x)
  55. x = self.layer1(x)
  56. x = self.layer2(x)
  57. x = self.layer3(x)
  58. x = self.layer4(x)
  59. x = self.avgpool(x)
  60. x = torch.flatten(x, 1)
  61. x = self.fc(x)
  62. return x

运行对比测试

  1. if __name__ == '__main__':
  2. from torchsummary import summary
  3. from torchvision import models
  4. resnet = models.resnet50(pretrained=False)
  5. summary(ResNet50_src().cuda(),(3,512,512))
  6. # summary(resnet.cuda(),(3,512,512))

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/73108
推荐阅读
相关标签
  

闽ICP备14008679号