pytorch学习: 构建网络模型的几种方法 + BN层底层实现思路 + 六大学习率调整策略

转载地址:https://www.cnblogs.com/denny402/p/7593301.html

利用pytorch来构建网络模型有很多种方法,以下简单列出其中的四种。

假设构建一个网络模型如下:

卷积层--》Relu层--》池化层--》全连接层--》Relu层--》全连接层

首先导入几种方法用到的包:

import torch
import torch.nn.functional as F
from collections import OrderedDict

 

第一种方法

复制代码

# Method 1 -----------------------------------------

class Net1(torch.nn.Module):
    def __init__(self):
        super(Net1, self).__init__()
        self.conv1 = torch.nn.Conv2d(3, 32, 3, 1, 1)
        self.dense1 = torch.nn.Linear(32 * 3 * 3, 128)
        self.dense2 = torch.nn.Linear(128, 10)

    def forward(self, x):
        x = F.max_pool2d(F.relu(self.conv(x)), 2)
        x = x.view(x.size(0), -1)
        x = F.relu(self.dense1(x))
        x = self.dense2(x)
        return x

print("Method 1:")
model1 = Net1()
print(model1)

复制代码

这种方法比较常用,早期的教程通常就是使用这种方法。

 

第二种方法

复制代码

# Method 2 ------------------------------------------
class Net2(torch.nn.Module):
    def __init__(self):
        super(Net2, self).__init__()
        self.conv = torch.nn.Sequential(
            torch.nn.Conv2d(3, 32, 3, 1, 1),
            torch.nn.ReLU(),
            torch.nn.MaxPool2d(2))
        self.dense = torch.nn.Sequential(
            torch.nn.Linear(32 * 3 * 3, 128),
            torch.nn.ReLU(),
            torch.nn.Linear(128, 10)
        )

    def forward(self, x):
        conv_out = self.conv1(x)
        res = conv_out.view(conv_out.size(0), -1)
        out = self.dense(res)
        return out

print("Method 2:")
model2 = Net2()
print(model2)

复制代码

这种方法利用torch.nn.Sequential()容器进行快速搭建,模型的各层被顺序添加到容器中。缺点是每层的编号是默认的阿拉伯数字,不易区分。

 

第三种方法:

复制代码

# Method 3 -------------------------------
class Net3(torch.nn.Module):
    def __init__(self):
        super(Net3, self).__init__()
        self.conv=torch.nn.Sequential()
        self.conv.add_module("conv1",torch.nn.Conv2d(3, 32, 3, 1, 1))
        self.conv.add_module("relu1",torch.nn.ReLU())
        self.conv.add_module("pool1",torch.nn.MaxPool2d(2))
        self.dense = torch.nn.Sequential()
        self.dense.add_module("dense1",torch.nn.Linear(32 * 3 * 3, 128))
        self.dense.add_module("relu2",torch.nn.ReLU())
        self.dense.add_module("dense2",torch.nn.Linear(128, 10))

    def forward(self, x):
        conv_out = self.conv1(x)
        res = conv_out.view(conv_out.size(0), -1)
        out = self.dense(res)
        return out

print("Method 3:")
model3 = Net3()
print(model3)

复制代码

这种方法是对第二种方法的改进:通过add_module()添加每一层,并且为每一层增加了一个单独的名字。

 

第四种方法:

复制代码

# Method 4 ------------------------------------------
class Net4(torch.nn.Module):
    def __init__(self):
        super(Net4, self).__init__()
        self.conv = torch.nn.Sequential(
            OrderedDict(
                [
                    ("conv1", torch.nn.Conv2d(3, 32, 3, 1, 1)),
                    ("relu1", torch.nn.ReLU()),
                    ("pool", torch.nn.MaxPool2d(2))
                ]
            ))

        self.dense = torch.nn.Sequential(
            OrderedDict([
                ("dense1", torch.nn.Linear(32 * 3 * 3, 128)),
                ("relu2", torch.nn.ReLU()),
                ("dense2", torch.nn.Linear(128, 10))
            ])
        )

    def forward(self, x):
        conv_out = self.conv1(x)
        res = conv_out.view(conv_out.size(0), -1)
        out = self.dense(res)
        return out

print("Method 4:")
model4 = Net4()
print(model4)

复制代码

是第三种方法的另外一种写法,通过字典的形式添加每一层,并且设置单独的层名称。

 

PytorchBN层实现过程

原文:http://www.mamicode.com/info-detail-2378483.html

 

 之前一直和小伙伴探讨batch normalization层的实现机理,作用在这里不谈,知乎上有一篇paper在讲这个,链接

这里只探究其具体运算过程,我们假设在网络中间经过某些卷积操作之后的输出的feature map的尺寸为4×3×2×2

4为batch的大小,3为channel的数目,2×2为feature map的长宽

整个BN层的运算过程如下图

技术分享图片

 

上图中,batch size一共是4, 对于每一个batch的feature map的size是3×2×2

对于所有batch中的同一个channel的元素进行求均值与方差,比如上图,对于所有的batch,都拿出来最后一个channel,一共有4×4=16个元素,

然后求区这16个元素的均值与方差(上图只求了mean,没有求方差。。。),

求取完了均值与方差之后,对于这16个元素中的每个元素进行减去求取得到的均值与方差,然后乘以gamma加上beta,公式如下

技术分享图片

所以对于一个batch normalization层而言,求取的均值与方差是对于所有batch中的同一个channel进行求取,batch normalization中的batch体现在这个地方

batch normalization层能够学习到的参数,对于一个特定的channel而言实际上是两个参数,gamma与beta,对于total的channel而言实际上是channel数目的两倍。

 

用pytorch验证上述想法是否准确,用上述方法求取均值,以及用batch normalization层输出的均值,看看是否一样

上代码

 1 # -*-coding:utf-8-*-
 2 from torch import nn
 3 import torch
 4 
 5 m = nn.BatchNorm2d(3)  # bn设置的参数实际上是channel的参数
 6 input = torch.randn(4, 3, 2, 2)
 7 output = m(input)
 8 # print(output)
 9 a = (input[0, 0, :, :]+input[1, 0, :, :]+input[2, 0, :, :]+input[3, 0, :, :]).sum()/16
10 b = (input[0, 1, :, :]+input[1, 1, :, :]+input[2, 1, :, :]+input[3, 1, :, :]).sum()/16
11 c = (input[0, 2, :, :]+input[1, 2, :, :]+input[2, 2, :, :]+input[3, 2, :, :]).sum()/16
12 print(‘The mean value of the first channel is %f‘ % a.data)
13 print(‘The mean value of the first channel is %f‘ % b.data)
14 print(‘The mean value of the first channel is %f‘ % c.data)
15 print(‘The output mean value of the BN layer is %f, %f, %f‘ % (m.running_mean.data[0],m.running_mean.data[0],m.running_mean.data[0]))
16 print(m)

m = nn.BatchNorm2d(3)

声明新的batch normalization层,用

input = torch.randn(4, 3, 2, 2)

模拟feature map的尺寸

输出值

 技术分享图片

咦,怎么不一样,貌似差了一个小数点,可能与BN层的momentum变量有关系,在生命batch normalization层的时候将momentum设置为1试一试

m.momentum=1

输出结果

技术分享图片

 

pytorch学习率调整策略:

https://blog.csdn.net/chanbo8205/article/details/89283226

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值