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

本文详细介绍了PyTorch中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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zyw2002

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值