当前位置:   article > 正文

pytorch(3)--VGG block和 Resnet block

resnet block

一、前言

    本篇记录 VGG Block和Resnet Block 经典结构

二、VGGblock

    VGG Block 可由两层conv3或三层conv3组成,两层的感受野和一层conv5一样,三层conv3的感受野和一层conv7是一样的,但是能够减少计算量,以下为不同的VGGblock搭配的VGG网络

包含两层conv3的VGG block 代码如下,CBR-CBR,无池化层

  1. class VGGBlock(nn.Module):
  2. def __init__(self, in_channels, middle_channels, out_channels, act_func=nn.ReLU(inplace=True)):
  3. super(VGGBlock, self).__init__()
  4. self.act_func = act_func
  5. self.conv1 = nn.Conv2d(in_channels, middle_channels, 3, padding=1)
  6. self.bn1 = nn.BatchNorm2d(middle_channels)
  7. self.conv2 = nn.Conv2d(middle_channels, out_channels, 3, padding=1)
  8. self.bn2 = nn.BatchNorm2d(out_channels)
  9. def forward(self, x):
  10. out = self.conv1(x)
  11. out = self.bn1(out)
  12. out = self.act_func(out)
  13. out = self.conv2(out)
  14. out = self.bn2(out)
  15. out = self.act_func(out)
  16. return out

三、Resnet block

  resnet 有2种网络结构

BasicBlock结构 和 BottleNeck 结构

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-K7OrudiF-1595851424230)(C:\Users\Administrator\Desktop\Resnet\7.png)]  [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-JbMevQsR-1595851424232)(C:\Users\Administrator\Desktop\Resnet\8.png)]

