NSDT工具推荐Three.js AI纹理开发包 - YOLO合成数据生成器 - GLTF/GLB在线编辑 - 3D模型格式在线转换 - 可编程3D场景编辑器 - REVIT导出3D模型插件 - 3D模型语义搜索引擎 - AI模型在线查看 - Three.js虚拟轴心开发包 - 3D模型在线减面 - STL模型在线切割 - 3D道路快速建模

批归一化是完整 CNN 架构中的另一个重要元素,其作用如下:

  • 将不同范围的值压缩成近似N~(0, 1),即平均值为0,标准差为1
  • 对于 sigmoid 激活,如果值太大,梯度接近 0,存在梯度消失的风险

批量归一化的优点如下:

  • 使收敛速度更快
  • 梯度下降更稳定
  • 可以使用更大的学习率
  • 可能获得更好的损失函数最小值

图像或特征块批归一化的详细信息

  • 找到每个通道的平均值 μ 和标准 σ
  • 例如。 一批(N 个图像)形状为 [N, 3, 28, 28] 的 RGB 图像,在 3 个通道上完成批归一化。
  • 因此批处理层将具有shape=[3]的μ、σ。
  • 还有另外两个可学习参数:γ 和 β,用于微调平均值和标准差(γ 进行缩放,β 进行平移 N~(0, 1))
  • 这意味着最终的输出不会完全落入 N~(0, 1) 而是 N~(β, γ)

1、nn.BatchNorm1d()

用于扁平化网络。

例如。 CNN 末尾的全连接 nn,其中 x.shape=[100, 16, 784]

import torch
import torch.nn as nn

# nn.BatchNorm1d

x = torch.rand(100, 16, 784)  # here imgs are flattened from 28x28

layer = nn.BatchNorm1d(16)  # batch norm is done on channels
out = layer(x)

print(layer.running_mean)
print(layer.running_var)

2、nn.BatchNorm2d()

  • 用于具有 4 维特征的卷积层。
  • 例如。 x.shape = [1, 16, 7, 7]
  • 批归一化层中的权重为 γ,可在反向传播过程中学习
  • 批归一化层中的偏差为 β,可在反向传播过程中学习
  • 由于 γ 和 β 是可学习的,因此从 vars(layer) 结果中你可以看到 require_grad=True
  • 使用layer.train()和layer.eval()改变模式来判断是否需要计算梯度、μ和σ
# nn.BatchNorm2d
x = torch.rand(1, 16, 7, 7)  # here image or features are not flattened 
print(x.shape)

layer = nn.BatchNorm2d(16)  # batch norm is done on channels

out = layer(x)

print(layer.weight)  # weight here is gamma, was learned to adjust the batch norm to N(beta, gamma) from N(0, 1)
print(layer.bias)  # bias here is beta, was learned to adjust the batch norm to N(beta, gamma)

print(vars(layer))

print(layer.eval())
print(layer.train())

原文链接:Learning Day 20: Batch normalization concept and usage in Pytorch

BimAnt翻译整理,转载请标明出处