import torch.nn as nn
from torch.nn import Conv2d
from collections import OrderedDict
class net1(nn.Module):
def __init__(self):
super(net1, self).__init__()
self.conv1 = Conv2d(3, 3, 1)
self.conv2 = Conv2d(3, 3, 1)
def forward(self, x):
return self.conv1(self.conv2(x))
net1 = net1()
print(net1)
class net2(nn.Module):
def __init__(self):
super(net2, self).__init__()
self.layer = nn.Sequential(
Conv2d(3, 3, 1),
Conv2d(3, 3, 1)
)
def forward(self, x):
return self.conv1(self.conv2(x))
net2 = net2()
print(net2)
class net3(nn.Module):
def __init__(self):
super(net3, self).__init__()
self.layer = nn.Sequential(OrderedDict([
('conv1', Conv2d(3, 3, 1)),
('conv2', Conv2d(3, 3, 1))
]))
def forward(self, x):
return self.conv1(self.conv2(x))
net3 = net3()
print(net3)
class net4(nn.Module):
def __init__(self):
super(net4, self).__init__()
self.layer = nn.Sequential() # nn.ModuleDict(), nn.ModuleList()
self.layer.add_module('conv1', Conv2d(3, 3, 3))
self.layer.add_module('conv2', Conv2d(3, 3, 3))
def forward(self, x):
return self.conv1(self.conv2(x))
net4 = net4()
print(net4)
class net5(nn.Module):
def __init__(self):
super(net5, self).__init__()
self.layer = nn.ModuleList([Conv2d(3, 3, 3), Conv2d(3, 3, 3)])
def forward(self, x):
return self.conv1(self.conv2(x))
net5 = net5()
print(net5)
class net6(nn.Module):
def __init__(self):
super(net6, self).__init__()
self.layer = nn.ModuleDict({
'conv1': Conv2d(3, 3, 3),
'conv2': Conv2d(3, 3, 3)
})
def forward(self, x):
return self.conv1(self.conv2(x))
net6 = net6()
print(net6)
class net7(nn.Module):
def __init__(self):
super(net7, self).__init__()
self.layer = nn.ModuleDict([
('conv1', Conv2d(3, 3, 3)),
('conv2', Conv2d(3, 3, 3))
])
def forward(self, x):
return self.conv1(self.conv2(x))
net7 = net7()
print(net7)
class net8(nn.Module):
def __init__(self):
super(net8, self).__init__()
self.list = [Conv2d(3, 3, 3), Conv2d(3, 3, 3)] # 不建议使用, 不会加入到Module中
def forward(self, x):
return self.list(x)
model = net8()
print(model)
net1(
(conv1): Conv2d(3, 3, kernel_size=(1, 1), stride=(1, 1))
(conv2): Conv2d(3, 3, kernel_size=(1, 1), stride=(1, 1))
)
net2(
(layer): Sequential(
(0): Conv2d(3, 3, kernel_size=(1, 1), stride=(1, 1))
(1): Conv2d(3, 3, kernel_size=(1, 1), stride=(1, 1))
)
)
net3(
(layer): Sequential(
(conv1): Conv2d(3, 3, kernel_size=(1, 1), stride=(1, 1))
(conv2): Conv2d(3, 3, kernel_size=(1, 1), stride=(1, 1))
)
)
net4(
(layer): Sequential(
(conv1): Conv2d(3, 3, kernel_size=(3, 3), stride=(1, 1))
(conv2): Conv2d(3, 3, kernel_size=(3, 3), stride=(1, 1))
)
)
net5(
(layer): ModuleList(
(0): Conv2d(3, 3, kernel_size=(3, 3), stride=(1, 1))
(1): Conv2d(3, 3, kernel_size=(3, 3), stride=(1, 1))
)
)
net6(
(layer): ModuleDict(
(conv1): Conv2d(3, 3, kernel_size=(3, 3), stride=(1, 1))
(conv2): Conv2d(3, 3, kernel_size=(3, 3), stride=(1, 1))
)
)
net7(
(layer): ModuleDict(
(conv1): Conv2d(3, 3, kernel_size=(3, 3), stride=(1, 1))
(conv2): Conv2d(3, 3, kernel_size=(3, 3), stride=(1, 1))
)
)
net8()
Process finished with exit code 0