顺序¶
- class torch.nn.Sequential(*args: Module)[source]¶
- class 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()) ]))