ResNet网络结构

news2024/9/23 13:29:20

Deep Residual Learning for Image Recognition

论文:https://arxiv.org/abs/1512.03385

代码:ResNet网络详解及Pytorch代码实现(超详细帮助你掌握ResNet原理及实现)_basic block结构图_武晨的博客-CSDN博客

【DL系列】ResNet网络结构详解、完整代码实现_resnet代码_DearAlbert的博客-CSDN博客

Resnet残差块

 

resnet网络变体

resnet预训练模型下载

# 使用命令下载:wget 相应模型地址

# 提供官方预训练模型的下载地址
model_urls = {
    'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
    'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
    'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',
    'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',
    'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',
    'resnext50_32x4d': 'https://download.pytorch.org/models/resnext50_32x4d-7cdf4587.pth',
    'resnext101_32x8d': 'https://download.pytorch.org/models/resnext101_32x8d-8ba56ff5.pth',
    'wide_resnet50_2': 'https://download.pytorch.org/models/wide_resnet50_2-95faca4d.pth',
    'wide_resnet101_2': 'https://download.pytorch.org/models/wide_resnet101_2-32ee1156.pth',
}

resnet网络

import torch
import torch.nn as nn


__all__ = ['ResNet', 'resnet50', 'resnet101' , 'resnet18' , 'resnet34']


#提供官方预训练模型的下载地址
model_urls = {
    'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
    'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
    'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',
    'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',
    'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',
    'resnext50_32x4d': 'https://download.pytorch.org/models/resnext50_32x4d-7cdf4587.pth',
    'resnext101_32x8d': 'https://download.pytorch.org/models/resnext101_32x8d-8ba56ff5.pth',
    'wide_resnet50_2': 'https://download.pytorch.org/models/wide_resnet50_2-95faca4d.pth',
    'wide_resnet101_2': 'https://download.pytorch.org/models/wide_resnet101_2-32ee1156.pth',
}


def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
    return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
                     padding=dilation, groups=groups, bias=False, dilation=dilation)


def conv1x1(in_planes, out_planes, stride=1):
    return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)

#定义BasicBlock
class BasicBlock(nn.Module):
    expansion = 1

    def __init__(self, inplanes, planes, stride=1, downsaple=None, groups=1,
                 base_width=64, dilation=1, norm_layer=None):
        super(BasicBlock, self).__init__()
        if norm_layer is None:
            norm_layer = nn.BatchNorm2d
        if groups !=1 or base_width != 64:
            raise ValueError('BasicBlock only supports groups=1 and base_width=64')
        if dilation > 1:
            raise NotImplementedError("Dilation > 1 not supported in BasicBlock")

        #下面定义BasicBlock中的各个层
        self.conv1 = conv3x3(inplanes, planes, stride)
        self.bn1 = norm_layer(planes)
        self.relu = nn.ReLU(inplace=True) #inplace为True表示进行原地操作,一般默认为False,表示新建一个变量存储操作
        self.conv2 = conv3x3(planes, planes)
        self.bn2 = norm_layer(planes)
        self.dowansample = downsaple
        self.stride = stride

    #定义前向传播函数将前面定义的各层连接起来
    def forward(self, x):
        identity = x #这是由于残差块需要保留原始输入

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

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

        if self.dowansample is not None: #这是为了保证原始输入与卷积后的输出层叠加时维度相同
            identity = self.dowansample(x)

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

        return out


class Bottleneck(nn.Module):
    expansion = 4

    def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
                 base_width=64, dilation=1, norm_layer=None):
        super(Bottleneck, self).__init__()
        if norm_layer is None:
            norm_layer = nn.BatchNorm2d
        width = int(planes * (base_width / 64.)) * groups

        self.conv1 = conv1x1(inplanes, width)
        self.bn1 = norm_layer(width)
        self.conv2 = conv3x3(width, width, stride, groups, dilation)
        self.bn2 = norm_layer(width)
        self.conv3 = conv1x1(width, planes * self.expansion)
        self.bn3 = norm_layer(planes * self.expansion)
        self.relu = nn.ReLU(inplace=True)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        identity = 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)

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

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

        return out