5种不同层数的ResNet结构图,如下所示:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-yDZdjc2t-1595851424234)(C:\Users\Administrator\Desktop\Resnet\1.png)]

  1. #代码参考自pytorch 官方 https://pytorch.org/docs/0.4.0/_modules/torchvision/models/resnet.html
  2. import torch.nn as nn
  3. import math
  4. import torch
  5. def conv3x3(in_planes, out_planes, stride=1):
  6. """3x3 convolution with padding"""
  7. return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
  8. padding=1, bias=False)
  9. class BasicBlock(nn.Module):
  10. expansion = 1
  11. def __init__(self, inplanes, planes, stride=1, downsample=None):
  12. super(BasicBlock, self).__init__()
  13. self.conv1 = conv3x3(inplanes, planes, stride)
  14. self.bn1 = nn.BatchNorm2d(planes)
  15. self.relu = nn.ReLU(inplace=True)
  16. self.conv2 = conv3x3(planes, planes)
  17. self.bn2 = nn.BatchNorm2d(planes)
  18. self.downsample = downsample
  19. self.stride = stride
  20. def forward(self, x):
  21. residual = x
  22. out = self.conv1(x)
  23. out = self.bn1(out)
  24. out = self.relu(out)
  25. out = self.conv2(out)
  26. out = self.bn2(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 Bottleneck(nn.Module):
  33. expansion = 4
  34. def __init__(self, inplanes, planes, stride=1, downsample=None):
  35. super(Bottleneck, self).__init__()
  36. self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
  37. self.bn1 = nn.BatchNorm2d(planes)
  38. self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,
  39. padding=1, bias=False)
  40. self.bn2 = nn.BatchNorm2d(planes)
  41. self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)
  42. self.bn3 = nn.BatchNorm2d(planes * 4)
  43. self.relu = nn.ReLU(inplace=True)
  44. self.downsample = downsample
  45. self.stride = stride
  46. def forward(self, x):
  47. residual = x
  48. out = self.conv1(x)
  49. out = self.bn1(out)
  50. out = self.relu(out)
  51. out = self.conv2(out)
  52. out = self.bn2(out)
  53. out = self.relu(out)
  54. out = self.conv3(out)
  55. out = self.bn3(out)
  56. if self.downsample is not None:
  57. residual = self.downsample(x)
  58. out += residual
  59. out = self.relu(out)
  60. return out
  61. class ResNet(nn.Module):
  62. def __init__(self, block, layers, num_classes=1000):
  63. self.inplanes = 64
  64. super(ResNet, self).__init__()
  65. self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
  66. bias=False)
  67. self.bn1 = nn.BatchNorm2d(64)
  68. self.relu = nn.ReLU(inplace=True)
  69. self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
  70. self.layer1 = self._make_layer(block, 64, layers[0])
  71. self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
  72. self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
  73. self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
  74. #self.avgpool = nn.AvgPool2d(7, stride=1)
  75. self.avgpool = nn.AdaptiveAvgPool2d(1)
  76. self.fc = nn.Linear(512 * block.expansion, num_classes)
  77. for m in self.modules():
  78. if isinstance(m, nn.Conv2d):
  79. n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
  80. m.weight.data.normal_(0, math.sqrt(2. / n))
  81. elif isinstance(m, nn.BatchNorm2d):
  82. m.weight.data.fill_(1)
  83. m.bias.data.zero_()
  84. def _make_layer(self, block, planes, blocks, stride=1):
  85. downsample = None
  86. if stride != 1 or self.inplanes != planes * block.expansion:
  87. downsample = nn.Sequential(
  88. nn.Conv2d(self.inplanes, planes * block.expansion,
  89. kernel_size=1, stride=stride, bias=False),
  90. nn.BatchNorm2d(planes * block.expansion),
  91. )
  92. layers = []
  93. layers.append(block(self.inplanes, planes, stride, downsample))
  94. self.inplanes = planes * block.expansion
  95. for i in range(1, blocks):
  96. layers.append(block(self.inplanes, planes))
  97. return nn.Sequential(*layers)
  98. def forward(self, x):
  99. x = self.conv1(x)
  100. x = self.bn1(x)
  101. x = self.relu(x)
  102. x = self.maxpool(x)
  103. x = self.layer1(x)
  104. x = self.layer2(x)
  105. x = self.layer3(x)
  106. x = self.layer4(x)
  107. x = self.avgpool(x)
  108. x = x.view(x.size(0), -1)
  109. x = self.fc(x)
  110. return x
  111. def resnet18(pretrained=False, num_classes = 1000 ):
  112. """Constructs a ResNet-18 model.
  113. Args:
  114. pretrained (bool): If True, returns a model pre-trained on ImageNet
  115. """
  116. model = ResNet(BasicBlock, [2, 2, 2, 2] )
  117. if pretrained:
  118. model.load_state_dict( torch.load("resnet18-5c106cde.pth") )
  119. num_features=model.fc.in_features
  120. model.fc=nn.Linear(num_features,num_classes)
  121. return model
  122. def resnet50(pretrained=False, **kwargs):
  123. """Constructs a ResNet-50 model.
  124. Args:
  125. pretrained (bool): If True, returns a model pre-trained on ImageNet
  126. """
  127. model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs)
  128. if pretrained:
  129. model.load_state_dict(model_zoo.load_url(model_urls['resnet50']))
  130. return model
  131. def resnet101(pretrained=False, **kwargs):
  132. """Constructs a ResNet-101 model.
  133. Args:
  134. pretrained (bool): If True, returns a model pre-trained on ImageNet
  135. """
  136. model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs)
  137. if pretrained:
  138. model.load_state_dict(model_zoo.load_url(model_urls['resnet101']))
  139. return model
  140. def resnet152(pretrained=False, **kwargs):
  141. """Constructs a ResNet-152 model.
  142. Args:
  143. pretrained (bool): If True, returns a model pre-trained on ImageNet
  144. """
  145. model = ResNet(Bottleneck, [3, 8, 36, 3], **kwargs)
  146. if pretrained:
  147. model.load_state_dict(model_zoo.load_url(model_urls['resnet152']))
  148. return model
  149. model = resnet18( pretrained = True, num_classes = 7 )

 

 

 

 

 

 

 

 

 

 

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

闽ICP备14008679号