PyTorch踩坑指南(1)nn.BatchNorm2d()函数

PyTorch踩坑指南(1)nn.BatchNorm2d()函数前言最近在研究深度学习中图像数据处理的细节,基于的平台是PyTorch。心血来潮,总结一下,好记性不如烂笔头。BatchNormalization对于2015年出现的BatchNormalization1,2018年的文章GroupNormalization2在Abstract中总结得言简意赅,我直接copy过来。BatchNormalization(BN)isamile…

大家好,又见面了,我是你们的朋友全栈君。

前言

最近在研究深度学习中图像数据处理的细节,基于的平台是PyTorch。心血来潮,总结一下,好记性不如烂笔头。

Batch Normalization

对于2015年出现的Batch Normalization1,2018年的文章Group Normalization2在Abstract中总结得言简意赅,我直接copy过来。

Batch Normalization (BN) is a milestone technique in the development of deep learning, enabling various networks to train. However, normalizing along the batch dimension introduces problems — BN’s error increases rapidly when the batch size becomes smaller, caused by inaccurate batch statistics estimation. This limits BN’s usage for training larger models and transferring features to computer vision tasks including detection, segmentation, and video, which require small batches constrained by memory consumption.

机器学习中,进行模型训练之前,需对数据做归一化处理,使其分布一致。在深度神经网络训练过程中,通常一次训练是一个batch,而非全体数据。每个batch具有不同的分布产生了internal covarivate shift问题——在训练过程中,数据分布会发生变化,对下一层网络的学习带来困难。Batch Normalization强行将数据拉回到均值为0,方差为1的正太分布上,一方面使得数据分布一致,另一方面避免梯度消失。

结合图1,说明Batch Normalization的原理。假设在网络中间经过某些卷积操作之后的输出的feature maps的尺寸为N×C×W×H,5为batch size(N),3为channel(C),W×H为feature map的宽高,则Batch Normalization的计算过程如下。
在这里插入图片描述


图 1

  • 1.每个batch计算同一通道的均值 μ \mu μ,如图取channel 0,即 c = 0 c=0 c=0(红色表示)
    μ = ∑ n = 0 N − 1 ∑ w = 0 W − 1 ∑ h = 0 H − 1 X [ n , c , w , h ] N × W × H \mu = \frac{\sum\limits_{n=0}^{N-1}\sum\limits_{w=0}^{W-1} \sum\limits_{h=0}^{H-1} X[n, c, w, h]}{N×W×H} μ=N×W×Hn=0N1w=0W1h=0H1X[n,c,w,h]
  • 2.每个batch计算同一通道的方差 σ 2 σ^2 σ2
    σ 2 = ∑ n = 0 N − 1 ∑ w = 0 W − 1 ∑ h = 0 H − 1 ( X [ n , c , w , h ] − μ ) 2 N × W × H σ^2 = \frac{\sum\limits_{n=0}^{N-1}\sum\limits_{w=0}^{W-1} \sum\limits_{h=0}^{H-1} (X[n, c, w, h]-\mu)^2}{N×W×H} σ2=N×W×Hn=0N1w=0W1h=0H1(X[n,c,w,h]μ)2
  • 3.对当前channel下feature map中每个点 x x x,索引形式 X [ n , c , w , h ] X[n, c, w, h] X[n,c,w,h],做归一化
    x ′ = ( x − μ ) σ 2 + ϵ x^{‘}=\frac{(x-\mu)}{\sqrt{σ^2+\epsilon}} x=σ2+ϵ
    (xμ)
  • 4.增加缩放和平移变量 γ \gamma γ β \beta β(可学习的仿射变换参数),归一化后的值
    y = γ x ′ + β y=\gamma x^{‘}+\beta y=γx+β
    简化公式:
    y = x − μ σ 2 + ϵ γ + β y=\frac{x-\mu}{\sqrt{\sigma^2+\epsilon}}\gamma +\beta y=σ2+ϵ
    xμ
    γ+
    β

    原文中的算法描述如下,
    在这里插入图片描述
    注:上图1所示 m m m就是 N ∗ W ∗ H N*W*H NWH

PyTorch的nn.BatchNorm2d()函数

理解了Batch Normalization的过程,PyTorch里面的函数就参考其文档3用就好。
BatchNorm2d()内部的参数如下:

  • num_features:一般情况下输入的数据格式为batch_size * num_features * height * width,即为特征数,channel数
  • eps:分母中添加的一个值,目的是为了计算的稳定性,默认:1e-5
  • momentum:一个用于运行过程中均值和方差的一个估计参数,默认值为 0.1 0.1 0.1 x ^ n e w = ( 1 − m o m e n t u m ) × x ^ + m o m e n t u m × x t \hat{x}_{new} =(1−momentum) × \hat{x} +momentum×x_t x^new=(1momentum)×x^+momentum×xt,其中 x ^ \hat{x} x^是估计值, x t x_t xt是新的观测值
  • affine:当设为true时,给定可以学习的系数矩阵 γ \gamma γ β \beta β

Show me the codes

import torch
import torch.nn as nn

