文章目录

  • torch.nn.Sequential
    • 简单介绍
    • 构建实例
      • 参数列表
      • 字典
    • 基本操作
    • 参考

torch.nn.Sequential

简单介绍

nn.Sequential是一个有序的容器,该类将按照传入构造器的顺序,依次创建相应的函数,并记录在Sequential类对象的数据结构中,同时以神经网络模块为元素的有序字典也可以作为传入参数。

因此,Sequential可以看成是有多个函数运算对象,串联成的神经网络,其返回的是Module类型的神经网络对象。

构建实例

参数列表

  • 以参数列表的方式来实例化
print("利用系统提供的神经网络模型类:Sequential,以参数列表的方式来实例化神经网络模型对象")
# A sequential container. Modules will be added to it in the order they are passed in the constructor.
# Example of using Sequential
model_c = nn.Sequential(nn.Linear(28*28, 32), nn.ReLU(), nn.Linear(32, 10), nn.Softmax(dim=1))
print(model_c)print("\n显示网络模型参数")
print(model_c.parameters)print("\n定义神经网络样本输入")
x_input = torch.randn(2, 28, 28, 1)
print(x_input.shape)print("\n使用神经网络进行预测")
y_pred = model.forward(x_input.view(x_input.size()[0],-1))
print(y_pred)
利用系统提供的神经网络模型类:Sequential,以参数列表的方式来实例化神经网络模型对象
Sequential((0): Linear(in_features=784, out_features=32, bias=True)(1): ReLU()(2): Linear(in_features=32, out_features=10, bias=True)(3): Softmax(dim=1)
)显示网络模型参数
<bound method Module.parameters of Sequential((0): Linear(in_features=784, out_features=32, bias=True)(1): ReLU()(2): Linear(in_features=32, out_features=10, bias=True)(3): Softmax(dim=1)
)>定义神经网络样本输入
torch.Size([2, 28, 28, 1])使用神经网络进行预测
tensor([[-0.1526,  0.0437, -0.1685,  0.0034, -0.0675,  0.0423,  0.2807,  0.0527,-0.1710,  0.0668],[-0.1820,  0.0860,  0.0174,  0.0883,  0.2046, -0.1609,  0.0165, -0.2392,-0.2348,  0.1697]], grad_fn=<AddmmBackward>)

字典

  • 以字典的方式实例化
# Example of using Sequential with OrderedDict
print("利用系统提供的神经网络模型类:Sequential,以字典的方式来实例化神经网络模型对象")
model = nn.Sequential(OrderedDict([('h1', nn.Linear(28*28, 32)),('relu1', nn.ReLU()),('out', nn.Linear(32, 10)),('softmax', nn.Softmax(dim=1))]))print(model)print("\n显示网络模型参数")
print(model.parameters)print("\n定义神经网络样本输入")
x_input = torch.randn(2, 28, 28, 1)
print(x_input.shape)print("\n使用神经网络进行预测")
y_pred = model.forward(x_input.view(x_input.size()[0],-1))
print(y_pred)
利用系统提供的神经网络模型类:Sequential,以字典的方式来实例化神经网络模型对象
Sequential((h1): Linear(in_features=784, out_features=32, bias=True)(relu1): ReLU()(out): Linear(in_features=32, out_features=10, bias=True)(softmax): Softmax(dim=1)
)显示网络模型参数
<bound method Module.parameters of Sequential((h1): Linear(in_features=784, out_features=32, bias=True)(relu1): ReLU()(out): Linear(in_features=32, out_features=10, bias=True)(softmax): Softmax(dim=1)
)>定义神经网络样本输入
torch.Size([2, 28, 28, 1])使用神经网络进行预测
tensor([[0.1249, 0.1414, 0.0708, 0.1031, 0.1080, 0.1351, 0.0859, 0.0947, 0.0753,0.0607],[0.0982, 0.1102, 0.0929, 0.0855, 0.0848, 0.1076, 0.1077, 0.0949, 0.1153,0.1029]], grad_fn=<SoftmaxBackward>)

基本操作

  • 查看结构

通过打印 Sequential对象来查看它的结构

