LayerNorm#
- class torch.nn.modules.normalization.LayerNorm(normalized_shape, eps=1e-05, elementwise_affine=True, bias=True, device=None, dtype=None)[source]#
对输入 mini-batch 应用层归一化。
本层实现了论文 Layer Normalization 中描述的操作。
均值和标准差是根据 D 维计算的,其中 D 是
normalized_shape
的维度。例如,如果normalized_shape
是(3, 5)
(一个二维形状),则均值和标准差是根据输入的最后 2 维计算的(即input.mean((-2, -1))
)。如果elementwise_affine
为True
,则 和 是normalized_shape
的可学习仿射变换参数。方差是通过有偏估计量计算的,等同于 torch.var(input, unbiased=False)。注意
与 Batch Normalization 和 Instance Normalization 不同(它们在
affine
选项下为整个通道/平面应用标量缩放和偏差),Layer Normalization 在elementwise_affine
选项下应用逐元素缩放和偏差。此层在训练和评估模式下都使用从输入数据计算的统计量。
- 参数
normalized_shape (int 或 list 或 torch.Size) –
input shape from an expected input of size
If a single integer is used, it is treated as a singleton list, and this module will normalize over the last dimension which is expected to be of that specific size.
eps (float) – 为了数值稳定性添加到分母中的值。默认值:1e-5
elementwise_affine (bool) – 如果设置为
True
,则此模块将具有可学习的逐元素仿射参数,初始化为 1(权重)和 0(偏差)。默认值:True
。bias (bool) – 如果设置为
False
,则该层将不学习加性偏差(仅在elementwise_affine
为True
时才相关)。默认值:True
。
- 变量
weight – 当
elementwise_affine
设置为True
时,模块的可学习权重形状为 。值初始化为 1。bias – 当
elementwise_affine
设置为True
时,模块的可学习偏差形状为 。值初始化为 0。
- 形状
输入:
输出:(与输入形状相同)
示例
>>> # NLP Example >>> batch, sentence_length, embedding_dim = 20, 5, 10 >>> embedding = torch.randn(batch, sentence_length, embedding_dim) >>> layer_norm = nn.LayerNorm(embedding_dim) >>> # Activate module >>> layer_norm(embedding) >>> >>> # Image Example >>> N, C, H, W = 20, 5, 10, 10 >>> input = torch.randn(N, C, H, W) >>> # Normalize over the last three dimensions (i.e. the channel and spatial dimensions) >>> # as shown in the image below >>> layer_norm = nn.LayerNorm([C, H, W]) >>> output = layer_norm(input)