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)
上一篇 2022年10月7日 下午5:00
下一篇 2022年10月7日 下午5:00


相关推荐

  • pycharm注释方法

    pycharm注释方法用的 pycharm 有三种注释方式 1 用一对 括起来要注释的代码块 2 用一对 括起来要注释的代码块 3 选中要注释的代码 按下 ctrl 注释

    2026年3月18日
    1
  • matlab里的for循环,matlabfor循环

    matlab里的for循环,matlabfor循环matlab 动态 for 帮你快速入门 MATLAB 基本知识篇 matlabfor 循环 matlabfor 语句 Matlabfor 循环 数学 自然科学 专业资料 for 循环语句 for nEnd 其中默认的不错为 1 具体的编程内容 end 看看 matlab 的帮助吧 最简单的语句 fori 初值 增量 终值循环体 end 一般就是用在需要用到循环的 mat

    2026年3月17日
    1
  • RSA加密算法(原理)

    RSA加密算法(原理)RSA 加密算法是最常用的非对称加密算法 CFCA 在证书服务中离不了它 但是有不少新来的同事对它不太了解 恰好看到一本书中作者用实例对它进行了简化而生动的描述 使得高深的数学理论能够被容易地理解 我们经过整理和改写特别推荐给大家阅读 希望能够对时间紧张但是又想了解它的同事有所帮助 RSA 是第一个比较完善的公开密钥算法 它既能用于加密 也能用于数字签名 RSA 以它的三个发

    2026年3月26日
    2
  • tracert工作原理简述_tracert三个时间

    tracert工作原理简述_tracert三个时间linux上为tracerouteTracert 命令用 IP 生存时间 (TTL) 字段和 ICMP 错误消息来确定从一个主机到网络上其他主机的路由。首先,tracert送出一个TTL是1的IP 数据包到目的地,当路径上的第一个路由器收到这个数据包时,它将TTL减1。此时,TTL变为0,所以该路由器会将此数据包丢掉,并送回一个「ICMPtimeexceeded」消息(包

    2026年3月9日
    4
  • isnotempty和isnotnull_isannotationpresent()用法

    isnotempty和isnotnull_isannotationpresent()用法引入包:org.apache.commons.lang3.StringUtils;1.publicstaticbooleanisEmpty(Stringstr)判断某字符串是否为空,为空的标准是str==null或str.length()==0下面是StringUtils判断是否为空的示例:StringUtils.isEmpty(null)=trueStringUtils.isEm…

    2026年4月15日
    5
  • django自定义用户认证_编写一个自定义异常类

    django自定义用户认证_编写一个自定义异常类前言如果我们不用使用drf那套认证规则,我们想自定义认证类,那么我们首先要知道,drf本身是如何定义认证规则的,也就是要查看它的源码是如何写的源码分析源码的入口在APIView.py文件下的di

    2022年7月31日
    7

发表回复

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

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