LayerNorm#
- class torch.nn.LayerNorm(normalized_shape, eps=1e-05, elementwise_affine=True, bias=True, device=None, dtype=None)[原始碼]#
對輸入 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)