class ResNet(nn.Module):

    def __init__(self, block, layers, zero_init_residual=False, groups=1,
                 width_per_group=64, replace_stride_with_dilation=None, norm_layer=None):
        super(ResNet, self).__init__()

        if norm_layer is None:
            norm_layer = nn.BatchNorm2d
        self._norm_layer = norm_layer

        self.inplanes = 128
        self.dilation = 1
        if replace_stride_with_dilation is None:
            replace_stride_with_dilation = [False, False, False]
        if len(replace_stride_with_dilation) != 3:
            raise ValueError("replace_stride_with_dilation should be None "
                             "or a 3-element tuple, got {}".format(replace_stride_with_dilation))
        self.groups = groups
        self.base_width = width_per_group
        self.conv1 = nn.Sequential(
            nn.Conv2d(3, 64, kernel_size=3, stride=2, padding=1, bias=False),
            norm_layer(64),
            nn.ReLU(inplace=True),
            nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1, bias=False),
            norm_layer(64),
            nn.ReLU(inplace=True),
            nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1, bias=False),
        )
        self.bn1 = norm_layer(self.inplanes)
        self.relu = nn.ReLU(inplace=True)
        self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
        self.layer1 = self._make_layer(block, 64, layers[0])
        self.layer2 = self._make_layer(block, 128, layers[1], stride=2,
                                       dilate=replace_stride_with_dilation[0])
        self.layer3 = self._make_layer(block, 256, layers[2], stride=2,
                                       dilate=replace_stride_with_dilation[1])
        self.layer4 = self._make_layer(block, 512, layers[3], stride=2,
                                       dilate=replace_stride_with_dilation[2])

        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.GroupNorm)):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)

        if zero_init_residual:
            for m in self.modules():
                if isinstance(m, Bottleneck):
                    nn.init.constant_(m.bn3.weight, 0)

    def _make_layer(self, block, planes, blocks, stride=1, dilate=False):
        norm_layer = self._norm_layer
        downsample = None
        previous_dilation = self.dilation
        if dilate:
            self.dilation *= stride
            stride = 1
        if stride != 1 or self.inplanes != planes * block.expansion:
            downsample = nn.Sequential(
                conv1x1(self.inplanes, planes * block.expansion, stride),
                norm_layer(planes * block.expansion),
            )

        layers = list()
        layers.append(block(self.inplanes, planes, stride, downsample, self.groups,
                            self.base_width, previous_dilation, norm_layer))
        self.inplanes = planes * block.expansion
        for _ in range(1, blocks):
            layers.append(block(self.inplanes, planes, groups=self.groups,
                                base_width=self.base_width, dilation=self.dilation,
                                norm_layer=norm_layer))

        return nn.Sequential(*layers)

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

        c1 = self.layer1(x)
        c2 = self.layer2(c1)
        c3 = self.layer3(c2)
        c4 = self.layer4(c3)

        return c1, c2, c3, c4


def _resnet(arch, block, layers, pretrained, **kwargs):
    model = ResNet(block, layers, **kwargs)
    if pretrained:
        pretrained_path = "pretrained/%s.pth" % arch
        state_dict = torch.load(pretrained_path)
        model.load_state_dict(state_dict, strict=False)
    return model




def resnet50(pretrained=False, **kwargs):
    return _resnet('resnet50', Bottleneck, [3, 4, 6, 3], pretrained, **kwargs)

def resnet101(pretrained=False, **kwargs):
    return _resnet('resnet101', Bottleneck, [3, 4, 23, 3], pretrained, **kwargs)

def resnet18(pretrained=False, **kwargs):
    return _resnet('resnet18', BasicBlock, [2, 2, 2, 2], pretrained, **kwargs)

def resnet34(pretrained=False, **kwargs):
    return _resnet('resnet34', BasicBlock, [3, 4, 6, 3], pretrained, **kwargs)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/689912.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

前端Vue自定义签到积分获取弹框抽取红包弹框 自定义弹框内容 弹框顶部logo

