【PyTorch】3-基础实战(ResNet)

PyTorch:3-基础实战

注:所有资料来源且归属于thorough-pytorch(https://datawhalechina.github.io/thorough-pytorch/),下文仅为学习记录

3.1:ResNet基本介绍

退化现象(degradation):增加网络层数的过程中,随着训练准确率逐渐饱和,继续增加层数,训练准确率出现下降的现象。且这种下降不是过拟合。

快捷连接(shortcut connection):将输入直接连接到后面的层,一定程度缓解了梯度消失和梯度爆炸,消除深度过大导致神经网络训练困难的问题。

梯度消失和梯度爆炸的根源:DNN结构,和,反向传播算法

梯度爆炸:网络层之间的梯度(值大于 1.0)重复相乘导致的指数级增长

梯度消失:网络层之间的梯度(值小于 1.0)重复相乘导致的指数级变小

3.2:torchvision的源代码

卷积核封装

封装3x3和1x1卷积核

def conv3x3(in_planes: int, out_planes: int, stride: int = 1, groups: int = 1, dilation: int = 1) -> nn.Conv2d:
    """3x3 convolution with padding"""
    return nn.Conv2d(
        in_planes,			# 输入通道数
        out_planes,			# 输出通道数
        kernel_size=3,		# 卷积核尺寸
        stride=stride,		# 步长
        padding=dilation,	# 填充
        groups=groups,		# 分组
        bias=False,			# 偏移量
        dilation=dilation,	# 空洞卷积的中间间隔
    )


def conv1x1(in_planes: int, out_planes: int, stride: int = 1) -> nn.Conv2d:
    """1x1 convolution"""
    return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
	# 解释同上

基本模块设计

ResNet常见的大小有ResNet-18,ResNet-34,ResNet-50、ResNet-101和ResNet-152,其中网络后面的数字代表的是网络的层数

两个基本模块:BasicBlock和BottleNeck

两个block类输入一个通道为in_planes维的度特征图,输出一个planes*block.expansion维的特征图,其中planes的数目大小等于in_planes。

支路上的downsample操作:对shortcut支路进行大小或维度上的调整。

shortcut connection

【1】同等维度的映射:输入输出直接相加
F ( x ) + x F(x)+x F(x)+x
【2】不同维度的映射:给x补充一个线性映射来匹配维度(通常是1x1卷积)

basic block

BasicBlock模块用来构建resnet18和resnet34

class BasicBlock(nn.Module):
    expansion: int = 1

    def __init__(
        self,
        inplanes: int,
        planes: int,
        stride: int = 1,
        downsample: Optional[nn.Module] = None,
        groups: int = 1,
        base_width: int = 64,
        dilation: int = 1,
        norm_layer: Optional[Callable[..., nn.Module]] = None,
    ) -> None:
        super().__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")
        # Both self.conv1 and self.downsample layers downsample the input when stride != 1
        self.conv1 = conv3x3(inplanes, planes, stride)
        self.bn1 = norm_layer(planes)
        self.relu = nn.ReLU(inplace=True)
        self.conv2 = conv3x3(planes, planes)
        self.bn2 = norm_layer(planes)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x: Tensor) -> Tensor:
        identity = x  			# 备份

        out = self.conv1(x)  	# 对x做卷积 
        out = self.bn1(out)  	# 对x归一化 
        out = self.relu(out)  	# 对x用激活函数

        out = self.conv2(out)  	# 对x做卷积
        out = self.bn2(out)  	# 归一化

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

        out += identity  		# 进行downsample
        out = self.relu(out)

        return out
bottle neck

BottleNeck模块用来构建resnet50,resnet101和resnet152

