在使用pytorch进行深度学习开发的时候,在一个模型的基础上进行模块的添加,可以使用add_module,可以采用nn.Sequential,也可以采用nn.Module。
(1)nn.Sequential()
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())
(2) nn.Module()
# 被添加的module可以通过 name 属性来获取。
import torch.nn as nn
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.add_module("conv", nn.Conv2d(10, 20, 4))
# self.conv = nn.Conv2d(10, 20, 4) 和上面这个增加module的方式等价
model = Model()
print(model.conv) # 通过name属性访问添加的子模块
print(model)
参考文献: