PyTorch实现的ResNet50、ResNet101和ResNet152

PyTorch实现的ResNet50、ResNet101和ResNet152PyTorch实现的ResNet50、ResNet101和ResNet152importtorchimporttorch.nnasnnimporttorchvisionprint("PyTorchVersion:",torch.__version__)print("TorchvisionVersion:",torchvision.__version__)

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE稳定放心使用

PyTorch实现的ResNet50、ResNet101和ResNet152
PyTorch: https://github.com/shanglianlm0525/PyTorch-Networks
在这里插入图片描述

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://javaforall.net/184890.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • Angular 图片懒加载

    Angular图片懒加载有很多写好的nglibrary可以用,我这里用的是ng-lazyload-image。可以在npm官网直接搜索。安装npminstallng-lazyload-image–save在module中导入:import{CommonModule}from’@angular/common’;import{LazyLoad…

    2022年4月9日
    131
  • redisson锁 tryLock的使用及正确用法

    redisson锁 tryLock的使用及正确用法方式一RLocklock=redissonClient.getLock(“Export:create:”+Context.get().getCorpId());try{if(lock.tryLock(5,10,TimeUnit.SECONDS)){//业务处理}else{Assert.isTrue(false,”排队中,请稍后重试!”);}}catch(InterruptedExceptione){.

    2022年8月31日
    2
  • AMCL是什么公司_论文技术参数是什么

    AMCL是什么公司_论文技术参数是什么整理内容来自:http://wiki.ros.org/amcl1、AMCL订阅的节点:scan(sensor_msgs/LaserScan):激光数据tf(tf/tfMessage):各种转

    2022年8月5日
    7
  • Mybatis 拦截器简述[通俗易懂]

    Mybatis 拦截器简述[通俗易懂]一、Mybatis拦截器可以做到什么慢查询,SQL异常监控数据预处理(加密,自生成字段)数据脱敏数据权限过滤二、MybatisSQL执行流程这里重点关注InterceptorChain,它会为Mybatis的四大对象织入代理。我们自定义生成的拦截器也将通过InterceptorChain织入。三、Mybatis拦截器使用方式拦截粒度为方法签名自定义拦截器需使用@Intercepts和@Signature注解来指定拦截类和方法。例如拦截Exceptor的query和update

    2025年10月9日
    3
  • 扑克牌花色排列_扑克牌花色大小顺序图片

    扑克牌花色排列_扑克牌花色大小顺序图片前阵子去某家公司笔试,发现有一道扑克牌排序的算法题,题目的大致意思是从一个给定的扑克牌文件读取内容,里面的内容是每行一个扑克牌牌面值,如♠J,♥Q,♣A,♦10等,要求对该文本进行两种排序,一种是按S

    2022年8月3日
    13
  • 微创业平台

    一种专为大学生创业服务的平台。主旨是,让大学生创业创新,在某种比较简单,比较容易的环境里进行。让大学生创业创新,不要太多的风险,比较容易达成创业目标。云电话,一种5G新电话。特别适合大学生微创业,更需要大学生微创新。将云电话平台,建设成湖铁微创业平台,是深圳云电话平台,与湖铁职院创新创业学院,合作打造的专为湖铁职院大学生,创新创业服务的平台。建设好湖铁微创业平台,具有重大的社会意义。√成功示范作用。先在创新创业学院,打造标杆试点MVP。√便…

    2022年4月4日
    87

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号