class Bottleneck(nn.Module):
    expansion: int = 4  # 对输出通道进行倍增

    def __init__(
        self,
        inplanes: int,
        planes: int,
        stride: int = 1,
        downsample: Optional[nn.Module] = None,
        groups: int = 1,
        base_width: int = 64,
        dilation: int = 1,
        norm_layer: Optional[Callable[..., nn.Module]] = None,
    ) -> None:
        super().__init__()
        if norm_layer is None:
            norm_layer = nn.BatchNorm2d
        width = int(planes * (base_width / 64.0)) * groups
        # Both self.conv2 and self.downsample layers downsample the input when stride != 1
        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

    # Bottleneckd forward函数和BasicBlock类似
    def forward(self, x: Tensor) -> Tensor:
        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: Type[Union[BasicBlock, Bottleneck]], # 选择基本模块
        layers: List[int],							# 每一层block的数目构成 -> [3,4,6,3]
        num_classes: int = 1000, 					# 分类数目
        zero_init_residual: bool = False, 			# 初始化
        
        #######其他卷积构成,与本文ResNet无关######
        groups: int = 1,
        width_per_group: int = 64,
        replace_stride_with_dilation: Optional[List[bool]] = None,
        #########################################
        
        norm_layer: Optional[Callable[..., nn.Module]] = None, # norm层
    ) -> None:
        super().__init__()
        _log_api_usage_once(self)
        if norm_layer is None:
            norm_layer = nn.BatchNorm2d
        self._norm_layer = norm_layer
		
        self.inplanes = 64 # 输入通道
        
        #######其他卷积构成,与本文ResNet无关######
        self.dilation = 1 # 空洞卷积
        if replace_stride_with_dilation is None:
            # each element in the tuple indicates if we should replace
            # the 2x2 stride with a dilated convolution instead
            replace_stride_with_dilation = [False, False, False]
        if len(replace_stride_with_dilation) != 3:
            raise ValueError(
                "replace_stride_with_dilation should be None "
                f"or a 3-element tuple, got {replace_stride_with_dilation}"
            )
        self.groups = groups
        self.base_width = width_per_group
        #########################################
        
        self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3, 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)
        # 通过_make_layer带到层次化设计的效果
        self.layer1 = self._make_layer(block, 64, layers[0])  # 对应着conv2_x
        self.layer2 = self._make_layer(block, 128, layers[1], stride=2, dilate=replace_stride_with_dilation[0])  # 对应着conv3_x
        self.layer3 = self._make_layer(block, 256, layers[2], stride=2, dilate=replace_stride_with_dilation[1])  # 对应着conv4_x
        self.layer4 = self._make_layer(block, 512, layers[3], stride=2, dilate=replace_stride_with_dilation[2])  # 对应着conv5_x
        # 分类头
        self.avgpool = nn.AdaptiveAvgPool2d((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")
            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) and m.bn3.weight is not None:
                    nn.init.constant_(m.bn3.weight, 0)  # type: ignore[arg-type]
                elif isinstance(m, BasicBlock) and m.bn2.weight is not None:
                    nn.init.constant_(m.bn2.weight, 0)  # type: ignore[arg-type]
	# 层次化设计
    def _make_layer(
        self,
        block: Type[Union[BasicBlock, Bottleneck]], # 基本构成模块选择
        planes: int,  								# 输入的通道
        blocks: int, 								# 模块数目
        stride: int = 1, 							# 步长
        dilate: bool = False, 						# 空洞卷积,与本文无关
    ) -> nn.Sequential:
        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存储每个layer
        layers = []
        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,
                )
            )
		# 将layers通过nn.Sequential转化为网络
        return nn.Sequential(*layers)

    def _forward_impl(self, x: Tensor) -> Tensor:
        # See note [TorchScript super()]
        x = self.conv1(x)  		# conv1   x shape [1 64 112 112]
        x = self.bn1(x)   		# 归一化处理   
        x = self.relu(x)  		# 激活函数
        x = self.maxpool(x)  	# conv2_x的3x3 maxpool, x shape [1 64 56 56]

        x = self.layer1(x) # layer 1
        x = self.layer2(x) # layer 2
        x = self.layer3(x) # layer 3
        x = self.layer4(x) # layer 4

        x = self.avgpool(x) 	# 自适应池化
        x = torch.flatten(x, 1) 
        x = self.fc(x) 			# 分类

        return x

    def forward(self, x: Tensor) -> Tensor:
        return self._forward_impl(x) 

模型步骤

【1】首先是一个7 x 7的卷积作用在输入的3维图片上,并输入一个64维的特征图(即self.inplanes的初始值),通过BatchNorm层,ReLU层,MaxPool层。

【2】然后经过_make_layer()函数构建的4层layer。

【3】最后经过一个AveragePooling层,再经过一个fc层得到分类输出。

【4】在网络搭建起来后,还对模型的参数(Conv2d、BatchNorm2d、last BN)进行了初始化。

