层归一化 ¶
- class torch.nn.LayerNorm(normalized_shape, eps=1e-05, elementwise_affine=True, bias=True, device=None, dtype=None)[source][source]¶
在输入的小批量上应用层归一化。
此层实现了论文《层归一化》中描述的操作。
均值和标准差是在最后 D 维上计算的,其中 D 是
normalized_shape
的维度。例如,如果normalized_shape
是(3, 5)
(一个 2 维形状),则均值和标准差是在输入的最后 2 维上计算的(即input.mean((-2, -1))
)。当elementwise_affine
为True
时, 和 是normalized_shape
的可学习仿射变换参数。方差通过有偏估计器计算,相当于 torch.var(input, unbiased=False)。注意
与批量归一化和实例归一化不同,它们使用
affine
选项为每个整个通道/平面应用标量缩放和偏置,层归一化则应用每个元素的缩放和偏置elementwise_affine
。此层使用在训练和评估模式下从输入数据中计算出的统计数据。
- 参数:
normalized_shape (int 或 list 或 torch.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)