当前位置:网站首页>PyTorch笔记——通过搭建ResNet熟悉网络搭建方式(完整代码)
PyTorch笔记——通过搭建ResNet熟悉网络搭建方式(完整代码)
2022-04-23 05:44:00 【umbrellalalalala】
参考资料:《深度学习框架PyTorch:入门与实践》
注意:书籍作者表示要注意编程简洁,所以本文的网络搭建方式是可以借鉴的。
完整代码
部分讲解见注释:
from torch import nn
import torch as t
from torch.nn import functional as F
# 实现子module:Residual Block
class ResidualBlock(nn.Module):
def __init__(self, inchannel, outchannel, stride=1, shortcut=None):
super().__init__()
self.left = nn.Sequential(
# padding=1指的是上下左右各补一行,如果是padding=(1, 1)则是
# 上下各补一行、左右各补一行(先高后宽)
nn.Conv2d(inchannel, outchannel, 3, stride, 1, bias=False),
nn.BatchNorm2d(outchannel),
# inplace=True是指原地操作,直接修改上层传递下来的tensor,节省内存
nn.ReLU(inplace=True),
nn.Conv2d(outchannel, outchannel, 3, 1, 1, bias=False),
nn.BatchNorm2d(outchannel))
self.right = shortcut
def forward(self, x):
out = self.left(x)
residual = x if self.right is None else self.right(x)
out += residual
return F.relu(out)
class ResNet(nn.Module):
def __init__(self, num_classes=1000):
super().__init__()
self.pre = nn.Sequential(
nn.Conv2d(3, 64, 7, 2, 3, bias=False),
nn.BatchNorm2d(64),
nn.ReLU(inplace=True),
# kernel_size, stride, padding
nn.MaxPool2d(3, 2, 1))
self.layer1 = self._make_layer(64, 128, 3)
self.layer2 = self._make_layer(128, 256, 4, stride=2)
self.layer3 = self._make_layer(256, 512, 6, stride=2)
self.layer4 = self._make_layer(512, 512, 3, stride=2)
self.fc = nn.Linear(512, num_classes)
def _make_layer(self, inchannel, outchannel, block_num, stride=1):
shortcut = nn.Sequential(
nn.Conv2d(inchannel, outchannel, 1, stride, bias=False),
nn.BatchNorm2d(outchannel))
layers = []
# 第一个把inchannel变成outchannel
layers.append(ResidualBlock(inchannel, outchannel, stride, shortcut))
for i in range(1, block_num):
layers.append(ResidualBlock(outchannel, outchannel))
# list a=[1,2,3],那么*a就是指1 2 3
return nn.Sequential(*layers)
def forward(self, x):
x = self.pre(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
x = F.avg_pool2d(x, 7)
# 变为[batch, ...]
x = x.view(x.size(0), -1)
return self.fc(x)
测试前向传播
model = ResNet()
# 模拟224×224的图片,通道为3。开头的1是batch_size
input = t.randn(1, 3, 224, 224)
o = model(input)
o.shape
输出结果:
torch.Size([1, 1000])
对应分类问题的1000个类别。
版权声明
本文为[umbrellalalalala]所创,转载请带上原文链接,感谢
https://blog.csdn.net/umbrellalalalala/article/details/119981166
边栏推荐
- RedHat realizes keyword search in specific text types under the directory and keyword search under VIM mode
- POI exports to excel, and the same row of data is automatically merged into cells
- 你不能访问此共享文件夹,因为你组织的安全策略阻止未经身份验证的来宾访问
- Ptorch learning record (XIII): recurrent neural network
- PyQy5学习(三):QLineEdit+QTextEdit
- Solution record of slow access speed of SMB service in redhat6
- 实操—Nacos安装与配置
- 自定义异常类
- 图解HashCode存在的意义
- lambda表达式
猜你喜欢
2 - principes de conception de logiciels
Multithreading and high concurrency (2) -- detailed explanation of synchronized usage
Font shape `OMX/cmex/m/n‘ in size <10.53937> not available (Font) size <10.95> substituted.
Conda 虚拟环境管理(创建、删除、克隆、重命名、导出和导入)
字符串(String)笔记
开发环境 EAS登录 license 许可修改
Pytoch learning record (x): data preprocessing + batch normalization (BN)
一文读懂当前常用的加密技术体系(对称、非对称、信息摘要、数字签名、数字证书、公钥体系)
MySQL realizes master-slave replication / master-slave synchronization
JVM family (4) -- memory overflow (OOM)
随机推荐
Pytorch learning record (IV): parameter initialization
实操—Nacos安装与配置
Software architecture design - software architecture style
Font shape `OMX/cmex/m/n‘ in size <10.53937> not available (Font) size <10.95> substituted.
多线程与高并发(1)——线程的基本知识(实现,常用方法,状态)
Latex快速入门
Object to map
Pytorch learning record (XI): data enhancement, torchvision Explanation of various functions of transforms
容器
Common status codes
Anaconda
图像恢复论文简记——Uformer: A General U-Shaped Transformer for Image Restoration
Understand the current commonly used encryption technology system (symmetric, asymmetric, information abstract, digital signature, digital certificate, public key system)
框架解析1.系统架构简介
mysql-触发器、存储过程、存储函数
JVM系列(4)——内存溢出(OOM)
Pytorch——数据加载和处理
Treatment of tensorflow sequelae - simple example record torch utils. data. dataset. Picture dimension problem when rewriting dataset
rsync实现文件服务器备份
Getting started with JDBC \ getting a database connection \ using Preparedstatement