print(net)
# Sequential(
#   (0): Linear(in_features=20, out_features=10, bias=True)
#   (1): ReLU()
#   (2): Linear(in_features=10, out_features=5, bias=True)
# )
  • 索引

我们可以使用索引来查看其子模块

print(net[0])
# Linear(in_features=20, out_features=10, bias=True)
print(net[1])
# ReLU()
  • 长度
print(len(net))
# 3
  • 修改子模块
net[1] = nn.Sigmoid()
print(net)
# Sequential(
#   (0): Linear(in_features=20, out_features=10, bias=True)
#   (1): Sigmoid()
#   (2): Linear(in_features=10, out_features=5, bias=True)
# )
  • 删除子模块
del net[2]
print(net)
# Sequential(
#   (0): Linear(in_features=20, out_features=10, bias=True)
#   (1): Sigmoid()
# )
  • 添加子模块
net.append(nn.Linear(10, 2))  # 均会添加到末尾
print(net)
# Sequential(
#   (0): Linear(in_features=20, out_features=10, bias=True)
#   (1): Sigmoid()
#   (2): Linear(in_features=10, out_features=2, bias=True)
# )
  • 遍历
net = nn.Sequential(nn.Linear(20, 10),nn.ReLU(),nn.Linear(10, 5)
)for sub_module in net:print(sub_module)
# Linear(in_features=20, out_features=10, bias=True)
# ReLU()
# Linear(in_features=10, out_features=5, bias=True)
  • 嵌套
'''在一个 Sequential 中嵌套两个 Sequential'''
seq_1 = nn.Sequential(nn.Linear(15, 10), nn.ReLU(), nn.Linear(10, 5))
seq_2 = nn.Sequential(nn.Linear(25, 15), nn.Sigmoid(), nn.Linear(15, 10))
seq_3 = nn.Sequential(seq_1, seq_2)
print(seq_3)
# Sequential(
#   (0): Sequential(
#     (0): Linear(in_features=15, out_features=10, bias=True)
#     (1): ReLU()
#     (2): Linear(in_features=10, out_features=5, bias=True)
#   )
#   (1): Sequential(
#     (0): Linear(in_features=25, out_features=15, bias=True)
#     (1): Sigmoid()
#     (2): Linear(in_features=15, out_features=10, bias=True)
#   )
# )
''''使用多级索引进行访问'''
print(seq_3[1])
# Sequential(
#   (0): Linear(in_features=25, out_features=15, bias=True)
#   (1): Sigmoid()
#   (2): Linear(in_features=15, out_features=10, bias=True)
# )
print(seq_3[0][1])
# ReLU()
'''使用双重循环进行遍历'''
for seq in seq_3:for module in seq:print(module)
# Linear(in_features=15, out_features=10, bias=True)
# ReLU()
# Linear(in_features=10, out_features=5, bias=True)
# Linear(in_features=25, out_features=15, bias=True)
# Sigmoid()
# Linear(in_features=15, out_features=10, bias=True)

参考

PyTorch学习笔记(六)–Sequential类、参数管理与GPU_Lareges的博客-CSDN博客_sequential类

[Pytorch系列-30]:神经网络基础 - torch.nn库五大基本功能:nn.Parameter、nn.Linear、nn.functioinal、nn.Module、nn.Sequentia_文火冰糖的硅基工坊的博客-CSDN博客_torch库nn

