nn.Sequential()动态添加方法

之前我们使用nn.Sequential()都是直接写死的,就如下所示:

# Example of using Sequential
model = nn.Sequential(
          nn.Conv2d(1,20,5),
          nn.ReLU(),
          nn.Conv2d(20,64,5),
          nn.ReLU()
        )

# Example of using Sequential with OrderedDict
model = nn.Sequential(OrderedDict([
          (‘conv1‘, nn.Conv2d(1,20,5)),
          (‘relu1‘, nn.ReLU()),
          (‘conv2‘, nn.Conv2d(20,64,5)),
          (‘relu2‘, nn.ReLU())
        ]))

那如果我们想要根据条件一点点添加进去,那就可以使用其的add_module方法

torch.nn.Module.add_module

add_module(name, module)

添加子模块到当前模块中

该添加子模块能够使用给定的名字name来访问

参数:

  • name (string):子模块的名字。该添加子模块能够使用给定的名字name来从该模块中被访问
  • module (Module) :添加到该模块中的子模块

例子:

class Encoder(nn.Module):  #输入图片的大小isize、噪声的维度nz=100、输入图片的通道nc=3、ndf=64、
    def __init__(self,isize,nz,nc,ndf,ngpu,n_exter_layers=0,add_final_conv=True):
        super(Encoder,self).__init__()
        self.ngpu=ngpu
        # 必须为16倍数
        assert isize % 16==0,"isize has to be a multiple of 16"

        main=nn.Sequential()
        # 图片的高宽缩小一倍
        main.add_module(‘initial-conv-{0}-{1}‘.format(nc,ndf),nn.Conv2d(nc,ndf,4,2,1,bias=False))
        main.add_module(‘initial-relu-{0}‘.format(ndf),nn.LeakyReLU(0.2,inplace=True))
        csize,cndf=isize/2,ndf

        for t in range(n_exter_layers): #在这里面特征宽高不变,通道数也不变
            main.add_module(‘extra-layers-{0}-{1}-conv‘.format(t,cndf),nn.Conv2d(cndf,cndf,3,1,1,bias=False))
            main.add_module(‘extra-layers-{0}-{1}-batchnorm‘.format(t,cndf),nn.BatchNorm2d(cndf))
            main.add_module(‘extra-layers-{0}-{1}-relu‘.format(t,cndf),nn.LeakyReLU(0.2,inplace=True))

        # 在特征高宽仍大于4时,就添加缩小一倍高宽,通道增加一倍的卷积块
        while csize>4:
            in_feat = cndf

            out_feat = cndf * 2

            main.add_module(‘pyramid-{0}-{1}-conv‘.format(in_feat, out_feat),nn.Conv2d(in_feat, out_feat, 4, 2, 1, bias=False))

            main.add_module(‘pyramid-{0}-batchnorm‘.format(out_feat),nn.BatchNorm2d(out_feat))

            main.add_module(‘pyramid-{0}-relu‘.format(out_feat),nn.LeakyReLU(0.2, inplace=True))

            cndf = cndf * 2

            csize = csize / 2

        # 最后一层卷积,将4*4变为1*1,得到nz = 100的噪声
        if add_final_conv:

            main.add_module(‘final-{0}-{1}-conv‘.format(cndf, 1),nn.Conv2d(cndf, nz, 4, 1, 0, bias=False))
            self.main=main

    def forward(self,input):
        if self.ngpu>1:
             output=nn.parallel.data_parallel(self.main,input,range(self.ngpu)) #在多个gpu上运行模型,并行计算
        else:
            output=self.main(input)

        return output  #如果输入的大小是3×32×32,最后的输出是100×1×1.

原文地址:https://www.cnblogs.com/wanghui-garcia/p/11278061.html

时间: 2024-07-31 16:44:33

nn.Sequential()动态添加方法的相关文章

Runtime(动态添加方法)

A问:  有没有使用过performSelector,什么时候使用?动态添加方法的时候使用过?怎么动态添加方法?用runtime?为什么要动态添加方法? B:Runtime(动态添加方法):OC都是懒加载机制,只要一个方法实现了,就会马上添加到方法列表中. app:免费版,收费版 QQ,微博,直播等等应用,都有会员机制 // 任何方法默认都有两个隐式参数,self,_cmd // 什么时候调用:只要一个对象调用了一个未实现的方法就会调用这个方法,进行处理 // 作用:动态添加方法,处理未实现 +

使用runtime给类动态添加方法并调用 - class_addMethod

上手开发 iOS 一段时间后,我发现并不能只着眼于完成需求,利用闲暇之余多研究其他的开发技巧,才能在有限时间内提升自己水平.当然,“其他开发技巧”这个命题对于任何一个开发领域都感觉不找边际,而对于我来说,尝试接触 objc/runtime 不失为是开始深入探索 iOS 开发的第一步. 刚了解 runtime 当然要从比较简单的 api 开始,今天就罗列整理一下 class_addMethod 的相关点: 首先从文档开始. /** * Adds a new method to a class wi

给python类动态添加方法(method)

群里有人问如何做到 def foo(): pass class Bar(object): pass Bar.set_instance_method(foo) b = Bar() b.foo() 这个其实还是比较简单的, 只要写个函数给类设置属性即可, 可根据需求是否用函数包装下, 或者用staticmethod这个decorator: import functools def foo(): print 'hello world' class Bar(object): def __init__(s

python 面向对象六 动态添加方法 __slots__限制动态添加方法

一.动态添加属性 1 >>> class Student(object): 2 pass 3 4 >>> st = Student() 5 >>> st.name = 'Jack' 6 >>> st.name 7 'Jack' 二.动态给实例添加方法 1 >>> from types import MethodType 2 >>> class Student(object): 3 pass 4 5

给模型类动态添加方法

想要在每个类上加个方法或者property,一种可以每个类下加,另一种如下 def get_test(self): return 1 from django.contrib.contenttypes.models import ContentType model_list = ['CommonSite'] # 或者也可以直接传类对象,下面就不用ContentType了 for obj in model_list: # ContentType.objects.get(model=obj).mode

runtime与动态添加方法

代码-ViewController.m: #import "ViewController.h" #import "Dog.h" @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; Dog *dog = [[Dog alloc] init]; [dog performSelector:NSSelectorFromString(@"run")]; [dog

python 类对象和实例对象动态添加方法

1 class Person(): 2 def __init__(self, name): 3 self.name = name 4 5 6 def print_name(self): 7 print(self.name) 8 9 p = Person('Li') 10 import types 11 p.print_name = types.MethodType(print_name, p) # 绑定函数到对象 12 p.print_name() 13 14 15 @staticmethod

runtime 方法替换 和 动态添加类方法 结合使用

原文地址:runtime 方法替换 和 动态添加类方法 结合使用 前言:方法替换,可以替换任意外部类的方法,而动态添加方法只能实现在被添加类创建的对象里,但是将方法替换和动态添加方法结合使用,可以实现,对任意外部类动态添加需要的方法. 缺陷:1.含参数的方法难以处理,参数值需要根据实际业务逻辑而定.2.无法实现动态添加实例方法. Create Person.h and Person.m Person.h: 12345 #import <Foundation/Foundation.h> @int

python3 - 动态添加属性以及方法

给实例动态添加方法,需引入types模块,用其的MethodType(要绑定的方法名,实例对象)来进行绑定:给类绑定属性和方法,可以通过 实例名.方法名(属性名) = 方法名(属性值) 来进行绑定.给类添加方法,通过@classmethod:给类添加静态方法通过@staticmethod import types #定义了一个类class Person(object): num = 0 def __init__(self, name = None, age = None): self.name