当前位置:  开发笔记 > 人工智能 > 正文

pytorch实现特殊的Module--Sqeuential三种写法

今天小编就为大家分享一篇pytorch实现特殊的Module--Sqeuential三种写法。具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

我就废话不多说了,直接上代码吧!

# -*- coding: utf-8 -*-
#@Time  :2019/7/1 13:34
#@Author :XiaoMa
 
import torch as t
from torch import nn
#Sequential的三种写法
net1=nn.Sequential()
net1.add_module('conv',nn.Conv2d(3,3,3))  #Conv2D(输入通道数,输出通道数,卷积核大小)
net1.add_module('batchnorm',nn.BatchNorm2d(3))  #BatchNorm2d(特征数)
net1.add_module('activation_layer',nn.ReLU())
 
net2=nn.Sequential(nn.Conv2d(3,3,3),
          nn.BatchNorm2d(3),
          nn.ReLU()
          )
 
from collections import OrderedDict
net3=nn.Sequential(OrderedDict([
  ('conv1',nn.Conv2d(3,3,3)),
  ('bh1',nn.BatchNorm2d(3)),
  ('al',nn.ReLU())
]))
 
print('net1',net1)
print('net2',net2)
print('net3',net3)
 
#可根据名字或序号取出子module
print(net1.conv,net2[0],net3.conv1)

输出结果:

net1 Sequential(
 (conv): Conv2d(3, 3, kernel_size=(3, 3), stride=(1, 1))
 (batchnorm): BatchNorm2d(3, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
 (activation_layer): ReLU()
)
 
net2 Sequential(
 (0): Conv2d(3, 3, kernel_size=(3, 3), stride=(1, 1))
 (1): BatchNorm2d(3, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
 (2): ReLU()
)
 
net3 Sequential(
 (conv1): Conv2d(3, 3, kernel_size=(3, 3), stride=(1, 1))
 (bh1): BatchNorm2d(3, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
 (al): ReLU()
)
 
Conv2d(3, 3, kernel_size=(3, 3), stride=(1, 1)) 
Conv2d(3, 3, kernel_size=(3, 3), stride=(1, 1)) 
Conv2d(3, 3, kernel_size=(3, 3), stride=(1, 1))

以上这篇pytorch实现特殊的Module--Sqeuential三种写法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

推荐阅读
jerry613
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有