Pytorch-nn.BatchNorm2d()

本文通过PyTorch官方文档和示例代码详细解析了批量归一化(BatchNorm)的工作原理。展示了如何在神经网络中使用BatchNorm2d层,并通过具体数值验证了归一化过程。深入讨论了BatchNorm在训练和测试阶段的作用,以及其为何能有效提高网络性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Pytorch官方文档:

测试代码:

转自:https://blog.csdn.net/tmk_01/article/details/80679549

import torch
import torch.nn as nn

m = nn.BatchNorm2d(2,affine=True) #weight(gamma)和bias(beta)将被使用
input = torch.randn(1,2,3,4)
output = m(input)

print("输入图片:")
print(input)
print("归一化权重(公式中的gamma):")
print(m.weight)
print("归一化偏置(公式中的beta):")
print(m.bias)

print("归一化的输出:")
print(output)
print("输出的尺度:")
print(output.size())

# i = torch.randn(1,1,2)
print("输入的第一个维度:")
print(input[0][0])
firstDimenMean = torch.Tensor.mean(input[0][0])
firstDimenVar= torch.Tensor.var(input[0][0],False) #Bessel's Correction贝塞尔校正不会被使用

print(m.eps)
print("输入的第一个维度平均值:")
print(firstDimenMean)
print("输入的第一个维度方差:")
print(firstDimenVar)

bacthnormone = \
    ((input[0][0][0][0] - firstDimenMean)/(torch.pow(firstDimenVar+m.eps,0.5) ))\
               * m.weight[0] + m.bias[0]
print(bacthnormone)

代码运行结果:

输入图片:
tensor([[[[-1.1622, -0.9170, -0.6798, -0.0270],
          [ 0.2687, -1.6046, -0.2142, -0.3561],
          [ 0.2908, -0.1012,  1.3594,  1.1316]],

         [[ 0.4689,  1.4049,  1.2324, -1.3721],
          [-0.1498, -0.3207,  0.5072, -1.2563],
          [ 1.5934, -0.8010,  0.1270,  0.5993]]]])
归一化权重(公式中的gamma):
Parameter containing:
tensor([0.8681, 0.7207], requires_grad=True)
归一化偏置(公式中的beta):
Parameter containing:
tensor([0., 0.], requires_grad=True)
归一化的输出:
tensor([[[[-1.0344, -0.7794, -0.5326,  0.1463],
          [ 0.4538, -1.4945, -0.0484, -0.1960],
          [ 0.4767,  0.0691,  1.5881,  1.3512]],

         [[ 0.2279,  0.9400,  0.8088, -1.1729],
          [-0.2429, -0.3729,  0.2570, -1.0848],
          [ 1.0834, -0.7384, -0.0323,  0.3271]]]],
       grad_fn=<ThnnBatchNormBackward>)
输出的尺度:
torch.Size([1, 2, 3, 4])
输入的第一个维度:
tensor([[-1.1622, -0.9170, -0.6798, -0.0270],
        [ 0.2687, -1.6046, -0.2142, -0.3561],
        [ 0.2908, -0.1012,  1.3594,  1.1316]])
1e-05
输入的第一个维度平均值:
tensor(-0.1676)
输入的第一个维度方差:
tensor(0.6967)
tensor(-1.0344, grad_fn=<ThAddBackward>)

BatchNorm深度理解可参考:

  https://zhuanlan.zhihu.com/p/30922689

  4.Normalizing activations in a network

  5.Fitting Batch Norm into a neural network

  6.Why does Batch Norm work?

  7. Batch Norm at test time

 

  

 

转载于:https://www.cnblogs.com/leebxo/p/10102689.html

<think>我们正在讨论的是PyTorch中的`nn.BatchNorm2d`模块。用户已经提供了函数原型和参数说明,现在用户特别询问了返回值类型和意义。 根据用户的问题:“我想了解nn.BatchNorm2d的返回值类型和意义”,我们需要明确以下几点: 1. `nn.BatchNorm2d`是一个类,当我们实例化它之后,它就是一个可调用的模块(Module)。 2. 当我们调用这个实例(即进行前向传播)时,它接受一个输入张量(Tensor),然后返回一个输出张量(Tensor)。 因此,返回值类型是`torch.Tensor`,其形状与输入相同。 返回值的意义:经过批量归一化处理后的特征图。具体来说,对于输入张量的每个通道,根据当前模式(训练或评估)使用不同的统计量(当前批次的统计量或运行统计量)进行归一化,然后应用缩放(gamma)和平移(beta)。 下面我们详细展开:</think>### PyTorch `nn.BatchNorm2d` 返回值详解 #### 返回值类型 `nn.BatchNorm2d` 的返回值类型是 **四维张量** (`torch.Tensor`),其形状与输入张量完全相同: $$ \text{输出形状} = (N, C, H, W) $$ 其中: - $N$:批大小(Batch Size) - $C$:通道数(与 `num_features` 相同) - $H$:特征图高度 - $W$:特征图宽度 #### 返回值意义 返回值是经过**批归一化处理的特征图**,其数学意义取决于当前模式: 1. **训练模式(`model.train()`)**: $$ y = \gamma \cdot \frac{x - \mu_{\text{batch}}}{\sqrt{\sigma_{\text{batch}}^2 + \epsilon}} + \beta $$ - $\mu_{\text{batch}}$:当前批次数据的**通道级均值** - $\sigma_{\text{batch}}^2$:当前批次数据的**通道级方差** - $\gamma$:可学习的缩放参数(权重) - $\beta$:可学习的平移参数(偏置) - $\epsilon$:数值稳定项(`eps` 参数)[^1] 2. **评估模式(`model.eval()`)**: $$ y = \gamma \cdot \frac{x - \mu_{\text{run}}}{\sqrt{\sigma_{\text{run}}^2 + \epsilon}} + \beta $$ - $\mu_{\text{run}}$:训练过程中累积的**全局运行均值** - $\sigma_{\text{run}}^2$:训练过程中累积的**全局运行方差** - 使用预存统计量而非当前批次数据 #### 关键特性验证 ```python import torch import torch.nn as nn # 创建BN层 (输入通道=3) bn = nn.BatchNorm2d(3) # 模拟输入 (批大小=2, 3通道, 4x4特征图) inputs = torch.randn(2, 3, 4, 4) # 训练模式输出 bn.train() output_train = bn(inputs) print("训练输出形状:", output_train.shape) # torch.Size([2, 3, 4, 4]) print("通道0均值:", output_train[:,0].mean().item()) # ≈0 (归一化效果) print("通道0方差:", output_train[:,0].var().item()) # ≈1 (归一化效果) # 评估模式输出 bn.eval() with torch.no_grad(): output_eval = bn(inputs) print("评估输出形状:", output_eval.shape) # 相同形状 ``` #### 返回值特性总结 | 特性 | 说明 | |------|------| | **形状不变性** | 输出与输入维度完全一致 | | **通道独立性** | 每个通道单独归一化处理 | | **统计量依赖** | 训练/评估模式使用不同统计量 | | **可学习参数** | $\gamma$ 和 $\beta$ 参与梯度反传[^2] | | **数值稳定性** | $\epsilon$ 防止除零错误(默认 $10^{-5}$) | #### 典型应用场景 ```python # CNN中的标准用法:卷积 → BN → 激活 model = nn.Sequential( nn.Conv2d(3, 64, kernel_size=3), # 卷积层[^2] nn.BatchNorm2d(64), # 批归一化 nn.ReLU(), # 激活函数 nn.MaxPool2d(2) # 池化层[^1] ) ``` 此结构能有效缓解梯度消失/爆炸问题,加速模型收敛[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值