Vic
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # LayerNorm v.s. BatchNorm ![image](https://hackmd.io/_uploads/H1ARHaKYkx.png) 1. Layer Normalization(層歸一化) 2. Batch Normalization(批次歸一化) 都是深度學習中的 **正規化(Normalization)技術**,它們可以 **加速模型訓練、穩定梯度、提高收斂速度**,但在 **適用場景** 和 **計算方式** 上有所不同。 --- ## **Batch Normalization(BN)** Batch Normalization 是 **針對一個批次(Batch)內所有樣本的相同dimension** 進行Normalization,使該維度的輸出均值為 0,標準差為 1。 ### **BatchNorm formula** 假設神經網路輸入為: $$ X = [x_1, x_2, ..., x_B] $$ 其中 $B$ 為 **Batch Size**。 對於每個 mini-batch,計算: 1. **均值(Mean)**: $$ \mu_B = \frac{1}{B} \sum_{i=1}^{B} x_i $$ 2. **標準差(Standard Deviation)**: $$ \sigma_B^2 = \frac{1}{B} \sum_{i=1}^{B} (x_i - \mu_B)^2 $$ 3. **正規化(Normalization)**: $$ \hat{x}_i = \frac{x_i - \mu_B}{\sqrt{\sigma_B^2 + \epsilon}} $$ 4. **學習可調參數**: $$ y_i = \gamma \hat{x}_i + \beta $$ - $\gamma$(scale):學習到的縮放參數 - $\beta$(shift):學習到的平移參數 - $\epsilon$ 是小數值,防止除零錯誤 ### **🔹 直覺解釋** - BatchNorm 會根據一個 batch 的均值和標準差,將該 batch 內的數據縮放到標準正態分佈。 - 然後再通過 $\gamma$ 和 $\beta$ 進行調整,確保模型能學習適當的數值範圍。 ### **pros** ✅ **加速收斂**,減少內部共變異轉移(Internal Covariate Shift) ✅ **能夠提高學習率,避免梯度消失或爆炸** ✅ **適用於 CNN**,特別是 ResNet、VGG、EfficientNet 等 ### **cons** ❌ **對 Batch Size 敏感**(Batch 太小時,均值和方差估計不準確) ❌ **在 NLP 中效果較差**(因為 NLP 的句子長度不同,BatchNorm 無法有效應用) ### **PyTorch** ```python import torch import torch.nn as nn # 針對 2D 輸入 (適用於 CNN) batch_norm = nn.BatchNorm2d(num_features=64) # 64 個通道 x = torch.randn(32, 64, 28, 28) # (batch_size, channels, height, width) output = batch_norm(x) ``` --- ## **Layer Normalization(LN)** Layer Normalization 是 **針對單個樣本的所有神經元維度** 進行正規化,使每個樣本的輸出均值為 0,標準差為 1。 ### **LayerNorm formula** 對於單個樣本 $x$,計算: 1. **均值**: $$ \mu_L = \frac{1}{N} \sum_{i=1}^{N} x_i $$ 2. **標準差**: $$ \sigma_L^2 = \frac{1}{N} \sum_{i=1}^{N} (x_i - \mu_L)^2 $$ 3. **正規化**: $$ \hat{x}_i = \frac{x_i - \mu_L}{\sqrt{\sigma_L^2 + \epsilon}} $$ 4. **學習可調參數**: $$ y_i = \gamma \hat{x}_i + \beta $$ ### **🔹 直覺解釋** - LayerNorm 是對 **每一個樣本的所有神經元** 進行正規化,而不是針對整個 batch。 - 這樣可以確保即使 batch size 很小,或者輸入是變長序列(如 NLP),也不會影響正規化效果。 ### **pros** ✅ **不依賴 Batch Size**,適合變長輸入(NLP) ✅ **適用於 Transformer(BERT, GPT, T5)** ✅ **適合 RNN、LSTM 等序列模型** ### **cons** ❌ **在 CNN 上效果不如 BatchNorm**(因為 CNN 需要 batch-wise 統計資訊) ❌ **計算成本稍高**(因為它需要針對每個樣本計算均值和標準差) ### **PyTorch** ```python import torch import torch.nn as nn # 針對 5 維輸入 (適用於 Transformer) layer_norm = nn.LayerNorm(normalized_shape=512) # 512 維輸入 x = torch.randn(32, 512) # (batch_size, feature_dim) output = layer_norm(x) ``` --- ## **3. BatchNorm vs. LayerNorm 的關鍵區別** | 特性 | **Batch Normalization(BN)** | **Layer Normalization(LN)** | |------|----------------------|----------------------| | **計算方式** | 在一個 batch 內對每個特徵歸一化 | 在單個樣本內對所有特徵歸一化 | | **適用場景** | CNN(ResNet, VGG, EfficientNet) | NLP(Transformer, RNN, LSTM) | | **是否受 Batch Size 影響** | ✅ 受影響 | ❌ 不受影響 | | **是否適用於變長序列** | ❌ 不適用 | ✅ 適用 | | **是否能加速訓練** | ✅ 是 | ✅ 是 | | **是否適用於 Self-Attention** | ❌ 不適用 | ✅ 適用 | | **對小 Batch Size 是否穩定** | ❌ 可能不穩定 | ✅ 穩定 | --- ## **4. 何時使用 BatchNorm vs. LayerNorm?** ✅ **使用 BatchNorm(BN)** **→ CNN(ResNet, VGG, MobileNet, EfficientNet)** - 適合影像處理,因為 CNN 具有空間維度的特性 - 適合大 Batch Size,能提高訓練速度 ✅ **使用 LayerNorm(LN)** **→ NLP(Transformer, BERT, GPT, T5, LSTM, RNN)** - 適用於變長輸入,如 NLP、對話系統、機器翻譯 - 在 **Transformer(Self-Attention 機制)** 中是標準做法 - 適合小批量(Batch Size 小於 32) --- ## **5. 進階問題** ### **Q1: 為什麼 Transformer 使用 LayerNorm,而不是 BatchNorm?** - Transformer 主要應用於 **NLP**,批次中的序列長度可能不同,BatchNorm 無法有效處理變長序列,而 LayerNorm 針對 **單個樣本** 進行歸一化,能穩定學習。 - Self-Attention 機制是高度依賴層輸出的,如果 BatchNorm 改變了不同批次的特徵分佈,可能會影響學習。 ### **Q2: 為什麼 CNN 更適合 BatchNorm,而不是 LayerNorm?** - CNN 的特徵來自 **卷積操作(Convolution)**,它在 **通道維度** 進行學習,BatchNorm 可以利用 **批次內的統計資訊** 來加速學習。 - LayerNorm 無法利用 **批次內的統計特性**,因此效果通常不如 BatchNorm。 --- ## **6. 總結** | **問題** | **BN(BatchNorm)** | **LN(LayerNorm)** | |----------|----------------|----------------| | **適用場景** | CNN(影像處理) | NLP(Transformer, RNN) | | **是否受 Batch Size 影響** | ✅ 是 | ❌ 否 | | **是否適用於變長輸入** | ❌ 否 | ✅ 是 | ✅ **CNN → BatchNorm** ✅ **Transformer → LayerNorm** 🚀 ## Ref https://blog.csdn.net/Little_White_9/article/details/123345062

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully