参考:官方文档    源码

官方文档

nn.Sequential

  A sequential container. Modules will be added to it in the order they are passed in the constructor. Alternatively, an ordered dict of modules can also be passed in.

  翻译:一个有序的容器,神经网络模块将按照在传入构造器的顺序依次被添加到计算图中执行,同时以神经网络模块为元素的有序字典也可以作为传入参数。

使用方法一:作为一个有顺序的容器

  作为一个有顺序的容器,将特定神经网络模块按照在传入构造器的顺序依次被添加到计算图中执行。

官方 Example:

model = nn.Sequential(
nn.Conv2d(1,20,5),
nn.ReLU(),
nn.Conv2d(20,64,5),
nn.ReLU()
)
# When `model` is run,input will first be passed to `Conv2d(1,20,5)`.
# The output of `Conv2d(1,20,5)` will be used as the input to the first `ReLU`;
# the output of the first `ReLU` will become the input for `Conv2d(20,64,5)`.
# Finally, the output of `Conv2d(20,64,5)` will be used as input to the second `ReLU`

例子:

net = nn.Sequential(
nn.Linear(num_inputs, num_hidden)
# 传入其他层
)

使用方法二:作为一个有序字典

  将以特定神经网络模块为元素的有序字典(OrderedDict)为参数传入。

官方 Example :

model = nn.Sequential(OrderedDict([
('conv1', nn.Conv2d(1,20,5)),
('relu1', nn.ReLU()),
('conv2', nn.Conv2d(20,64,5)),
('relu2', nn.ReLU())
]))

例子:

net = nn.Sequential()
net.add_module('linear1', nn.Linear(num_inputs, num_hiddens))
net.add_module('linear2', nn.Linear(num_hiddens, num_ouputs))
# net.add_module ......

源码分析

初始化函数 init

    def __init__(self, *args):
super(Sequential, self).__init__()
if len(args) == 1 and isinstance(args[0], OrderedDict):
for key, module in args[0].items():
self.add_module(key, module)
else:
for idx, module in enumerate(args):
self.add_module(str(idx), module)

  __init__ 首先使用 if 条件进行判断,若传入的参数为 1 个,且类型为 OrderedDict,则通过字典索引的方式利用 add_module 函数 将子模块添加到现有模块中。否则,通过 for 循环遍历参数,将所有的子模块添加到现有模块中。 这里需要注意,Sequential 模块的初始换函数没有异常处理。

forward 函数

    def forward(self, input):
for module in self:
input = module(input)
return input

  因为每一个 module 都继承于 nn.Module,都会实现 __call__ 与 forward 函数,所以 forward 函数中通过 for 循环依次调用添加到 self._module 中的子模块,最后输出经过所有神经网络层的结果。

Pytorch——torch.nn.Sequential()详解的更多相关文章

  1. torch.nn.Sequential()详解

    参考:官方文档    源码 官方文档 nn.Sequential A sequential container. Modules will be added to it in the order th ...

  2. pytorch之nn.Conv1d详解

    转自:https://blog.csdn.net/sunny_xsc1994/article/details/82969867,感谢分享 pytorch之nn.Conv1d详解

  3. PyTorch : torch.nn.xxx 和 torch.nn.functional.xxx

    PyTorch : torch.nn.xxx 和 torch.nn.functional.xxx 在写 PyTorch 代码时,我们会发现一些功能重复的操作,比如卷积.激活.池化等操作.这些操作分别可 ...

  4. 【小白学PyTorch】11 MobileNet详解及PyTorch实现

    文章来自微信公众号[机器学习炼丹术].我是炼丹兄,欢迎加我微信好友交流学习:cyx645016617. @ 目录 1 背景 2 深度可分离卷积 2.2 一般卷积计算量 2.2 深度可分离卷积计算量 2 ...

  5. 【小白学PyTorch】12 SENet详解及PyTorch实现

    文章来自微信公众号[机器学习炼丹术].我是炼丹兄,有什么问题都可以来找我交流,近期建立了微信交流群,也在朋友圈抽奖赠书十多本了.我的微信是cyx645016617,欢迎各位朋友. 参考目录: @ 目录 ...

  6. Pytorch里的CrossEntropyLoss详解

    在使用Pytorch时经常碰见这些函数cross_entropy,CrossEntropyLoss, log_softmax, softmax.看得我头大,所以整理本文以备日后查阅. 首先要知道上面提 ...

  7. pytorch torch.nn.functional实现插值和上采样

    interpolate torch.nn.functional.interpolate(input, size=None, scale_factor=None, mode='nearest', ali ...

  8. pytorch torch.nn 实现上采样——nn.Upsample

    Vision layers 1)Upsample CLASS torch.nn.Upsample(size=None, scale_factor=None, mode='nearest', align ...

  9. Pytorch Bi-LSTM + CRF 代码详解

    久闻LSTM + CRF的效果强大,最近在看Pytorch官网文档的时候,看到了这段代码,前前后后查了很多资料,终于把代码弄懂了.我希望在后来人看这段代码的时候,直接就看我的博客就能完全弄懂这段代码. ...

随机推荐

  1. Spring源码浅析之bean实例的创建过程(二)

    在上一篇内容中,介绍了doGetBean方法的源码内容,知道了bean在创建的过程中,有三个范围,单例.多例.Scope,里面都使用到了createBean.下面本篇文章的主要内容,就是围绕creat ...

  2. 堆栈相关的经典题(c++)

    1.定义队列 typedef struct node{ int data; struct node * next; }Node; typedef struct linkQueue { Node * f ...

  3. 问题:idea 中文无法使用

    1. 问题--idea无法使用中文输入 原因:idea本身版本过高,所以需要你强制减低它的jdk版本 解决:使用配置idea环境变量解决  ps:目前适用于任何版本的jdk和idea 步骤: 1.新建 ...

  4. 【算法】使用Golang实现加权负载均衡算法

    背景描述 如下图所示,负载均衡做为反向代理,将请求方的请求转发至后端的服务节点,实现服务的请求. 在nginx中可以通过upstream配置server时,设置weight表示对应server的权重. ...

  5. UNION / UNION ALL 区别

    Union:对两个结果集进行并集操作,不包括重复行,同时进行默认规则的排序: Union All:对两个结果集进行并集操作,包括重复行,不进行排序: 使用union all: select top 5 ...

  6. Python - 面向对象编程 - __repr__()

    为什么要讲 __repr__ 在 Python 中,直接 print 一个实例对象,默认是输出这个对象由哪个类创建的对象,以及在内存中的地址(十六进制表示) 假设在开发调试过程中,希望使用 print ...

  7. Spring Dependency Injection浅析

    Dependency Injection 依赖注入,在Spring框架负责创建Bean对象时,动态的将依赖对象注入到Bean组件. 1.在UserService中提供一个get/set的name方法, ...

  8. C# 动态构建表达式树(一)—— 构建 Where 的 Lambda 表达式

    C# 动态构建表达式树(一)-- 构建 Where 的 Lambda 表达式 前言 记得之前同事在做筛选功能的时候提出过一个问题:如果用户传入的条件数量不确定,条件的内容也不确定(大于.小于和等于), ...

  9. R和Rstudio的安装

    首先是安装R再安装Rstudio 链接放在这里: R语言软件以及Rstudio软件下载:链接:https://pan.baidu.com/s/11TH4mJjoi3QXGfamB697rw 密码:o1 ...

  10. 手把手教你 Docker搭建nacos单机版

    Docker搭建nacos单机版步骤 一.使用 docker pull nacos/nacos-server 拉取nacos镜像 我这里没有指定版本所以是拉取latest,你也可以使用 docker ...