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

yipeiwu_com6年前Python基础

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

# -*- 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三种写法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python中实现将多个print输出合成一个数组

比如有下面一段代码: for i in range(10): print ("%s" % (f_list[i].name)) 该代码段的执行,会生成如下的10行“name”属性...

python中的for循环

python中的for循环

Python for循环可以遍历任何序列的项目,如一个列表或者一个字符串。 语法: for循环的语法格式如下: for iterating_var in sequence:...

Python面向对象类编写细节分析【类,方法,继承,超类,接口等】

本文实例讲述了Python面向对象类编写技术细节。分享给大家供大家参考,具体如下: 类代码编写细节 继续学习类、方法和继承。 class语句 以下是class语句的一般形式: cla...

Python中时间datetime的处理与转换用法总结

python中日期类datetime功能比较强大,使用起来很方便,把常用的两种用法总结如下: from datetime import datetime from datetime...

解决python 3 urllib 没有 urlencode 属性的问题

今天在pycharm(我用的python3)练习的时候,发现报了个AttributeError: module 'urllib' has no attribute 'urlencode'...