PyTorch建立resnet34和resnet101代码[通俗易懂]

PyTorch建立resnet34和resnet101代码[通俗易懂]model.pyimporttorch.nnasnnimporttorchclassBasicBlock(nn.Module):expansion=1def__init__(self,in_channel,out_channel,stride=1,downsample=None):super(BasicBlock,self).__init__()self.conv1=nn.Conv2d(in_channels=

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

Jetbrains全系列IDE稳定放心使用

model.py

import torch.nn as nn
import torch


class BasicBlock(nn.Module):
    expansion = 1

    def __init__(self, in_channel, out_channel, stride=1, downsample=None):
        super(BasicBlock, self).__init__()
        self.conv1 = nn.Conv2d(in_channels=in_channel, out_channels=out_channel,
                               kernel_size=3, stride=stride, padding=1, bias=False)
        self.bn1 = nn.BatchNorm2d(out_channel)
        self.relu = nn.ReLU()
        self.conv2 = nn.Conv2d(in_channels=out_channel, out_channels=out_channel,
                               kernel_size=3, stride=1, padding=1, bias=False)
        self.bn2 = nn.BatchNorm2d(out_channel)
        self.downsample = downsample

    def forward(self, x):
        identity = x
        if self.downsample is not None:
            identity = self.downsample(x)

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)

        out += identity
        out = self.relu(out)

        return out


class Bottleneck(nn.Module):
    expansion = 4

    def __init__(self, in_channel, out_channel, stride=1, downsample=None):
        super(Bottleneck, self).__init__()
        self.conv1 = nn.Conv2d(in_channels=in_channel, out_channels=out_channel,
                               kernel_size=1, stride=1, bias=False)  # squeeze channels
        self.bn1 = nn.BatchNorm2d(out_channel)
        # -----------------------------------------
        self.conv2 = nn.Conv2d(in_channels=out_channel, out_channels=out_channel,
                               kernel_size=3, stride=stride, bias=False, padding=1)
        self.bn2 = nn.BatchNorm2d(out_channel)
        # -----------------------------------------
        self.conv3 = nn.Conv2d(in_channels=out_channel, out_channels=out_channel*self.expansion,
                               kernel_size=1, stride=1, bias=False)  # unsqueeze channels
        self.bn3 = nn.BatchNorm2d(out_channel*self.expansion)
        self.relu = nn.ReLU(inplace=True)
        self.downsample = downsample

    def forward(self, x):
        identity = x
        if self.downsample is not None:
            identity = self.downsample(x)

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)
        out = self.relu(out)

        out = self.conv3(out)
        out = self.bn3(out)

        out += identity
        out = self.relu(out)

        return out


class ResNet(nn.Module):

    def __init__(self, block, blocks_num, num_classes=1000, include_top=True):
        super(ResNet, self).__init__()
        self.include_top = include_top
        self.in_channel = 64

        self.conv1 = nn.Conv2d(3, self.in_channel, kernel_size=7, stride=2,
                               padding=3, bias=False)
        self.bn1 = nn.BatchNorm2d(self.in_channel)
        self.relu = nn.ReLU(inplace=True)
        self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
        self.layer1 = self._make_layer(block, 64, blocks_num[0])
        self.layer2 = self._make_layer(block, 128, blocks_num[1], stride=2)
        self.layer3 = self._make_layer(block, 256, blocks_num[2], stride=2)
        self.layer4 = self._make_layer(block, 512, blocks_num[3], stride=2)
        if self.include_top:
            self.avgpool = nn.AdaptiveAvgPool2d((1, 1))  # output size = (1, 1)
            self.fc = nn.Linear(512 * block.expansion, num_classes)

        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')

    def _make_layer(self, block, channel, block_num, stride=1):
        downsample = None
        if stride != 1 or self.in_channel != channel * block.expansion:
            downsample = nn.Sequential(
                nn.Conv2d(self.in_channel, channel * block.expansion, kernel_size=1, stride=stride, bias=False),
                nn.BatchNorm2d(channel * block.expansion))

        layers = []
        layers.append(block(self.in_channel, channel, downsample=downsample, stride=stride))
        self.in_channel = channel * block.expansion

        for _ in range(1, block_num):
            layers.append(block(self.in_channel, channel))

        return nn.Sequential(*layers)

    def forward(self, x):
        x = self.conv1(x)
        x = self.bn1(x)
        x = self.relu(x)
        x = self.maxpool(x)

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

        if self.include_top:
            x = self.avgpool(x)
            x = torch.flatten(x, 1)
            x = self.fc(x)

        return x


