本文共 2091 字,大约阅读时间需要 6 分钟。
import torch.nn as nnmodel = 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())# 输出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())
# 被添加的module可以通过 name 属性来获取。import torch.nn as nnclass 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)# 输出:注意子模块的命名方式Conv2d(10, 20, kernel_size=(4, 4), stride=(1, 1))Model( (conv): Conv2d(10, 20, kernel_size=(4, 4), stride=(1, 1)))
import torch.nn as nnmodel = 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())
import collectionsimport torch.nn as nnmodel = 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())
转载地址:http://ybugf.baihongyu.com/