torch.nn.Sequential()搭建神经网络模型


一、第一种方式(可以配合一些条件判断语句动态添加)

  • 模板——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()
)

posted on 2020-08-25 10:40  cltt  阅读(1842)  评论(0编辑  收藏  举报

导航