PyTorch实现ResNet50、ResNet101和ResNet152示例


Posted in Python onJanuary 14, 2020

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)

以上这篇PyTorch实现ResNet50、ResNet101和ResNet152示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python实现备份文件实例
Sep 16 Python
python过滤字符串中不属于指定集合中字符的类实例
Jun 30 Python
简单实现python爬虫功能
Dec 31 Python
python中pandas.DataFrame的简单操作方法(创建、索引、增添与删除)
Mar 12 Python
Python+PIL实现支付宝AR红包
Feb 09 Python
对python的文件内注释 help注释方法
May 23 Python
学生信息管理系统python版
Oct 17 Python
用Python中的turtle模块画图两只小羊方法
Apr 09 Python
关于Pytorch MaxUnpool2d中size操作方式
Jan 03 Python
python next()和iter()函数原理解析
Feb 07 Python
自定义Django_rest_framework_jwt登陆错误返回的解决
Oct 18 Python
基于Python实现的购物商城管理系统
Apr 27 Python
python重要函数eval多种用法解析
Jan 14 #Python
关于ResNeXt网络的pytorch实现
Jan 14 #Python
Python属性和内建属性实例解析
Jan 14 #Python
Python程序控制语句用法实例分析
Jan 14 #Python
dpn网络的pytorch实现方式
Jan 14 #Python
Django之form组件自动校验数据实现
Jan 14 #Python
简单了解python filter、map、reduce的区别
Jan 14 #Python
You might like
PHP中调用JAVA
2006/10/09 PHP
PHP用GD库生成高质量的缩略图片
2011/03/09 PHP
简单的php数据库操作类代码(增,删,改,查)
2013/04/08 PHP
浅谈PHP变量作用域以及地址引用问题
2013/12/27 PHP
PHP $_FILES中error返回值详解
2014/01/30 PHP
微信自定义分享php代码分析
2016/11/24 PHP
基于jquery实现的文字淡入淡出效果
2013/11/14 Javascript
利用浏览器全屏api实现js全屏
2014/01/16 Javascript
jquery中子元素和后代元素的区别示例介绍
2014/04/02 Javascript
Javascript让DEDECMS告别手写Tag
2014/09/01 Javascript
js实现Select列表各项上移和下移的方法
2015/08/14 Javascript
浅谈JavaScript中promise的使用
2017/01/11 Javascript
JavaScript实现垂直滚动条效果
2017/01/18 Javascript
JS实现中国公民身份证号码有效性验证
2017/02/20 Javascript
Angular 4.x 路由快速入门学习
2017/05/03 Javascript
vue.js 微信支付前端代码分享
2018/02/10 Javascript
[02:44]DOTA2英雄基础教程 魅惑魔女
2014/01/07 DOTA
Python使用scrapy抓取网站sitemap信息的方法
2015/04/08 Python
分享python数据统计的一些小技巧
2016/07/21 Python
对python 各种删除文件失败的处理方式分享
2018/04/24 Python
Python实现简易过滤删除数字的方法小结
2019/01/09 Python
python标准库os库的函数介绍
2020/02/12 Python
pycharm软件实现设置自动保存操作
2020/06/08 Python
Python confluent kafka客户端配置kerberos认证流程详解
2020/10/12 Python
Python环境使用OpenCV检测人脸实现教程
2020/10/19 Python
HTML5 用动画的表现形式装载图像
2016/03/08 HTML / CSS
Belle Maison倍美丛官网:日本千趣会旗下邮购网站
2016/07/22 全球购物
Larsson & Jennings官网:现代瑞士钟表匠
2018/03/20 全球购物
函授本科毕业自我鉴定
2013/10/09 职场文书
公司人力资源的自我评价
2014/01/02 职场文书
综合实践活动方案
2014/02/14 职场文书
任命书模板
2014/06/04 职场文书
2014年班级工作总结
2014/11/14 职场文书
家庭财产分割协议范文
2014/11/24 职场文书
会计求职自荐信范文
2015/03/04 职场文书
vue配置型表格基于el-table拓展之table-plus组件
2022/04/12 Vue.js