torch.nn.Sequential 类是 torch.nn 中的一种序列容器(嵌套有各种→实现神经网络具体功能),最主要的是,参数会按照我们定义好的序列自动传递下去。

将嵌套在容器中的各个部分看作各种不同的模块(可以自由组合),模块的加入有以下两种方式:

1、直接嵌套
hidden_layer = 100 
input_data = 1000 
output_data = 10 

models = torch.nn.Sequential( 
 torch.nn.Linear(input_data, hidden_layer), 
 torch.nn.ReLU(), 
 torch.nn.Linear(hidden_layer, output_data) 
) 

print(models)
Sequential(
  (0): Linear(in_features=1000, out_features=100, bias=True)
  (1): ReLU()
  (2): Linear(in_features=100, out_features=10, bias=True)
)
2、以 orderdict 有序字典的方式进行传入
hidden_layer = 100 
input_data = 1000 
output_data = 10

from collections import OrderedDict
models = torch.nn.Sequential(OrderedDict([
    ("Line1", torch.nn.Linear(input_data, hidden_layer)),
    ("Relul", torch.nn.ReLU()),
    ("Line2", torch.nn.Linear(hidden_layer, output_data))
])
)

print(models)
Sequential(
  (Line1): Linear(in_features=1000, out_features=100, bias=True)
  (Relul): ReLU()
  (Line2): Linear(in_features=100, out_features=10, bias=True)
)

从上面两个例子可以看出来:这两种方式的唯一区别是,使用后者搭建的模型的每个模块都有我们自定义的名字,而前者默认使用从零开始的数字序列作为每个模块的名字。
对模块使用自定义的名称可让我们更便捷地找到模型中相应的模块并进行操作。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