顺序
- 类torch.nn.Sequential(*args: Module)[源代码]
- 类torch.nn.Sequential(arg: OrderedDict[str, Module])
-
一个有序容器。
模块将以它们在构造函数中传递的顺序被添加到容器中。或者,可以传入一个包含这些模块的
OrderedDict
。Sequential
的forward()
方法接受任何输入,并将其传递给第一个模块。然后依次将每个后续模块的输出作为下一个模块的输入,最后返回最后一个模块的输出。使用
Sequential
的好处是,它可以将整个容器视为一个单一的模块。这样,对Sequential
进行的操作会自动应用于它存储的所有模块(这些模块都是Sequential
中注册的子模块)。什么是
Sequential
和torch.nn.ModuleList
之间的区别?一个ModuleList
就像它的名字一样,是一个用于存储Module
的列表。另一方面,在Sequential
中的层是级联连接的。示例:
# Using Sequential to create a small model. 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` model = nn.Sequential( nn.Conv2d(1,20,5), nn.ReLU(), nn.Conv2d(20,64,5), nn.ReLU() ) # Using Sequential with OrderedDict. This is functionally the # same as the above code model = nn.Sequential(OrderedDict([ ('conv1', nn.Conv2d(1,20,5)), ('relu1', nn.ReLU()), ('conv2', nn.Conv2d(20,64,5)), ('relu2', nn.ReLU()) ]))