PyTorch实现ResNet50、ResNet101和ResNet152示例

作者:mingo_敏 时间:2023-10-16 05:44:39 

PyTorch: https://github.com/shanglianlm0525/PyTorch-Networks

PyTorch实现ResNet50、ResNet101和ResNet152示例


import torch
import torch.nn as nn
import torchvision
import numpy as np

print("PyTorch Version: ",torch.__version__)
print("Torchvision Version: ",torchvision.__version__)

__all__ = ['ResNet50', 'ResNet101','ResNet152']

def Conv1(in_planes, places, stride=2):
 return nn.Sequential(
   nn.Conv2d(in_channels=in_planes,out_channels=places,kernel_size=7,stride=stride,padding=3, bias=False),
   nn.BatchNorm2d(places),
   nn.ReLU(inplace=True),
   nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
 )

class Bottleneck(nn.Module):
 def __init__(self,in_places,places, stride=1,downsampling=False, expansion = 4):
   super(Bottleneck,self).__init__()
   self.expansion = expansion
   self.downsampling = downsampling

self.bottleneck = nn.Sequential(
     nn.Conv2d(in_channels=in_places,out_channels=places,kernel_size=1,stride=1, bias=False),
     nn.BatchNorm2d(places),
     nn.ReLU(inplace=True),
     nn.Conv2d(in_channels=places, out_channels=places, kernel_size=3, stride=stride, padding=1, bias=False),
     nn.BatchNorm2d(places),
     nn.ReLU(inplace=True),
     nn.Conv2d(in_channels=places, out_channels=places*self.expansion, kernel_size=1, stride=1, bias=False),
     nn.BatchNorm2d(places*self.expansion),
   )

if self.downsampling:
     self.downsample = nn.Sequential(
       nn.Conv2d(in_channels=in_places, out_channels=places*self.expansion, kernel_size=1, stride=stride, bias=False),
       nn.BatchNorm2d(places*self.expansion)
     )
   self.relu = nn.ReLU(inplace=True)
 def forward(self, x):
   residual = x
   out = self.bottleneck(x)

if self.downsampling:
     residual = self.downsample(x)

out += residual
   out = self.relu(out)
   return out

class ResNet(nn.Module):
 def __init__(self,blocks, num_classes=1000, expansion = 4):
   super(ResNet,self).__init__()
   self.expansion = expansion

self.conv1 = Conv1(in_planes = 3, places= 64)

self.layer1 = self.make_layer(in_places = 64, places= 64, block=blocks[0], stride=1)
   self.layer2 = self.make_layer(in_places = 256,places=128, block=blocks[1], stride=2)
   self.layer3 = self.make_layer(in_places=512,places=256, block=blocks[2], stride=2)
   self.layer4 = self.make_layer(in_places=1024,places=512, block=blocks[3], stride=2)

self.avgpool = nn.AvgPool2d(7, stride=1)
   self.fc = nn.Linear(2048,num_classes)

for m in self.modules():
     if isinstance(m, nn.Conv2d):
       nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
     elif isinstance(m, nn.BatchNorm2d):
       nn.init.constant_(m.weight, 1)
       nn.init.constant_(m.bias, 0)

def make_layer(self, in_places, places, block, stride):
   layers = []
   layers.append(Bottleneck(in_places, places,stride, downsampling =True))
   for i in range(1, block):
     layers.append(Bottleneck(places*self.expansion, places))

return nn.Sequential(*layers)

def forward(self, x):
   x = self.conv1(x)

x = self.layer1(x)
   x = self.layer2(x)
   x = self.layer3(x)
   x = self.layer4(x)

x = self.avgpool(x)
   x = x.view(x.size(0), -1)
   x = self.fc(x)
   return x

def ResNet50():
 return ResNet([3, 4, 6, 3])

def ResNet101():
 return ResNet([3, 4, 23, 3])

def ResNet152():
 return ResNet([3, 8, 36, 3])

if __name__=='__main__':
 #model = torchvision.models.resnet50()
 model = ResNet50()
 print(model)

input = torch.randn(1, 3, 224, 224)
 out = model(input)
 print(out.shape)

来源:https://blog.csdn.net/shanglianlm/article/details/86376627

标签:PyTorch,ResNet50,ResNet101,ResNet152
0
投稿

猜你喜欢

  • Bootstrap实现圆角、圆形头像和响应式图片

    2023-08-12 07:16:59
  • selenium3.0+python之环境搭建的方法步骤

    2023-03-20 06:00:22
  • 解析PyCharm集成GitLab代码仓的问题

    2022-06-08 07:36:15
  • vue前端开发keepAlive使用详解

    2024-05-02 16:33:52
  • 常用SQL功能语句

    2024-01-15 17:08:58
  • 如何在独立服务器上创建用户?

    2010-06-18 19:59:00
  • 使用批处理脚本自动生成并上传NuGet包(操作方法)

    2021-12-24 18:05:34
  • Python 实现数组相减示例

    2021-08-19 07:01:52
  • 解决PyCharm同目录下导入模块会报错的问题

    2023-06-12 22:39:55
  • 通过表单的做为二进制文件上传request.totalbytes提取出上传的二级制数据

    2011-03-16 10:39:00
  • Python操作SQLite数据库的方法详解【导入,创建,游标,增删改查等】

    2024-01-19 09:29:00
  • 有趣的python小程序分享

    2023-11-27 20:31:55
  • python生成遍历暴力破解密码的方法

    2021-07-02 21:28:54
  • NopCommerce架构分析之(八)多语言支持

    2024-05-13 09:15:53
  • 极力推荐10个短小实用的JavaScript代码段

    2024-06-05 09:12:40
  • python读取html中指定元素生成excle文件示例

    2021-04-08 19:51:11
  • Python图像读写方法对比

    2022-10-07 08:13:46
  • python3中确保枚举值代码分析

    2023-05-23 17:47:31
  • python sys.stdin和sys.stdout的用法说明

    2022-04-05 07:35:29
  • Python利用手势识别实现贪吃蛇游戏

    2022-05-24 07:25:55
  • asp之家 网络编程 m.aspxhome.com