一个_make_layer()构建一个layer层,每一个layer层是两种基本模块的堆叠。

输入参数中block代表该layer堆叠模块的类型,可选BasicBlock或者BottleNeck。blocks代表该layer中堆叠的block的数目;planes与该layer最终输出的维度数有关,注意最终输出的维度数为planes * block.expansion。

变体

【1】Wider ResNet。

【2】DarkNet53。只是使用到了残差连接从而复用特征。

【3】ResNeXt。提出了一种介于普通卷积核深度可分离卷积的这种策略:分组卷积。通过控制分组的数量(基数)来达到两种策略的平衡。分组卷积的思想源自Inception,ResNeXt的每个分支的拓扑结构是相同的。

3.3:模型保存

【1】确定保存路径

【2】调用save函数

save_path = "./FahionModel.pkl"
torch.save(model, save_path)

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

“浙大学报英文版”订阅号这篇文章,丢名校脸面

今天翻到“浙大学报英文版”订阅号分享的一篇文章,介绍了一篇奇文,该论文的摘要(Abstract)非常任性,仅有一个单词— “Yes”。 原文链接:https://mp.weixin.qq.com/s/riw_YU3caBf7E6rdCbLE-Q 该论文是由J. …

如何为Postgres数据库设置安全的访问控制和权限管理

文章目录 解决方案1. 使用角色和权限管理2. 配置认证方法3. 使用网络访问控制4. 定期审查和更新权限 示例代码1. 创建角色并分配权限2. 配置密码认证3. 配置网络访问控制 总结 PostgreSQL是一个功能强大的开源关系型数据库系统,提供了丰富的权限和访问控制机制&…

bit、进制、位、时钟(窗口)、OSI七层网络模型、协议、各种码

1.bit与进制 (个人理解,具体电路是非常复杂的) 物理层数据流,bit表示物理层数据传输单位, 一个电路当中,通过通断来表示数字1和0 两个电路要通讯,至少要两根线,一根作为电势参照…

C语言入门课程学习笔记2

C语言入门课程学习笔记2 第8课 - 四则运算与关系运算第9课 - 逻辑运算与位运算第10课 - 深度剖析位运算第11课 - 程序中的选择结构 本文学习自狄泰软件学院 唐佐林老师的 C语言入门课程,图片全部来源于课程PPT,仅用于个人学习记录 第8课 - 四则运算与关系…

Java | Leetcode Java题解之第48题旋转图像

题目&#xff1a; 题解&#xff1a; class Solution {public void rotate(int[][] matrix) {int n matrix.length;// 水平翻转for (int i 0; i < n / 2; i) {for (int j 0; j < n; j) {int temp matrix[i][j];matrix[i][j] matrix[n - i - 1][j];matrix[n - i - 1]…

【Camera KMD ISP SubSystem笔记】CAM SYNC与DRQ②

DRQ的作用&#xff1a; DRQ负责调度管理pipeline里的node处理逻辑(通过node之间的dependency依赖机制) 利用多线程并行处理Pipeline中并行的node&#xff0c;加快处理速度 DRQ运转流程&#xff1a; DRQ先告诉node fill dependency&#xff0c; 此时seq id 为0…

15.接口自动化学习-Mock(挡板/测试桩)

场景&#xff1a; 新需求还未开发时&#xff0c;使用mock提早介入测试&#xff0c;等后边开发后&#xff0c;进行调试 三方接口返回效率低&#xff0c;使用mock技术走通流程 1.mock方式 &#xff08;1&#xff09;如果会写django或flask,可以写简单对应的代码 &#xff08;…

小红书的影视剧泥土刷剧5天涨千粉7天接商单轻轻松松月入了万没脑子运送游戏玩法,新手也可以快速上手

大家好&#xff0c;今天我将为大家介绍一个项目&#xff1a;在小红书上通过观看和分享影视剧内容&#xff0c;五天涨千粉&#xff0c;七天接商业订单&#xff0c;轻松月入过万。这个项目的玩法简单易学&#xff0c;即使是新手也能快速上手。 下载 地 址 &#xff1a; laoa1.c…

【网络安全】系统0day分析

前言 起因看见通告&#xff0c;描述是通过/lfw/core/rpc接口访问到PortalSpecServiceImpl类中的createSkinFile方法。 补丁名称&#xff1a;patch_portal65_lfw任意文件上传漏洞 补丁编码&#xff1a;NCM_NC6.5_000_109902_20240301_GP_281362040 【386G《黑客&网络安全入…

