評價此頁

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)[原始碼]#

從 self 中彈出 key

返回型別

模組