【torch.nn.Sequential】序列容器的介绍和使用相关推荐

  1. 【深度学习】torch.nn.Sequential方法介绍

    torch.nn.Sequential是一个Sequential容器,模块将按照构造函数中传递的顺序添加到模块中. 另外,也可以传入一个有序模块. 作用:Sequential除了本身可以用来定义模型之 ...

  2. PyTorch 笔记(16)— torch.nn.Sequential、torch.nn.Linear、torch.nn.RelU

    PyTorch 中的 torch.nn 包提供了很多与实现神经网络中的具体功能相关的类,这些类涵盖了深度神经网络模型在搭建和参数优化过程中的常用内容,比如神经网络中的卷积层.池化层.全连接层这类层次构 ...

  3. pytorch torch.nn.Sequential(* args)(嘎哈用的?构建神经网络用的?)

    class torch.nn.Sequential(* args) 一个时序容器.Modules 会以他们传入的顺序被添加到容器中.当然,也可以传入一个OrderedDict. 为了更容易的理解如何使 ...

  4. pytorch使用torch.nn.Sequential构建网络

    以一个线性回归的例子为例: 全部代码 import torch import numpy as npdef get_x_y():x = np.random.randint(0, 50, 300)y_v ...

  5. nn.Module、nn.Sequential和torch.nn.parameter学习笔记

    nn.Module.nn.Sequential和torch.nn.parameter是利用pytorch构建神经网络最重要的三个函数.搞清他们的具体用法是学习pytorch的必经之路. 目录 nn.M ...

  6. 深度之眼 PyTorch 训练营第 4 期(5):构建模型 torch.nn.Module

    本文中,我们看一看如何构建模型. 创造一个模型分两步:构建模型和权值初始化.而构建模型又有"定义单独的网络层"和"把它们拼在一起"两步. 1. torch.nn ...

  7. [Pytorch系列-28]:神经网络基础 - torch.nn模块功能列表

    作者主页(文火冰糖的硅基工坊):文火冰糖(王文兵)的博客_文火冰糖的硅基工坊_CSDN博客 本文网址:https://blog.csdn.net/HiWangWenBing/article/detai ...

  8. PyTorch学习笔记(1)nn.Sequential、nn.Conv2d、nn.BatchNorm2d、nn.ReLU和nn.MaxPool2d

    文章目录 一.nn.Sequential 二.nn.Conv2d 三.nn.BatchNorm2d 四.nn.ReLU 五.nn.MaxPool2d 一.nn.Sequential torch.nn. ...

  9. pytorch_lesson13.4 Dead ReLU Problem成因分析+通过调整学习率来缓解+Relu特性理解+nn.Sequential建模方式以及参数自定义方法

    提示:仅仅是学习记录笔记,搬运了学习课程的ppt内容,本意不是抄袭!望大家不要误解!纯属学习记录笔记!!!!!! 文章目录 前言 一.Dead ReLU Problem成因分析 1.Dead ReLU ...

最新文章

  1. MySQL数据库将查询结果插入到其它表中
  2. stm32如何执行软复位_常见的单片机复位方式及其原理分析
  3. python画直方图成绩分析-使用Python绘制直方图和正态分布曲线
  4. 使用nginx做反向代理和负载均衡效果图
  5. 华为2011上机笔试题2+参考程序
  6. 云原生体系下 Serverless 弹性探索与实践
  7. 机器学习中的参数调整
  8. Bash脚本教程之命令提示符
  9. 工作失职的处理决定_工作失职的处理决定
  10. if判断用户名 linux,Shell脚本IF条件判断和判断条件总结
  11. micropython是什么意思_MicroPython到底是啥-百度经验
  12. mysql server启动_mysql的启动方式
  13. tensorflow GPU版本配置加速环境
  14. axios传递数据到java_axios 传输与springboot后台接收数据
  15. Java 2实用教程(第5版)实验指导与习题解答 第3章-上机实践-分支与循环语句
  16. linux内存占用率高怎么办,Linux下如何解决高内存使用率问题?
  17. 百度网盘直链下载助手(MacOSChrome)
  18. js 手机号码和电话号码(座机号)正则校验
  19. 计算机论文结束语致谢,毕业论文致谢结束语3篇
  20. 与编程密切相关的数学——离散数学——代数系统篇

热门文章

  1. 阿里云服务器公网带宽价格表2023更新了
  2. Android 动态壁纸(Live Wallpaper)编写注意事项小记
  3. 43、几种线性表的介绍及实现
  4. java sleep 失效_java:Thread.sleep()导致同步失效
  5. UltraISO Premium Edition v9.5.2.2836注册码
  6. 谭松波酒店评价情感分析代码以及数据集获取
  7. linux sublime中文输入法,完美解决 Linux 下 Sublime Text 中文输入
  8. BZOJ 4883 [Lydsy2017年5月月赛]棋盘上的守卫(最小生成环套树森林)
  9. 我计算机专业哪个大学枪,11个专业大学期末考试酸爽排行榜!你的专业中枪没?...
  10. HCL Technologies庆祝在澳大利亚和新西兰市场创新20年