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

时间:2020-08-25 11:23:15   收藏:0   阅读:472

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


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))
)

 

 

二、第二种方式

 

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()
)

 

 

三、第三种方式

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()
)

原文:https://www.cnblogs.com/tingtin/p/13558355.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!