当前位置:网站首页>pytorch学习之nn.Sequential类—使用Sequential类来自定义顺序连接模型
pytorch学习之nn.Sequential类—使用Sequential类来自定义顺序连接模型
2022-07-21 10:04:00 【wzw12315】
前言:类似于keras中的序贯模型,当模型较简单的时候,可以使用torch.nn.Sequential类来实现简单的顺序连接模型。Sequential类是继承自Module类的
Sequential类的定义:
class Sequential(Module): # 继承Module
def __init__(self, *args): # 重写了构造函数
def _get_item_by_idx(self, iterator, idx):
def __getitem__(self, idx):
def __setitem__(self, idx, module):
def __delitem__(self, idx):
def __len__(self):
def __dir__(self):
def forward(self, input): # 重写关键方法forward
Sequential类不同的实现(3种实现)
实现一:
import torch.nn as nn
model = nn.Sequential(
nn.Conv2d(in_channels=1,out_channels=32,kernel_size=3),
nn.ReLU(),
nn.Conv2d(in_channels=32,out_channels=64,kernel_size=3),
nn.ReLU()
)
print("运行结果为:")
print(model)
print(model[0])
'''
运行结果为:
Sequential(
(0): Conv2d(1, 32, kernel_size=(3, 3), stride=(1, 1))
(1): ReLU()
(2): Conv2d(32, 64, kernel_size=(3, 3), stride=(1, 1))
(3): ReLU()
)
Conv2d(1, 32, kernel_size=(3, 3), stride=(1, 1))
'''
注意:上面实现上存在一个问题,每一个层是没有名称,默认的是以0、1、2、3来命名,从上面的运行结果也可以看出。
实现二:
import torch.nn as nn
from collections import OrderedDict
model = nn.Sequential(OrderedDict([
('conv1', nn.Conv2d(in_channels=1,out_channels=32,kernel_size=3)),
('relu1', nn.ReLU()),
('conv2', nn.Conv2d(in_channels=32,out_channels=64,kernel_size=3)),
('relu2', nn.ReLU())])
)
print("运行结果为:")
print(model)
print(model[2])
'''
运行结果为:
Sequential(
(conv1): Conv2d(1, 32, kernel_size=(3, 3), stride=(1, 1))
(relu1): ReLU()
(conv2): Conv2d(32, 64, kernel_size=(3, 3), stride=(1, 1))
(relu2): ReLU()
)
Conv2d(32, 64, kernel_size=(3, 3), stride=(1, 1))
'''
注意:从结果中可以看出,虽然每一个层都有了自己的名称,但是并不能够通过名称直接获取层,依然只能通过索引index,即
model[2] 是正确的
model["conv2"] 是错误的
这其实是由它的定义实现的,看上面的Sequenrial定义可知,只支持index访问。
实现三:
import torch.nn as nn
model = nn.Sequential()
model.add_module('conv1', nn.Conv2d(in_channels=1,out_channels=32,kernel_size=3))
model.add_module('relu1', nn.ReLU())
model.add_module('conv2', nn.Conv2d(in_channels=32,out_channels=64,kernel_size=3))
model.add_module('relu2', nn.ReLU())
print("运行结果为:")
print(model)
print(model[2])
'''
运行结果为:
Sequential(
(conv1): Conv2d(1, 32, kernel_size=(3, 3), stride=(1, 1))
(relu1): ReLU()
(conv2): Conv2d(32, 64, kernel_size=(3, 3), stride=(1, 1))
(relu2): ReLU()
)
Conv2d(32, 64, kernel_size=(3, 3), stride=(1, 1))
'''
实现三与keras做法类似,实际上Sequential类并没有定义add_module()方法,实际上这个方法是定义在它的父类Module,Sequential继承而来。
边栏推荐
- Raspberry pie 3B builds Flink cluster
- Construction practice of pipeline engine of engineering efficiency ci/cd
- 辛丑年之万家灯火
- 力扣 1260. 二维网格迁移
- 请教个问题,按照快速上手的来,flink SQL 建表后查询,出来表结构,但是有个超时报错,怎么办?
- Why does a very simple function crash
- Leetcode 104. 二叉树的最大深度
- 个性潮流与性能兼备,华硕a豆14 Pro搭载全新12代酷睿标压处理器
- 871. 约数之和
- three hundred and thirteen billion one hundred and thirty-one million three hundred and thirteen thousand one hundred and twenty-three
猜你喜欢
Network address translation (NAT)
工程效能CI/CD之流水线引擎的建设实践
阿里云技术专家杨泽强:弹性计算云上可观测能力构建
SVD singular value decomposition matrix compression
hi和hello两个请求引发的@RequestBody思考
别乱用UUID了,自增ID和UUID性能差距你测试过吗?
我,AI博士生,在线众筹研究主题
In the cloud native era, developers should have these five capabilities
Kuberntes cloud native combat high availability deployment architecture
Leetcode 104. 二叉树的最大深度
随机推荐
leetcode:169. Most elements
MySQL performance optimization (I): MySQL architecture and core issues
How airbnb realizes dynamic expansion of kubernetes cluster
Six ways for JS to implement inheritance
Read / write operation of trust file
Perfect + today's headline written test questions + summary of knowledge points
个性潮流与性能兼备,华硕a豆14 Pro搭载全新12代酷睿标压处理器
Did someone cut someone with a knife on Shanghai Metro Line 9? Rail transit public security: safety drill
Yunyuanyuan (IX) | Devops chapter Jenkins installation and actual combat
MySQL. Pas de fichier ou de répertoire
Codeforces Round #578 (Div. 2) B - Block Adventure 【贪心】
Number of pairs (dynamic open point)
调用百度AI开放平台实现图片文字识别
辛丑年之万家灯火
[sklearn] data set split sklearn moduel_ selection. train_ test_ split
Layer 3 switching and VRRP
871. 约数之和
请教个问题 有没有用cdc监控oracle遇到Error Msg = ORA-04036: 实例使用
写个批处理,启动redis
辛丑年之立冬