一、第一種方式(可以配合一些條件判斷語句動態添加)
- 模板——torch.nn.Sequential()的一個對象.add_module(name, module)。
- name:某層次的名字;module:需要添加的子模塊,如卷積、激活函數等等。
- 添加子模塊到當前模塊中。
- 可以通過 name 屬性來訪問添加的子模塊。
- 輸出后每一層的名字:不是采用默認的命名方式(按序號 0,1,2,3…),而是按照name屬性命名!!
import torch.nn as nn
model = nn.Sequential()
model.add_module("conv1",nn.Conv2d(1,20,5))
model.add_module('relu1',nn.ReLU())
model.add_module("conv2",nn.Conv2d(20,64,5))
model.add_module('relu2',nn.ReLU())
print(model)
Sequential(
(conv1): Conv2d(1, 20, kernel_size=(5, 5), stride=(1, 1))#默認stride=(1,1)
(relu1): ReLU()
(conv2): Conv2d(20, 64, kernel_size=(5, 5), stride=(1, 1))
(relu2): ReLU()
)
nn.module也有add_module()對象
import torch.nn as nn
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.add_module("conv",nn.Conv2d(10,20,5))
#self.conv = nn.Conv2d(10,20,5)和上面操作等價
model = Model()
print(model.conv) # 通過name屬性訪問添加的子模塊
print(model)
Conv2d(10, 20, kernel_size=(5, 5), stride=(1, 1))
Model(
(conv): Conv2d(10, 20, kernel_size=(5, 5), stride=(1, 1))
)
二、第二種方式
- 模板——nn.Sequential(*module)。
- 輸出的每一層的名字:采用默認的命名方式(按序號 0,1,2,3…)
import torch.nn as nn
model = nn.Sequential(
nn.Conv2d(1,20,5),
nn.ReLU(),
nn.Conv2d(20,64,5),
nn.ReLU()
)
print(model)
# 輸出:注意命名方式
Sequential(
(0): Conv2d(1, 20, kernel_size=(5, 5), stride=(1, 1))
(1): ReLU()
(2): Conv2d(20, 64, kernel_size=(5, 5), stride=(1, 1))
(3): ReLU()
)
三、第三種方式
- 模板——nn.Sequential(OrderedDict([*(name, module)]))
- 輸出后每一層的名字:不是采用默認的命名方式(按序號 0,1,2,3…),而是按照name屬性命名!!
import collections
import torch.nn as nn
model = nn.Sequential(collections.OrderedDict([('conv1', nn.Conv2d(1, 20, 5)), ('relu1', nn.ReLU()),
('conv2', nn.Conv2d(20, 64, 5)),
('relu2', nn.ReLU())
]))
print(model)
# 輸出:注意子模塊命名方式
Sequential(
(conv1): Conv2d(1, 20, kernel_size=(5, 5), stride=(1, 1))
(relu1): ReLU()
(conv2): Conv2d(20, 64, kernel_size=(5, 5), stride=(1, 1))
(relu2): ReLU()
)