前端Vue自定义签到积分获取弹框抽取红包弹框 自定义弹框内容 弹框顶部logo&#xff0c; 下载完整代码请访问uni-app插件市场地址&#xff1a;https://ext.dcloud.net.cn/plugin?id13204 效果图如下&#xff1a; # cc-downloadDialog #### 使用方法 使用方法 <!-- show&…

用VSCode开发的Vue项目请求HBuilder项目的JSON数据

在学Vue之前采用HBuilder学习了HTML,CSS.JavaScript&#xff0c;jQuery&#xff0c;AJAX&#xff0c;最方便的就是可以请求项目中的JSON数据&#xff0c;当然也可以请求【聚合数据】的数据。 现在用VSCode开发&#xff0c;去访问HBuilder发布的项目中的json数据&#xff0c;因…

chatgpt赋能python:Python计算器程序代码:一种简单却强大的工具

Python计算器程序代码&#xff1a;一种简单却强大的工具 如果你是一名计算机编程爱好者&#xff0c;那你一定不会陌生于Python编程语言。Python是如今最受欢迎的编程语言之一&#xff0c;它简单易学、功能强大&#xff0c;也有着庞大的社区支持&#xff0c;使得它成为了很多人…

嵌入式ppt

第二章 第五章 第六章 第七章 第八章 第九章 第十章 考点 条件编译 volatile、static、 union、 struct、 const指针 堆与栈的不同点 3.功能模块应用题 (1) GPIO 的应用:流水灯的电路及软件编码、驱动数码管的电路及编码。 (2)外部中断的应用:电路及回调函数编码。 (3) …

云原生安全取决于开源

本文首发微信公众号网络研究院&#xff0c;关注获取更多。 Kubernetes 和 K3S 等技术是云原生计算的成功和开源力量的代名词。他们在竞争中大获全胜绝非偶然。当企业寻求安全的云原生环境时&#xff0c;开源是难题中的关键部分。 工具法则是众所周知的认知偏差。当你只有一把…

openeuler22.03系统salt-minion启动报“Invalid version: ‘cpython‘“错的问题处理

某日&#xff0c;检查发现一台openeuler22.03 SP1系统的服务器上之前正常运行的saltstack客户端minion未运行&#xff0c;查看服务状态&#xff0c;报"Invalid version: cpython"错&#xff0c;无法正常运行&#xff0c;本文记录问题处理过程。 一、检查salt-minion…

【Nginx】第三章 Nginx常用的命令和配置文件

第3章 Nginx常用的命令和配置文件 3.1 nginx常用的命令 &#xff08;1&#xff09;启动命令 在/usr/local/nginx/sbin目录下执行 ./nginx &#xff08;2&#xff09;关闭命令 在/usr/local/nginx/sbin目录下执行 ./nginx -s stop &#xff08;3&#xff09;重新加载命令…

docker报错 driver failed programming external connectivity on e

Error response from daemon: driver failed programming external connectivity on e ndpoint mj 原因&#xff1a;在我们启动了Docker后&#xff0c;我们再对防火墙firewalld进行操作&#xff0c;就会发生上述报错&#xff0c; 详细原因&#xff1a;docker服务启动时定义的…

分别用最小二乘法和梯度下降法实现线性回归

下面代码中包含了两种方法 import numpy as npnp.random.seed(1234)x np.random.rand(500, 3) # x为数据&#xff0c;500个样本&#xff0c;每个样本三个自变量 y x.dot(np.array([4.2, 5.7, 10.8])) # y为标签&#xff0c;每个样本对应一个y值# 最小二乘法 class LR_LS():d…

LENOVO联想笔记本拯救者Legion R7000P APH8 2023款(82Y9)原厂Windows11系统原装出厂状态预装系统

lenovo联想笔记本电脑&#xff0c;拯救者Legion R7000P APH8(2023款)(82Y9)原装出厂Windows11系统安装&#xff0c;预装系统重装镜像&#xff0c;恢复出厂状态 系统自带所有驱动、出厂主题壁纸LOGO、Office办公软件、联想电脑管家等预装程序 所需要工具&#xff1a;16G或以上…

