Sequential¶
- class torch.nn.Sequential(*args: Module)[source][source]¶
- class torch.nn.Sequential(arg: OrderedDict[str, Module])
一個 Sequential 容器。
模組將按照它們在建構函式中傳入的順序被新增到其中。或者,也可以傳入一個模組的
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()) ]))