咖哩麵包人
    • 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 New
    • Engagement control
    • Make a copy
    • 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 Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy 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
    1
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    ###### tags: `ML數學分部` {%hackmd @kk6333/theme-sty1 %} # KL Divergence & CrossEntrophy 的真面目 :warning: 本文是看過眾多教學後,覺得最好理解的版本,如果有不嚴謹的地方歡迎指教 ~ --- 很多 ML 初學者(Me) 一定都有聽過 CrossEntrophy ,甚至知道他的計算原理 這邊有我看過的一篇文章講的還蠻好理解的 - ["文章連結"](https://r23456999.medium.com/%E4%BD%95%E8%AC%82-cross-entropy-%E4%BA%A4%E5%8F%89%E7%86%B5-b6d4cef9189d) 但本文想從另一個角度 KL Divergence 切回 CrossEntrophy 這樣可以更直觀看待 loss 的意義,且 Divergence 一詞在 GAN 也會常看到 (我也是遇到了才知道...) 先簡單提一下, Divergence 可以被看作是一種機率分布的"差異", KL Divergence 則是最基礎的 Divergence CrossEntrophy 其實就是 KL Divergence 的變形。 <br> ## 1. KL Divergence 這邊用一個簡單的例子來說明 KL Divergence :::warning example - 有兩硬幣,出現正反面的機率各不相同 - coin-1 : (H)正面機率 = $p_1$ 、(T)負面機率 = $p_2$ - coin-2 : (H)正面機率 = $q_1$ 、(T)負面機率 = $q_2$ ::: **Step1.** > 假設今天連續丟好幾次硬幣的情況是 (正,正,反,反) 機率如下 (Observation 為某種情況) > - coin-1 : $P( Observation|coin1 ) = p_1*p_1*p_2*p_2$ > - coin-2 : $P( Observation|coin2 ) = q_1*q_1*q_2*q_2$ **Step2.** > 所以我們推導出在某種 Observation $P$ 可以寫成以下式 > 並且我們可以 Observation 就是丟出某種硬幣情況的"**機率分布 Distribution**" > > - coin-1 : $P( Observation|coin1 ) = p_1^{N_H}*p_2^{N_T}$ > - coin-2 : $P( Observation|coin2 ) = q_1^{N_H}*q_2^{N_T}$ > > ( $N$ : 丟的次數、$N_H$ : 正面次數、$N_T$ : 負面次數 ) **Step3.** > 之後計算兩個 Distribution 的比例 (Observation 簡稱 Obs) > > $\frac{P( Obs|coin1 )}{P( Obs|coin2 )}=\frac{p_1^{N_H}*p_2^{N_T}}{q_1^{N_H}*q_2^{N_T}}$ **Step4.** > 將此比例正規化 ( 開根號 ),並取 log ( 比例是不變的所以可以這樣操作 ) > > $log( \frac{p_1^{N_H}*p_2^{N_T}}{q_1^{N_H}*q_2^{N_T}} )^{\frac{1}{N}}$ > > 提出 $\frac{1}{N}$ 並拆解 log > > $\frac{N_H}{N}log(p_1) + \frac{N_T}{N}log(p_2) - \frac{N_H}{N}log(q_1) - \frac{N_T}{N}log(q_2)$ **Step5. 算出 KL Divergence** > 現在我們以 coin-1 作為觀察(observe)到的對象 ( 真實分布 ), > coin-2 則是根據機率得出的分布 ( 理論分布 ) > 會符合以下關係 ( 就是 coin-1 正反面出現機率 ) > > $\frac{N_H}{N}=p_1$、$\frac{N_T}{N}=p_2$ > > 有了此關係就可以改寫 Step4 的式子 > > $p_1log(p_1) + p_2log(p_2) - p_1log(q_1) - p_2log(q_2)$ > > 再整理一下可得 > > $p_1log( \frac{p_1}{q_1} ) + p_2log(\frac{p_2}{q_2}) = D_{KL}( P || Q )$ > > 這個就是在 Coin-1 為觀察對象的 KL Divergence **Step6. Summary** > 在其他狀況中會有更多不同分布,寫成 > > $D_{KL}( P || Q )=\sum_i{P(i)log(\frac{P(i)}{Q(i)})}$ > > KL Divergence 真正的意義就是兩機率分布的比例 (Step3) > 我們可以稱這個比例為 "距離" > 當兩 Distribution 相同時 $D_{KL}$ 會為 0 > 而差距越大 $D_{KL}$ 會越大 > > **特性** : > - 不對稱性 : 如果今天觀察對象調換,$D_{KL}(Q||P) \neq D_{KL}(P||Q)$ > :::info **KL-Divergence 公式** $$D_{KL}( P || Q )=\sum_i{P(i)log(\frac{P(i)}{Q(i)})}$$ ::: ![](https://i.imgur.com/ACJ9R5p.png =500x400) --- <br> ## 2. CrossEntrophy 剛剛講完 KL Divergence,我們知道可以用來量測兩機率分佈的"差異性" CrossEntrophy 更直觀的把他用在計算"**實際資料**"與"**預測資料**"分佈的差異上 > 設 Data 的分佈如下 > - 實際資料 ( label ) 分佈 : $P^* (y|x_i)$ > - 預測資料分佈 : $P (y|x_i;\theta)$ > > ( $x_i$ : input、 $\theta$ : model 參數 ) 接著要計算 Data 間的差異,也就是 KL Divergence > $D_{KL}(P^* || P)=\sum_i{P^*log(\frac{P^*}{P})}$ > > 化減 > > $D_{KL}(P^* || P)=\sum_i{P^*log(P^*)} - \sum_i{P^*log(P)}$ > > 這就是預測與實際 y 的差距 因為我們之後會想要所小差距,使預測更接近實際結果 所以任務會是最小化 $D_{KL}$ > 任務寫成此式 > > $min ( \sum_i{P^*log(P^*)} - \sum_i{P^*log(P)} )$ > > 但 $\sum_i{P^*log(P^*)}$ 是實際資料產生的,無法做變動 ( 只能變動 model 參數 ) > 所以可將任務縮減 > > $min (- \sum_i{P^*log(P)})$ **Summary** > 所以 CrossEntrophy 寫成如下 > > $CrossEntrophy = - \sum_i{P^*log(P)}$ > > 目的就是要縮小預測與實際結果差距 ! :::info **Cross Entrophy 公式** $$CrossEntrophy = - \sum_i{P^*log(P)}$$ > - 實際資料分佈 : $P^*$ > - 預測資料分佈 : $P$ ::: --- <br> ## 3. CrossEntrophy & Softmax 關係 在知道 CrossEntrophy 與 KL Divergence 後, 可以很簡單就理解為什麼 CrossEntrophy 前都要用 Softmax 了 > 因為要計算 CrossEntrophy 我們公式中式要求"機率分布" > 而 Softmax 剛好就能使輸出的分類 y 轉為機率 > 將值保留在 [0-1],且 p 總合為 1 > > 補充 : 在還沒轉為機率前的 y 我們習慣叫他 logits ! --- <br> ## 4. Reference - [Intuitively Understanding the KL Divergence](https://www.youtube.com/watch?v=SxGYPqCgJWM) - [Intuitively Understanding the Cross Entropy Loss](https://www.youtube.com/watch?v=Pwgpl9mKars) - [相對熵-維基百科](https://zh.wikipedia.org/wiki/%E7%9B%B8%E5%AF%B9%E7%86%B5) - [何謂 Cross-Entropy (交叉熵)](https://r23456999.medium.com/%E4%BD%95%E8%AC%82-cross-entropy-%E4%BA%A4%E5%8F%89%E7%86%B5-b6d4cef9189d) - [剖析深度學習:你知道Cross Entropy和KL Divergence代表什麼意義嗎?](https://www.ycc.idv.tw/deep-dl_2.html)

    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