基于STM32的蓝牙小车(虚拟串口模拟)的Proteus仿真

文章目录 一、前言二、仿真图1.要求2.思路3.画图3.1 电源部分3.2 超声波测距部分3.3 电机驱动部分3.4 按键部分3.5 蓝牙部分3.6 显示屏部分3.7 整体 4.仿真5.软件 三、总结 一、前言 proteus本身并不支持蓝牙仿真&#xff0c;这里我采用虚拟串口的方式来模拟蓝牙控制。 这里给…

医院敏感文件交互 如何保障安全和效率?

医院会产生大量的敏感文件&#xff0c;这些敏感文件交互时&#xff0c;都需要使用特殊的手段&#xff0c;来保障数据的安全性。 医院的敏感数据主要包括以下几类&#xff1a; 1、患者基本信息&#xff1a;包括患者的姓名、身份证号码、户籍地或现住址、联系方式、文化程度、既…

jar包做成Windows Service 服务,不能访问网络映射磁盘

在Windows操作系统中&#xff0c;系统服务&#xff08;Services&#xff09;、计划任务&#xff08;Scheduled Tasks&#xff09;以及很多系统调用都是以SYSTEM系统账号进行操作的。用 net use 挂载&#xff0c;或者在文件管理器上直接挂载&#xff0c;挂载卷是以 Administrato…

504网关超时可能是哪些原因导致

当前随时互联网的发展普及&#xff0c;我们经常会使用到网站服务&#xff0c;许多网站为了提高打开速度&#xff0c;都会接入使用CDN。当我们在浏览网页或使用网络服务时&#xff0c;有时候可能有遇到网站打不开的情况&#xff0c;出现各式各样的错误代码&#xff0c;其中504网…

书生·浦语 大模型(学习笔记-5)XTuner 微调 LLM:1.8B、多模态、Agent

一&#xff1a;两种微调 增量与训练和指令微调的区别 二、数据的一生 原始数据转换为标准格式数据 添加对话模板&#xff0c;直接调用即可&#xff0c;会拼接 三、微调方案 三种加载对比 四、XTuner 五、8GB 显存玩转 LLM 五、InternLM2 1.8B模型&#xff08;相关知识&#x…

【火柴题】509移动两根火柴变成最大的数字

题目 509移动两根火柴变成最大的数字 <font face"DS-Digital" size"6">5&thinsp;0&thinsp;9</font>答案 <font face"DS-Digital" size"6">9&thinsp;1&thinsp;1&thinsp;8&thinsp;</font…

【JavaScript】Mockjs

基础语法 <script src"https://cdn.bootcdn.net/ajax/libs/Mock.js/1.0.0/mock-min.js"></script> <script>let mockData Mock.mock({age|10-50: 1, // 此时生成对象的 age 属性会是 10-50 之间的数 1 此时只是用来确定类型arr|5-10: [{id|1: 1,…

物联网五层架构:每一层都扮演着不可或缺的角色——青创智通

物联网五层架构涵盖了感知层、网络层、数据层、应用层和业务层&#xff0c;每一层都扮演着不可或缺的角色&#xff0c;共同构成了物联网的完整生态系统。下面我们将详细探讨这五层架构的功能和特点。 首先&#xff0c;感知层是物联网的起点&#xff0c;负责获取和识别各种物理世…

3DTiles特性与内容解析

一篇19年整理的比较老的笔记了。更多精彩内容尽在数字孪生平台。 瓦片种类 3DTiles瓦片有多种类型&#xff1a; b3dm(Batched 3D Model&#xff0c;批量3D模型) b3dm瓦片存储了多个个体&#xff0c;b3dm中的glb代表的实际对象应该具有相同的种类但是可能数据内容不同。b3dm…

ROS摄像机标定

文章目录 一、环境准备二、摄像头标定2.1 为什么要标定2.2 标定前准备2.2.1 标定板2.2.2 摄像头调焦 2.3 开始标定2.4 测试标定结果 总结参考资料 一、环境准备 安装usb_cam相机驱动 sudo apt-get install ros-noetic-usb-cam 安装标定功能包 sudo apt-get install ros-noet…
最新文章