LayerNorm
- classtorch.nn.LayerNorm(normalized_shape, eps=1e-05, elementwise_affine=True, bias=True, device=None, dtype=None)[源代码]
- 
    对一批输入数据进行层归一化处理。 此层实现了《层归一化》论文中描述的操作。 $y = \frac{x - \mathrm{E}[x]}{ \sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta$均值和标准差是通过对最后一个D维度进行计算得出的,其中D是指 normalized_shape中的维度数量。例如,如果normalized_shape为(3, 5)(一个二维形状),则均值和标准差将通过输入的最后两个维度进行计算(即input.mean((-2, -1)))。如果elementwise_affine为True,则$\gamma$和$\beta$是normalized_shape的可学习仿射变换参数。标准差通过有偏估计器计算得出,等同于torch.var(input, unbiased=False)。注意 与批量归一化和实例归一化不同,当使用 affine选项时,批量归一化和实例归一化会对每个完整的通道/平面应用标量缩放和偏置,而层归一化则会使用elementwise_affine对每个元素分别应用缩放和偏置。此层在训练和评估模式下都会使用从输入数据中计算出的统计信息。 - 参数
- 
      - 
        normalized_shape (int 或 list 或 torch.Size) – 输入形状不符合预期的输入大小 $[* \times \text{normalized\_shape}[0] \times \text{normalized\_shape}[1] \times \ldots \times \text{normalized\_shape}[-1]]$如果使用单个整数,它会被视为一个包含这个整数的列表。此模块会在最后一个维度上进行归一化处理,而这个维度的大小应该与提供的整数值一致。 
- 
        eps (float) — 一个添加到分母的值,用于保证数值稳定性。默认值为 1e-5。 
- 
        elementwise_affine (bool) – 一个布尔值,当设置为 True时,此模块具有可学习的每个元素的仿射参数。权重初始化为1,偏差初始化为0。默认值:True。
- 
        bias (bool) – 如果设置为 False,层将不会学习加性偏置(仅在elementwise_affine为True时相关)。默认值:True。
 
- 
        
- 变量
- 
      - 
        weight – 模块的可学习权重,当 elementwise_affine设置为True时,其形状为$\text{normalized\_shape}$。初始值被设置为1。
- 
        bias — 模块的可学习偏置,形状为$\text{normalized\_shape}$,当 elementwise_affine设置为True时。初始值被设置为0。
 
- 
        
 - 形状:
- 
      - 
        输入: $(N, *)$ 
- 
        输出: $(N, *)$ (与输入的形状相同) 
 
- 
        
 示例: >>> # 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) 