def resnet34(num_classes=1000, include_top=True):
    return ResNet(BasicBlock, [3, 4, 6, 3], num_classes=num_classes, include_top=include_top)


def resnet101(num_classes=1000, include_top=True):
    return ResNet(Bottleneck, [3, 4, 23, 3], num_classes=num_classes, include_top=include_top)

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/188326.html原文链接:https://javaforall.net

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


相关推荐

  • Q学习(Q-learning)入门小例子及python实现

    Q学习(Q-learning)入门小例子及python实现一、从马尔科夫过程到Q学习#有一定基础的读者可以直接看第二部分Q学习(Q-learning)算法是一种与模型无关的强化学习算法,以马尔科夫决策过程(MarkovDecisionProcesses,MDPs)为理论基础。标准的马尔科夫决策过程可以用一个五元组<S,A,P,R,γ>表示,其中:S是一个离散有界的状态空间; A是一个离散的动作空间; P为状态转…

    2022年10月4日
    2
  • 常见电子元器件的常用品牌汇总

    ​抽时间汇总了一些常见电子元器件常用品牌,大家在元器件选型时可以参考。电阻:Yageo国巨、Uniohm厚声、Walsin华新科、Fenghua风华、Ralec旺诠、KOA兴亚、Panasonic松下、AVX、Rohm罗姆、Samsung三星、TDK、TMTEC泰铭、Kyocera京瓷、PHYCOM飞元。电容:Yageo国巨、Samsung三星、Eyang宇阳、Murata村田、Taiyo太诱、Fenghua风华、Kyocera京瓷、HEC禾伸堂、Kemet基美、ISND华信安、AVX、TDK、Nich

    2022年4月4日
    81
  • javaee学生选课系统源码_学生选课管理系统流程图

    javaee学生选课系统源码_学生选课管理系统流程图基于javaweb的ssm学校教务管理系统(管理员,教师,学生)文章结构一、开发框架及业务方向1.开发环境2.开发框架3.整体业务二、项目结构及页面展示1.项目整体结构2.用户页面3.管理员页面***需要源码的加企鹅:671033846;备注CSDN即可******文章结构一、开发框架及业务方向1.开发环境操作系统不限:java特性,一套代码,导出运行jdk版本不限:推荐jdk1.8tomcat版本不限:推荐Tomcat8.0数据库mysql:版本不限,推荐mysql8.0以下开发工具:e

    2022年10月15日
    3
  • 8种HOOK技术[通俗易懂]

    8种HOOK技术[通俗易懂]1.IAT_HOOKIAT是程序中存储导入函数地址的数据结构,如果HOOK了导入函数地址。就可以在函数调用的时候,将函数流程HOOK到我们指定的流程。但是我个人觉得这种方式最好要结合DLL注入的方式,如果单纯的使用HOOK,那么就需要将需要执行的操作的shellcode写入目标进程,如果操作复杂,可能需要的shellcode量特别大,所以我们需要借助DLL注入,这样就将我们需要执行的代码写入…

    2022年5月26日
    34
  • icmp报文校验算法

    icmp报文校验算法备忘用检验和算法在TCP/IP协议族中是比较常见的算法。IP、ICMP、UDP和TCP报文头部都有校验和字段,不过IP、TCP、UDP只针对首部计算校验和  而ICMP对首部和报文数据一起计算校验和。检验和算法可以分成两步来实现。首先在发送端,有以下三步:1.把校验和字段置为0。2.对需要校验的数据看成以16bit为单位的数字组成,依次进行二进制求和。3.将上一步的求和结果取反,存入校验和字

    2022年5月6日
    48
  • 杭电OJ2058_杭电OJ

    杭电OJ2058_杭电OJ杭电OJ2058我写的超时了下面是不超时的#include<stdio.h>#include<math.h>intmain(){ intn,m,i,j; while(scanf(“%d%d”,&n,&m)!=EOF){ if(n==0&&m==0) break; for(j=(int)sqrt((double)(2*m));j>=1;j–){ i=(

    2022年10月2日
    5

发表回复

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

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