評價此頁

Sequential#

class torch.nn.modules.container.Sequential(*args: Module)[原始碼]#
class torch.nn.modules.container.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)[原始碼]#

從 self 中彈出 key

返回型別

模組