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

这篇具有很好参考价值的文章主要介绍了【torch.nn.Sequential】序列容器的介绍和使用。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

torch.nn.Sequential

简单介绍

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

因此,Sequential可以看成是有多个函数运算对象,串联成的神经网络,其返回的是Module类型的神经网络对象。
torch.nn.sequential,深度学习框架,python,深度学习,人工智能

构建实例

参数列表

  • 以参数列表的方式来实例化
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文章来源地址https://www.toymoban.com/news/detail-759916.html

到了这里,关于【torch.nn.Sequential】序列容器的介绍和使用的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • pytorch nn.ModuleList和nn.Sequential的用法笔记

    有部分内容转自: pytorch小记:nn.ModuleList和nn.Sequential的用法以及区别_慕思侣的博客-CSDN博客 但是有部分内容做了修改调整, 在构建网络的时候,pytorch有一些基础概念很重要,比如nn.Module,nn.ModuleList,nn.Sequential,这些类我们称为为容器(containers),可参考containers。本文中

    2024年02月13日
    浏览(26)
  • Pytorch深度学习-----神经网络之Sequential的详细使用及实战详解

    PyTorch深度学习——Anaconda和PyTorch安装 Pytorch深度学习-----数据模块Dataset类 Pytorch深度学习------TensorBoard的使用 Pytorch深度学习------Torchvision中Transforms的使用(ToTensor,Normalize,Resize ,Compose,RandomCrop) Pytorch深度学习------torchvision中dataset数据集的使用(CIFAR10) Pytorch深度学习--

    2024年02月14日
    浏览(29)
  • 深度学习之pytorch 中 torch.nn介绍

    pytorch 中必用的包就是 torch.nn,torch.nn 中按照功能分,主要如下有几类: 1. Layers(层):包括全连接层、卷积层、池化层等。 2. Activation Functions(激活函数):包括ReLU、Sigmoid、Tanh等。 3. Loss Functions(损失函数):包括交叉熵损失、均方误差等。 4. Optimizers(优化器):包括

    2024年02月22日
    浏览(34)
  • 搭建小实战和Sequential的使用

    以CIFAR 10 model结构为例搭建网络 CIFAR 10 model结构 torch.nn.Flatten 是PyTorch中的一个模块,用于将多维的输入张量转换为一维的输出张量。它可以被用作神经网络模型中的一层,用于将输入张量展平后作为全连接层的输入。比如输入张量的形状是 [10, 3, 32, 32] ,即批大小为 10,通道

    2024年02月12日
    浏览(23)
  • 学习pytorch13 神经网络-搭建小实战&Sequential的使用

    B站小土堆pytorch视频学习 https://pytorch.org/docs/stable/generated/torch.nn.Sequential.html#torch.nn.Sequential sequential 将模型结构组合起来 以逗号分割,按顺序执行,和compose使用方式类似。 箭头指向部分还需要一层flatten层,展开输入shape为一维 tensorboard 展示图文件, 双击每层网络,可查看层

    2024年02月07日
    浏览(29)
  • PyTorch入门学习(十二):神经网络-搭建小实战和Sequential的使用

    目录 一、介绍 二、先决条件 三、代码解释 一、介绍 在深度学习领域,构建复杂的神经网络模型可能是一项艰巨的任务,尤其是当您有许多层和操作需要组织时。幸运的是,PyTorch提供了一个方便的工具,称为Sequential API,它简化了神经网络架构的构建过程。在本文中,将探

    2024年02月05日
    浏览(31)
  • 【机器学习】P14 Tensorflow 使用指南 Dense Sequential Tensorflow 实现

    有关 Tensorflow/CUDA/cuDNN 安装,见博客:https://xu-hongduo.blog.csdn.net/article/details/129927665 上图中包含输入层、隐藏层、输出层; 其中输入层为 layer 0 ,输入到网络中的内容为 x ⃗ vec{x} x ; 其中隐藏层有三层, layer 1 , layer 2 , layer 3 ; 其中输出层为 layer 4 ,输出内容为 a ⃗ [

    2023年04月09日
    浏览(29)
  • 机器学习&&深度学习——torch.nn模块

    torch.nn模块包含着torch已经准备好的层,方便使用者调用构建网络。 卷积就是 输入和卷积核之间的内积运算 ,如下图: 容易发现,卷积神经网络中通过输入卷积核来进行卷积操作,使输入单元(图像或特征映射)和输出单元(特征映射)之间的连接时稀疏的,能够减少需要

    2024年02月15日
    浏览(27)
  • 【LangChain】顺序(Sequential)

    基础 【LangChain】LLM 【LangChain】路由(Router) 【LangChain】顺序(Sequential) 我们调用语言模型后的下一步,一般都是对语言模型进行一系列调用。也就是我们想要获取一个调用的输出并将其用作另一个调用的输入。 在本笔记本中,我们将通过一些示例来说明如何使用顺序链来执行此

    2024年02月13日
    浏览(36)
  • Circuits--Sequential--Registers_1

    1.4-bit shift register 2.Left/right rotator 3.Left / right arithmetic  4.5-bit LFSR

    2024年04月17日
    浏览(19)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包