def checkBN(debug = False):
    # parameters
    N = 5 # batch size
    C = 3 # channel
    W = 2 # width of feature map
    H = 2 # height of feature map
    # batch normalization layer
    BN = nn.BatchNorm2d(C,affine=True) #gamma和beta, 其维度与channel数相同
    # input and output
    featuremaps = torch.randn(N,C,W,H)
    output = BN(featuremaps)
    # checkout
    ###########################################
    if debug:
        print("input feature maps:\n",featuremaps)
        print("normalized feature maps: \n",output)
    ###########################################
    
    # manually operation, the first channel
    X = featuremaps[:,0,:,:]
    firstDimenMean = torch.Tensor.mean(X)
    firstDimenVar = torch.Tensor.var(X,False) #Bessel's Correction贝塞尔校正不被使用
    
    BN_one = ((input[0,0,0,0] - firstDimenMean)/(torch.pow(firstDimenVar+BN.eps,0.5) )) * BN.weight[0] + BN.bias[0]
    print('+++'*15,'\n','manually operation: ', BN_one)
    print('==='*15,'\n','pytorch result: ', output[0,0,0,0])
    
if __name__=="__main__":
    checkBN()

可以看出手算的结果和PyTorch的nn.BatchNorm2d的计算结果一致。

+++++++++++++++++++++++++++++++++++++++++++++
 manually operation:  tensor(-0.0327, grad_fn=<AddBackward0>)
=============================================
 pytorch result:  tensor(-0.0327, grad_fn=<SelectBackward>)

贝塞尔校正

代码中出现,求方差时是否需要贝塞尔校正,即从样本方差到总体方差的校正。
方差公式从,
σ 2 = ∑ i = 0 N − 1 ( x i − m e a n ( x ) ) 2 N \sigma^2 = \frac{\sum\limits_{i=0}^{N-1} (x_i-mean(x))^2}{N} σ2=Ni=0N1(ximean(x))2
变成(基于样本的总体方差的无偏估计),
σ 2 = ∑ i = 0 N − 1 ( x i − m e a n ( x ) ) 2 N − 1 \sigma^2 = \frac{\sum\limits_{i=0}^{N-1} (x_i-mean(x))^2}{N-1} σ2=N1i=0N1(ximean(x))2

Reference


  1. Ioffe, Sergey, and Christian Szegedy. “Batch normalization: Accelerating deep network training by reducing internal covariate shift.” arXiv preprint arXiv:1502.03167 (2015). ↩︎ ↩︎

  2. Wu, Yuxin, and Kaiming He. “Group normalization.” Proceedings of the European Conference on Computer Vision (ECCV). 2018. ↩︎

  3. BatchNorm2d ↩︎

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/134016.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • Silverlight网站实例资源收集(1)

    Silverlight网站实例资源收集(1)Silverlight做的试用VisualStudio2008http://www.challenges.com.cn/ 全功能的相册http://msbluelight-0.agappdom.net/e1/d/72193/13304799/63356644800/0.vpFl7uJ79e1H4xExhhjCX701HlA/zziframehtml2zz.html#%2f%2

    2022年10月18日
    4
  • 什么叫应用程序域?(zhuan)

    什么叫应用程序域?(zhuan) 一:应用程序域介绍:    "域",就是范围,环境,边界的意思,那么什么是应用程序域,官方给出的是这样的解释:操作系

    2022年7月3日
    17
  • linux卸载mysql(完全卸载)[通俗易懂]

    linux卸载mysql(完全卸载)[通俗易懂]//rpm包安装方式卸载查包名:rpm-qa|grep-imysql删除命令:rpm-e–nodeps包名//yum安装方式下载1.查看已安装的mysql命令:rpm-qa|grep-imysql2.卸载mysql命令:yumremovemysql-community-server-5.6.36-2.el7.x86_64查看mysql的其它依赖:rpm…

    2022年6月29日
    27
  • eXtremeDB内存实时数据库

    eXtremeDB内存实时数据库这是一款实时和嵌入式软件 用来管理持续增长的复杂数据 来支持高级应用的特性 性能和可靠性 更短的产品开发周期等需求 驱使开发者在他们的设计中 考虑采用经验证的 成熟的商业数据库系统组件来 来满足应用层的这些需求 McObject 公司的 eXtremeDB 嵌入式数据库系列产品是将高性能 稳定性和简单易用性等特性同时融入了工业基的数据库引擎 了解 eXtremeDB 产品系列或 eXtreme

    2025年8月23日
    3
  • vs2012卸载工具_teighax能卸载吗

    vs2012卸载工具_teighax能卸载吗vs2005的安装和部署功能打包時加入卸载功能:  方法一:  1.在打包項目中添加文件msiexec.exe(一般可在c:/windows/system32/下找到)  2.在文件系統視圖中選擇應用程序文件夾,在msiexec.exe上按右鍵,選擇創建快捷方式,重命名快捷方式為”卸载”.  3.更改此快捷方式的Arguments 为”/x {產品id}”,

    2022年9月23日
    3
  • MySQL——开窗函数

    MySQL——开窗函数

    2021年5月20日
    507

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号