评价此页

Sequential#

class torch.nn.Sequential(*args: Module)[来源]#
class torch.nn.Sequential(arg: OrderedDict[str, Module])

一个顺序容器。

模块将按照它们在构造函数中传递的顺序被添加到容器中。或者,也可以传入一个模块的 OrderedDictSequentialforward() 方法接收任何输入,并将其转发给它包含的第一个模块。然后,它将输出依次作为输入传递给后续的每一个模块,最后返回最后一个模块的输出。

与手动调用一系列模块相比,Sequential 提供的优势在于它允许将整个容器视为单个模块,因此对 Sequential 执行的转换会应用于它所存储的每个模块(每个模块都是 Sequential 的注册子模块)。

Sequentialtorch.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()),
        ]
    )
)
append(module)[来源]#

将给定的模块追加到末尾。

参数:

module (nn.Module) – 要附加的模块

返回类型:

自我

示例

>>> import torch.nn as nn
>>> n = nn.Sequential(nn.Linear(1, 2), nn.Linear(2, 3))
>>> n.append(nn.Linear(3, 4))
Sequential(
    (0): Linear(in_features=1, out_features=2, bias=True)
    (1): Linear(in_features=2, out_features=3, bias=True)
    (2): Linear(in_features=3, out_features=4, bias=True)
)
extend(sequential)[来源]#

使用来自另一个 Sequential 容器的层来扩展当前的 Sequential 容器。

参数:

sequential (Sequential) – 一个 Sequential 容器,其层将被添加到当前容器中。

返回类型:

自我

示例

>>> import torch.nn as nn
>>> n = nn.Sequential(nn.Linear(1, 2), nn.Linear(2, 3))
>>> other = nn.Sequential(nn.Linear(3, 4), nn.Linear(4, 5))
>>> n.extend(other) # or `n + other`
Sequential(
    (0): Linear(in_features=1, out_features=2, bias=True)
    (1): Linear(in_features=2, out_features=3, bias=True)
    (2): Linear(in_features=3, out_features=4, bias=True)
    (3): Linear(in_features=4, out_features=5, bias=True)
)
forward(input)[来源]#

执行前向传播。

insert(index, module)[来源]#

在指定的索引处向 Sequential 容器插入一个模块。

参数:
  • index (int) – 插入模块的索引。

  • module (Module) – 要插入的模块。

返回类型:

自我

示例

>>> import torch.nn as nn
>>> n = nn.Sequential(nn.Linear(1, 2), nn.Linear(2, 3))
>>> n.insert(0, nn.Linear(3, 4))
Sequential(
    (0): Linear(in_features=3, out_features=4, bias=True)
    (1): Linear(in_features=1, out_features=2, bias=True)
    (2): Linear(in_features=2, out_features=3, bias=True)
)
pop(key)[来源]#

从自身中弹出 key

返回类型:

模块