element ui - el-select 手动设置高度

el-select 手动设置高度 场景代码 场景 当我们的页面想要手动设置 element ui 中 el-select 的高度时&#xff0c;如果只是通过设置 el-select 的 height 属性时&#xff0c;会发现调整无效。 继续对 el-select 中的 input 元素 .el-input__inner 设置。会发现高度生效了&…

机器视觉硬件选型-机器视觉三大技术之一打光(图像采集技术)

机器视觉halcon-胶水轮廓检测 针对被测物的不同特征,要用不同打光方式,才可以突出被测物,便于图像处技术进一步处理。 机器视觉作为当前的热门行业,是计算机视觉的延伸,集结了光学、机械、电子、计算机软硬件等各方面技术,旨在于将所需求的图像特征提取出来,以方便视觉系…

读发布!设计与部署稳定的分布式系统(第2版)笔记13_断路器与舱壁

1. 电路保险丝 1.1. 保险丝通过自身率先失效&#xff0c;控制整体的系统失效方式 1.2. 当遇到电阻时&#xff0c;电流产生的热量与电流强度的平方和电阻的乘积&#xff08;I^2R&#xff09;成正比 1.3. 在房子着火前先行熔断&#xff0c;切断电路并避免火灾 1.4. 民用保险丝…

HOT22-相交链表

leetcode原题链接&#xff1a;相交链表 题目描述 给你两个单链表的头节点 headA 和 headB &#xff0c;请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点&#xff0c;返回 null 。 图示两个链表在节点 c1 开始相交&#xff1a; 题目数据 保证 整个链式结…

可视化低代码编程平台项目

后端Spring BootMySQL 前端Vue 同学通过这个项目练手&#xff0c;简历上写出来也蛮有亮点的。 技术栈比较全面&#xff0c; 项目可以提高公司的开发效率&#xff0c;特别是方便产品经理或者业务线人员直接可视化生成UI

java之路——带你了解springboot框架与其基本使用

文章目录 一、springboot的发展背景二、什么是springboot三、springboot的地位四、开发步骤 一、springboot的发展背景 要了解springboot&#xff0c;我们先要了解Spring Boot的发展背景。 Spring Boot的发展背景可以追溯到Spring Framework的诞生和演进过程。 首先&#xff…

Linux常用命令——free命令

在线Linux命令查询工具 free 显示内存的使用情况 补充说明 free命令可以显示当前系统未使用的和已使用的内存数目&#xff0c;还可以显示被内核使用的内存缓冲区。 语法 free(选项)选项 -b # 以Byte为单位显示内存使用情况&#xff1b; -k # 以KB为单位显示内存使用情况…

【Docker】Exited 139解决Window下docker启动oracle11g失败Exited 139

前几天&#xff0c;在docker安装了oracle11&#xff0c;安装非常简单&#xff0c;但是启动的时候启动不起来&#xff0c;且没有任何log日志输出&#xff01; docker 拉取安装oracle11 docker pull registry.cn-hangzhou.aliyuncs.com/helowin/oracle_11g安装完成后启动oracle …

Nature Biomedical Engineering --利用白细胞“吃掉”实体瘤

癌症仍然是美国死亡率最高的疾病之一&#xff0c;每年导致的死亡人数超过60万人。形成实体肿瘤的癌症&#xff0c;如乳房、大脑或皮肤肿瘤&#xff0c;尤其难以治疗。外科手术通常是对抗实体肿瘤的第一道防线。但是&#xff0c;手术可能无法完全清除癌细胞&#xff0c;残留的细…

Linux运维监控学习笔记6

触发器&#xff08;重点&#xff09; 触发器&#xff08;trigger&#xff09;&#xff1a;定义监控项到达一个临界值&#xff08;阈值&#xff09;或者满足一个条件&#xff0c;就会发现状态变化&#xff08;OK变为Problem&#xff0c;Problem变为OK&#xff09;。 监控agent1…