关于 Pytorch 几种定义网络的方法

点击上方“机器学习与生成对抗网络”,关注星标

获取有趣、好玩的前沿干货!

来源:知乎—ppgod

地址:https://zhuanlan.zhihu.com/p/80308275

以前自己的代码写得比较随意,最近阅读了很多大佬写的代码,发现真的是赏心悦目。这边就网络的定义的几种方法总结一下。首先,最简单的肯定是直接申明了

import torch
import torch.nn as nn
from torch.autograd import Variable
from collections import OrderedDict
class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.fc1 = nn.Linear(10,10)
        self.relu1 = nn.ReLU(inplace=True)
        self.fc2 = nn.Linear(10,2)
    def forward(self,x):
        x = self.fc1(x)
        x = self.relu1(x)
        x = self.fc2(x)
        return x

这是最简单的定义一个网络的方法,但是当网络层数过多的时候,这么写未免太麻烦,于是Pytorch还有第二种定义网络的方法nn.ModuleList()

class Net(nn.Module):    def __init__(self):        super(Net, self).__init__()        self.base = nn.ModuleList([nn.Linear(10,10), nn.ReLU(), nn.Linear(10,2)])    def forward(self,x):        x = self.base(x)        return x

nn.ModuleList()接收的参数为一个List,这样就可以很方便的定义一个网络,比如

base = [nn.Linear(10,10) for i in range(5)]net = nn.ModuleList(base)

最后一个方法就是nn.Sequential()

class Net(nn.Module):    def __init__(self):        super(Net, self).__init__()        self.base = nn.Sequential(nn.Linear(10,10), nn.ReLU(), nn.Linear(10,2))    def forward(self,x):        x = self.base(x)        return x

当然nn.Sequential()还有另外一种用法OrderedDict

class MultiLayerNN5(nn.Module):    def __init__(self):        super(MultiLayerNN5, self).__init__()        self.base = nn.Sequential(OrderedDict([            ('0', BasicConv(1, 16, 5, 1, 2)),            ('1', BasicConv(16, 32, 5, 1, 2)),        ]))        self.fc1 = nn.Linear(32 * 7 * 7, 10)
    def forward(self, x):        x = self.base(x)        x = x.view(x.size(0), -1)        x = self.fc1(x)        return x

除此之外,nn.Sequential还能add_module

class MultiLayerNN4(nn.Module):    def __init__(self):        super(MultiLayerNN4, self).__init__()        self.base = nn.Sequential()        self.base.add_module('0', BasicConv(1, 16, 5, 1, 2))        self.base.add_module('1', BasicConv(16, 32, 5, 1, 2))        self.fc1 = nn.Linear(32 * 7 * 7, 10)
    def forward(self, x):        x = self.base(x)        x = x.view(x.size(0),-1)        x = self.fc1(x)

来看一下nn.Sequential()以及nn.ModuleList()的主要区别,我个人感觉就是nn.Sequential()里面自带了forward函数,可以直接操作输入,而nn.ModuleList()需要定义一个forward函数

tt = [nn.Linear(10,10), nn.Linear(10,2)]n_1 = nn.Sequential(*tt)n_2 = nn.ModuleList(tt)x = torch.rand([1,10,10])x = Variable(x)n_1(x)n_2(x)#会出现NotImplementedError

在定义比较深的网络的时候,结合nn.ModuleList()以及nn.Sequential()在代码量上会看上去十分简洁


这是分割线,最近在看denseNet的时候,又学到了一种定义网络的办法,就是直接继承nn.Sequential

class DenseLayer(nn.Sequential):    def __init__(self):        super(DenseLayer, self).__init__()        self.add_module("conv1", nn.Conv2d(1, 1, 1, 1, 0))        self.add_module("conv2", nn.Conv2d(1, 1, 1, 1, 0))
    def forward(self, x):        new_features = super(DenseLayer, self).forward(x)        return torch.cat([x, new_features], 1)#这个写法和下面的是一样的class DenLayer1(nn.Module):    def __init__(self):        super(DenLayer1, self).__init__()        convs = [nn.Conv2d(1, 1, 1, 1, 0), nn.Conv2d(1, 1, 1, 1, 0)]        self.conv = nn.Sequential(*convs)    def forward(self, x):        return torch.cat([x, self.conv(x)], 1)net = DenLayer1()x = torch.Tensor([[[[1, 2], [3, 4]]]])print(x)x = Variable(x)print(net(x))
猜您喜欢:
等你着陆!【GAN生成对抗网络】知识星球!  
CVPR 2021 | GAN的说话人驱动、3D人脸论文汇总

CVPR 2021 | 图像转换 今如何?几篇GAN论文

【CVPR 2021】通过GAN提升人脸识别的遗留难题

CVPR 2021生成对抗网络GAN部分论文汇总

经典GAN不得不读:StyleGAN

最新最全20篇!基于 StyleGAN 改进或应用相关论文

超100篇!CVPR 2020最全GAN论文梳理汇总!
附下载 | 《Python进阶》中文版
附下载 | 经典《Think Python》中文版
附下载 | 《Pytorch模型训练实用教程》
附下载 | 最新2020李沐《动手学深度学习》

附下载 | 《可解释的机器学习》中文版

附下载 |《TensorFlow 2.0 深度学习算法实战》

附下载 | 超100篇!CVPR 2020最全GAN论文梳理汇总!
附下载 |《计算机视觉中的数学方法》分享

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值