捷徑

LayerNorm

class torch.nn.LayerNorm(normalized_shape, eps=1e-05, elementwise_affine=True, bias=True, device=None, dtype=None)[來源][來源]

在小批量輸入上應用層正規化。

此層實作了 層正規化 論文中所述的操作。

y=xE[x]Var[x]+ϵγ+βy = \frac{x - \mathrm{E}[x]}{ \sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta

平均值和標準差是根據最後的 D 維度計算的,其中 Dnormalized_shape 的維度。例如,如果 normalized_shape(3, 5)(一個二維形狀),則平均值和標準差是根據輸入的最後 2 個維度計算的(即 input.mean((-2, -1)))。如果 elementwise_affineTrue,則 γ\gammaβ\betanormalized_shape 的可學習仿射轉換參數。變異數是透過有偏差的估計量計算的,相當於 torch.var(input, unbiased=False)

注意

與批次正規化 (Batch Normalization) 和實例正規化 (Instance Normalization) 不同,後者使用 affine 選項對每個完整的通道/平面應用純量比例和偏差,而層正規化 (Layer Normalization) 則使用 elementwise_affine 應用每個元素的比例和偏差。

此層在訓練和評估模式下都使用從輸入資料計算的統計資料。

參數
  • normalized_shape (int or list or torch.Size) –

    來自預期大小輸入的輸入形狀

    [×normalized_shape[0]×normalized_shape[1]××normalized_shape[1]][* \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_affineTrue 時才相關)。預設值:True

變數
  • weight – 當 elementwise_affine 設定為 True 時,模組的可學習權重,形狀為 normalized_shape\text{normalized\_shape}。這些值初始化為 1。

  • bias – 當 elementwise_affine 設定為 True 時,模組的可學習偏差,形狀為 normalized_shape\text{normalized\_shape}。這些值初始化為 0。

形狀
  • 輸入: (N,)(N, *)

  • 輸出: (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)
../_images/layer_norm.jpg

文件

取得 PyTorch 的完整開發者文件

檢視文件

教學

取得初學者和進階開發者的深入教學

檢視教學

資源

尋找開發資源並獲得問題解答

檢視資源