孟軒
    • 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
    • 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 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
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # 機器學習2021 中文版 筆記 :::info 本文內容以李宏毅教授 【機器學習2021】(中文版) 為主,搭配參考資料編輯而成。 使用圖片出自 【機器學習2021】(中文版) 課程講義 [課程網站 - Machine Learning 2021](https://speech.ee.ntu.edu.tw/~hylee/ml/2021-spring.html) [【機器學習2021】(中文版)](https://youtube.com/playlist?list=PLJV_el3uVTsMhtt7_Y6sgTHGHp1Vb2P2J&si=C3UmtZJOYRvFv7fi) ::: <br/><br/> ## [1]預測本頻道觀看人數(上) - 深度學習基本概念簡介 **Machine Learning :** Looking for Function (藉由機器自動找出複雜的函式) ; 從資料中找出規則 <br/> **機器學習"任務種類"** 1. **Regression(回歸) :** The function outputs a scalar. 探討自變數(x)與依變數(y)之間的線性關係,透過迴歸模型,可以推論和預測研究者感興趣的變數(y)。 2. **Classification(分類) :** Given options (classes), the function outputs the correct one. 3. **Structured Learning :** create something with structure (image, document). <br/> **機器學習"訓練步驟"** 1. **定義問題(Define Function with Unknown Parameters) :** Given network structure, define a function set. A function (model) with unknown parameters, feature, weight, bias. 1-1 函數的設計 base on domain knowledge 1-2 Model 是帶有未知參數的函式 1-3 已知資訊:feature、跟feature相乘的:weight、相加的:bias 2. **定義Loss Function(Define Loss from Training Data) :** 2-1 用來評估目前模型的參數有多好。 2-2 一個函數,輸入為 Model 的參數,Loss function 中的 loss 是「實際值和預測值的殘差」,用來估計模型的好壞。(loss function 損失函數, cost function 成本函數) 2-3 計算方法例如:mean absolute error(MAE)、mean square error(MSE)、cross entropy。 [機器/深度學習: 基礎介紹-損失函數(loss function)](https://chih-sheng-huang821.medium.com/%E6%A9%9F%E5%99%A8-%E6%B7%B1%E5%BA%A6%E5%AD%B8%E7%BF%92-%E5%9F%BA%E7%A4%8E%E4%BB%8B%E7%B4%B9-%E6%90%8D%E5%A4%B1%E5%87%BD%E6%95%B8-loss-function-2dcac5ebb6cb) 3. **最佳化 Optimization :** 找到使 Loss 最小的參數值,例如 Gradient Descent 方法。 <br/> **梯度下降(Gradient Descent) :** 根據斜率改變參數,找 local min。 以一個參數(w)舉例: 1. (Randomly) Pick an initial value w0 2. Compute ∂L/∂w => 切線斜率 3. Update w iteratively <br/> **超參數(hyperparameter) :** 需要自己設定的參數,例如學習速率(梯度下降時的步伐大小)、更新參數的次數。 <br/><br/><br/> ## [2]預測本頻道觀看人數(下) - 深度學習基本概念簡介 **Linear models** -> 太過簡單,可能無法模擬出需要的函數模型,產生較大的 Model Bias. <br/> **Model bias** 來自於 model 的限制、由 model 所造成的誤差。refers to the presence of systematic errors in a model that can cause it to consistently make incorrect predictions. These errors can arise from many sources, including the selection of the training data, the choice of features used to build the model, or the algorithm used to train the model. <br/> **piecewise linear curve :** 1. 一個 curve 由很多線段所組成; a connected sequence of line segments. 2. 非 linear curve 的 function 可取很多點,成為 linear function ; Approximate continuous curve by a piecewise linear curve. ![螢幕擷取畫1](https://hackmd.io/_uploads/By2vag-f0.png =50%x) <br/> **激勵函數(Activation Function) :** ++利用非線性方程式,解決非線性問題 :++ 若不使用激勵函數,類神經網路是以線性的方式組合運算,因為隱藏層以及輸出層皆是將上層之結果輸入,並以線性組合計算,作為這一層的輸出,使得輸出與輸入只存在線性關係,而現實中的問題皆屬於非線性問題,若無使用非線性之激勵函數,類神經網路訓練之模型便失去意義。 為了減少線性程度,使類神經網路的分析結果可以更準確,因此使用激勵函數(Activation Function),以增加類神經網路訓練時的非線性程度。 常被使用的激勵函數包含 ReLU, SeLU, Softmax, Sigmoid [ 激勵函數(Activation Function) - ithome](https://ithelp.ithome.com.tw/m/articles/10304438) [深度學習激勵函數介紹](https://cvfiasd.pixnet.net/blog/post/275774124-%E6%B7%B1%E5%BA%A6%E5%AD%B8%E7%BF%92%E6%BF%80%E5%8B%B5%E5%87%BD%E6%95%B8%E4%BB%8B%E7%B4%B9) **S型函數(Sigmoid Function) :** y = c sigmoid( b + wx ) **ReLU (Rectified Linear Unit) :** y = c max( 0, 𝑏 + wx ) 這段太難記,參考別人的 [連結](https://blog.csdn.net/cmehppc/article/details/128529945?utm_medium=distribute.pc_relevant.none-task-blog-2~default~baidujs_baidulandingword~default-0-128529945-blog-115052326.235^v43^pc_blog_bottom_relevance_base8&spm=1001.2101.3001.4242.1&utm_relevant_index=1) **更新寫法 :** 用 θ 表示所有的參數,則 Loss Function 可表示成 L(θ)。θ 是一個很長的向量 (θ1, θ2, θ3, ... ),此時,目標就是找一組 θ 使 loss 最小,稱這組 θ 為 θ*。 1. 一開始隨機選一個初始值 θ0。 2. 接著計算微分,對每一個未知的參數 (θ1, θ2, θ3, ... ) 計算它對 L 的微分。把每一個參數都對 L 微分後,組合成一個向量 g。這邊假設有 1000 個參數,這個向量g的長度就是1000,這個向量稱為 Gradient(梯度)。Gradient 的表示方法是在 L 前面放一個倒三角形,代表這是一個 Gradient。 3. 算出 g 以後,需要 Update 參數,本來有一個參數叫 θ1,上標 0 代表它是一個起始的值,把 θ10 減掉 η 乘上微分的值,得到 θ11,代表 θ1 更新過一次的結果。θ20 減掉微分乘以,減掉 η 乘上微分的值,得到 θ21。以此類推,你就可以把那 1000 個參數都更新。總的來說,所有的 θ 合起來當做一個向量,我們用 θ0 來表示,設定 η ,每一個參數對 L 微分的叫做 g(Gradient),所以 θ0減掉 η 乘上 g,就得到 θ1 ![螢幕擷取畫面 2024-05-02 202837](https://hackmd.io/_uploads/rysgK-bfA.png =55%x) ![螢幕擷取畫面 2024-05-02 202845](https://hackmd.io/_uploads/BJ9ZYb-GA.png =40%x) **update :** 更新一次參數稱為一次 update。 **Iteration :** 使用一個 Batch 資料進行一次參數更新的過程,被稱為"一次訓練",或"一次迭代" **epoch :** 把所有的 Batch 看過一遍 ; 訓練模型過程裡,演算法完整使用過資料集每筆資料的狀態。 **Batch size :** 假設 10 筆資料,每筆數據量都很大,電腦因為記憶體不夠,無法一次跑 10 筆。這時我們把 10 筆資料分批送進神經網路,這裡分批的數量就是 Batch size,今天我一次放 2 筆資料進神經網路運算,那 Batch size 就等於 2。 ![screenshot](https://hackmd.io/_uploads/S16VUOu-1g.png =55%x) [Epoch, Batch size, Iteration, Learning Rate - medium](https://medium.com/%E4%BA%BA%E5%B7%A5%E6%99%BA%E6%85%A7-%E5%80%92%E5%BA%95%E6%9C%89%E5%A4%9A%E6%99%BA%E6%85%A7/epoch-batch-size-iteration-learning-rate-b62bf6334c49) [AI不惑境 学习率和batchsize如何影响模型的性能?](https://zhuanlan.zhihu.com/p/64864995) [神经网络中Epoch、Iteration、Batchsize相关理解和说明 - csdn](https://blog.csdn.net/program_developer/article/details/78597738) [梯度最佳解相關算法(gradient descent optimization algorithms) - medium](https://medium.com/@chih.sheng.huang821/%E6%A9%9F%E5%99%A8%E5%AD%B8%E7%BF%92-%E5%9F%BA%E7%A4%8E%E6%95%B8%E5%AD%B8-%E4%B8%89-%E6%A2%AF%E5%BA%A6%E6%9C%80%E4%BD%B3%E8%A7%A3%E7%9B%B8%E9%97%9C%E7%AE%97%E6%B3%95-gradient-descent-optimization-algorithms-b61ed1478bd7) <br/> ![螢幕擷取畫面 2024-01-27 120948](https://hackmd.io/_uploads/SJHbmiM5p.png) 每一個圓圈代表一個 neuron,一定數量的 neuron 就會構成一個 layer,整體網路稱為 Neural Network 當資料輸入進來後,會通過第一層 layer,輸出的結果再輸入到第二層 layer,以此類推直到得到最後的結果。 而接收輸入資料的 layer 叫做 input layer,輸出結果的 layer 叫做 output layer,中間連接的 layer 叫做 hidden layer。 [機器學習_學習筆記系列(99):神經網絡(Neural Network)](https://tomohiroliu22.medium.com/%E6%A9%9F%E5%99%A8%E5%AD%B8%E7%BF%92-%E5%AD%B8%E7%BF%92%E7%AD%86%E8%A8%98%E7%B3%BB%E5%88%97-99-%E7%A5%9E%E7%B6%93%E7%B6%B2%E7%B5%A1-neural-network-1e7177542995) <br/> ![螢幕擷取畫面](https://hackmd.io/_uploads/rkbvzSJia.png) layer, input layer, output layer, hidden layer 圖示 <br/> **Error Surface :** graphical representations of the relationship between the model’s parameters and the corresponding error values. [Error & Error Surface: Explore The Terrain of Errors and Error Surfaces in Deep Learning](https://medium.com/@HeCanThink/error-error-surface-explore-the-terrain-of-errors-and-error-surfaces-in-deep-learning-d1d17b4a382) <br/><br/><br/> ## [3]機器學習任務攻略 **Framwork of ML** 訓練資料訓練 Model 的3階段 1.寫出有未知數的 Function,未知數為 seta(所有未知數的統稱) 2.定義一個 loss function 3.optimization,讓 loss 最小,得 seta*,用 seta* 帶入模型函數,將 test data 輸入 <br/> **將訓練做的更好?** ![screenshot](https://hackmd.io/_uploads/rkNdFNG5T.png) 先檢查++訓練資料++的 loss loss 小→ok 若loss 太大→兩種可能 1.model bias 2.optimization Issue <br/> #### **1.Model Bias** 因為model太簡單→大海撈針但針不在海裡→需要一個更大的model,增加model的彈性 (redesign your model to make it more flexible) 解法1:增加更多 feature (增加資料量) 解法2:用 deep learning <br/> #### **2.Optimization Issue** 使用 Gradient Descent 找不到→大海撈針,撈不到 <br/> **Model Bias v.s. Optimization Issue** 找不到 loss 低的 function 是因為 model 的彈性不夠還是 model 彈性足夠但 Optimization 方法(如Gradient Descent)不夠力? ![螢幕擷取畫面 2024-01-27 201617](https://hackmd.io/_uploads/H1wNVdM56.png) =>此圖說明 56 層的 network 的 optimization 沒做好 If deeper networks do not obtain smaller loss on training data, then there is optimization issue. 先用簡單的model來做訓練,再做深的model,發現loss,深>淺→optimiaztion Issue 56層 v.s. 20層 的測試資料,20層的loss<56層的loss ++56層 v.s. 20層 的訓練資料,20層的loss<56層的loss++ 因為在訓練時,越深/複雜的model應該要越契合訓練資料,甚至會overfitting,所以訓練資料的loss應該:深<淺 [Deep Residual Learning for Image Recognition](https://arxiv.org/abs/1512.03385) 訓練資料的loss已經足夠小→檢查測試資料的loss loss小→ok loss大→兩種可能 1.overfitting 2.mismatch #### **1.Overfitting** ![螢幕擷取畫面](https://hackmd.io/_uploads/SystOOG5a.png) 缺乏應變能力,只契合訓練資料,在測試資料上會失準。 過度學習訓練資料,變得無法順利去預測或分辨不是在訓練資料內的其他資料 [[機器學習 ML NOTE]Overfitting - medium](https://medium.com/%E9%9B%9E%E9%9B%9E%E8%88%87%E5%85%94%E5%85%94%E7%9A%84%E5%B7%A5%E7%A8%8B%E4%B8%96%E7%95%8C/%E6%A9%9F%E5%99%A8%E5%AD%B8%E7%BF%92-ml-note-overfitting-%E9%81%8E%E5%BA%A6%E5%AD%B8%E7%BF%92-6196902481bb) 解法 1.增加訓練資料量 1.a.尋找新的資料 1.b.Data augmentation→對現有資料做更動,變成新的資料 Data augmentation [回顧Data Augmentation技巧](https://medium.com/learn-with-machine/paper-reading-a-survey-on-image-data-augmentation-for-deep-learning-b75bf3b3a688) 2.給model一些限制,最好是跟問題、題目要求有關的限制。e.g.已知題目可能會是2次曲線,就把model限制在2次;給模型太大的限制→可能會回到Model Bias的問題 給比較少的資料 Less parameters, sharing parameters Less features Early stopping Regularization Dropout 模型的複雜程度與彈性 複雜模型:包含的function、參數比較多 越複雜,訓練loss越低,但會overfitting,測試loss高 **怎麼選擇好的model?** 把訓練集分成訓練集&驗證集 N-fold Cross Validation ![螢幕擷取畫面 2024-01-27 204653](https://hackmd.io/_uploads/S1FDi_Mc6.png) 分三份,每份都分兩份訓練&一份驗證,與model交叉測試 <br/> #### **2.Mismatch** training and testing data have different distributions. 當訓練資料跟測試資料不一樣時,訓練資料的品質就不重要了。e.g.訓練資料是彩色真實動物圖片,測試資料是黑白卡通動物圖騰。 <br/><br/><br/> ## [4]類神經網路訓練不起來怎麼辦 (一): 局部最小值 (local minima) 與鞍點 (saddle point) ### 本節討論Optimization時,如何把Gradient descent做好 (LF、L(Θ)指Loss Function) (Θ=未知數的集合) #### 發現gradient = 0 (遇到critical point) ![image](https://hackmd.io/_uploads/r1V4EQWGR.png =50%x) 當model訓練不起來,一開始 training data loss就很高 → Optimization失敗 → 猜測遇到 LF gradient = 0的地方。 - gradient = 0有兩種情況 1. local minima,局部最小值 2. saddle point,鞍點 使 gradient 為 0 的情況統稱為 critical point,需分辨 critical point 的情況是哪一種,才可決定接下來要做的處理。 #### 區別 local minima or saddle point 怎麼知道是 local minima 還是 saddle point? L(Θ)很複雜無法完整知道,但給定一組參數Θ',Θ'附近的 LF 有辦法被寫出來,可用Tayler Series Approximation 表示 ![螢幕擷取畫面 2024-01-28 105602](https://hackmd.io/_uploads/HkPwGBX5T.png) 此函數共有三項 1. 第一項:L(Θ'),當Θ跟Θ'相近時,L(Θ)與L(Θ')也相近 2. 第二項:(Θ-Θ')的轉置矩陣乘上gradient向量g,此g用來彌補Θ與Θ'的差距,g=▽L(Θ') gi=Θi對L(Θ')的微分 3. 第三項:(Θ-Θ')的轉置矩陣乘上H,再乘以(Θ-Θ'),用以補足第二項未足夠的Θ與Θ'的差距,H為Hessian是一個矩陣,為L的二次微分 L(Θ)在Θ'附近可寫成一個跟gradient、Hessian有關的一個式子,而gradient與一次微分有關,Hessian與二次微分有關 在一個critical point,意味著gradient為0→第二項(綠色)為0,因此用第三項(紅色)來判斷error surface,藉此知道critical point是哪種情況 ![螢幕擷取畫面 2024-02-06 150603](https://hackmd.io/_uploads/Syh5cL1sp.png) **如何根據Hessian來判斷?** (v表示Θ-Θ') 設v為任何值 1. v的轉置矩陣Hv > 0 → Around Θ' : L(Θ)>L(Θ') →代表L(Θ') 是最低點 → Local minima 2. v的轉置矩陣Hv < 0 → Around Θ' : L(Θ)<L(Θ') →代表L(Θ') 是最高點 → Local maxima 3. v的轉置矩陣Hv 有時>0有時<0 → L(Θ)有時>有時<L(Θ') → 代表L(Θ') 附近有些地方高有些地方低 → saddle point 不可能真的嘗試所有的v,更簡便的方法:**線性代數理論** 1. 對所有的v而言,v的轉置矩陣Hv > 0 →H為positive definite矩陣,其特性為eigenvalue都是正數 →觀察H的eigenvalue是不是全都正數,便可知道v的轉置矩陣Hv是否>0 →Local minima 2. 對所有的v而言,v的轉置矩陣Hv < 0 →H為negative definite矩陣,其特性為eigenvalue都是負數 →觀察H的eigenvalue是不是全都負數,便可知道v的轉置矩陣Hv是否<0 →Local maxima 3. 對所有的v而言,v的轉置矩陣Hv有時>0有時<0 →觀察H的eigenvalue是不是有正有負 →Saddle point 結論 : 只要算出Hessian這個矩陣,並且觀察其eigenvalue,便可知道現在的Critical point是什麼情況 #### 範例(實際案例說明) 一個Network : y = w1 w2 x (只有兩個參數w1、w2) 一個Training data set,只有1筆data:輸入跟輸出都是1 窮舉w1和w2來畫出Error Surface,圖像化來看哪邊有Critical Point,並觀察哪些是saddle point哪些是Local minima **不窮舉如何看出來?** 把LF寫出來,L=(y_hat-w1w2x)^2 = (1-w1w2)^2 求 (w1, w2) = (0, 0),此點是什麼情況? 1. 求Gradient,並將w1=0, w2=0代入,發現gradient = 0 (遇到critical point) 2. 接著求Hessian,為一個2維矩陣,有四個式子,w1=0, w2=0代入,可得4個式子答案分別是0,-2,-2,0,求eigenvalue,可發現其為2與-2 → 因此此點為saddle point ![螢幕擷取畫面 2024-01-28 113913](https://hackmd.io/_uploads/BJ5thHXc6.png) <br/> Don't afraid of saddle point 如果是卡在鞍點,可以放心,因為H會告訴我們參數update的方向 運算量其實非常大,實作上不實用,通常視為最終手段 ==(線性代數需要複習)== #### Saddle Point v.s. Local Minima誰比較常見? STORY:能進入四維空間的狄奧倫娜 會不會我們發現的Critical Point,在其他維度空間,是有其他路可以走的呢? ![螢幕擷取畫面 2024-01-30 234019](https://hackmd.io/_uploads/B1bWTUyia.png) 實際例子 點:一個 network 縱軸:訓練時的Loss值 橫軸:Minimun ration,Hessian 矩陣中 Eigenvalue 數目分之正的 Eigenvalue數目 實作時,通常Eigenvalue都是有正有負,代表很少有Network真的走到Local minima,通常都是卡在Saddle Point. <br/><br/><br/> ## [5]類神經網路訓練不起來怎麼辦 (二): 批次 (batch) 與動量 (momentum) 遇到 Small Gradient 時的解決方法 ### Batch #### 介紹 實際上在算微分時,是把 Data 分成一個個的 Batch,分別對這些 Batch 的資料算loss, gradient 及做 update,不會拿所有的資料來算 loss,而是一次看一個Batch。 Batch Size 越大,代表裡面資料越多 Batch Size 越小,代表裡面資料越少 看過所有 Batch 1 次 = 1 Epoch 在分資料成 batch 時會先做 Shuffle,常見的作法是在每一個 Epoch 開始時重新分一次 Batch。 **Shuffle** 哪些資料在哪一個 Batch 裡面,都是不一樣的事情。 [机器学习,深度学习模型训练阶段的Shuffle重要么](https://blog.csdn.net/qq_19672707/article/details/88864207) [Lesson 1.4 Data Shuffling](https://deci.ai/course/data-shuffling/) #### 為什麼訓練時要用Batch? - 記憶體限制:訓練大型模型時,整個數據集可能無法一次性載入到記憶體中。使用批次處理可以有效管理記憶體使用,只將一小部分數據加載到記憶體中進行計算。 - 靈活性和學習率調整:使用批次訓練,可以更靈活地調整學習率和其他超參數,如逐步降低學習率(學習率退火),以幫助模型更好地收斂。 #### Small Batch v.s. Large Batch -- 計算時間 ![螢幕擷取畫面 2024-01-28 193239](https://hackmd.io/_uploads/HJ23shmqT.png) 兩個範例: 左邊:大的Batch,全部資料當一個Batch,看完所有資料才update一次,更新穩定但需要較長時間 右邊:小的Batch,1個資料當一個Batch,看完一個資料就update一次,更新快速但較不穩定 **考慮有平行運算 : 此時時間取決於一個epoch update 幾次參數** - 平行運算是指 : 在計算 gradient 時可以平行做,因此影響時間的因素主要取決於 update 次數,而非 batch 大小。(在平行運算量未超過硬體極限的情況下) - Larger batch size does not requires longer time to compute gradient (unless batch size is too large) - Smaller batch requires longer time for one epoch (longer time for seeing all data once) ![screenshot](https://hackmd.io/_uploads/Sy2cpQZfC.png =75%x) 60000筆資料: Batch Size設1,要60000次update跑完一次Epoch Batch Size設1000,要60次update跑完一次Epoch (左圖:拿一個Batch,計算一次參數,Update一次所需的時間) 可以發現Batch Size為1至1000,所花的時間都差不多,因為GPU進行平行運算,因此Batch Size為1000的運算時間,不會比Batch Size為1的運算時間多1000倍 但是可以觀察到當Batch Size很大很大的時候,時間還是會增加 (右圖:跑完一個Epoch所需的時間) 因為Batch Size設1、Batch Size設1000所需的時間差不多,那6000次update跟60次update比起來,差距就相當可觀 因此Batch Size update一次的時間,和一次Epoch的時間,趨勢圖是相反的 Batch Size越小:一次update很快,但因為要update次數多,跑一次Epoch愈慢 Batch Size越大:一次update很慢,但因為要update次數少,跑一次Epoch愈快 **結論:** 無平行運算時,大的Batch比較慢 有平行運算時,大的Batch比較快 <br/> #### Small Batch v.s. Large Batch -- 結果好壞 **Noisy的Gradient有幫助** ![screenshot](https://hackmd.io/_uploads/HktwkVZfC.png =80%x) 在MNIST及CIFAR-10模型上做實驗,發現兩者都是「當Batch Size越大,訓練結果越差」。 → 同樣的模型,Function相同,大的Batch結果差,不是Model Bias問題 → 在Training上就有問題,所以不是Overfitting,是Optimization問題 **Training時,小的Batch Size有比較好的結果** Full Batch容易卡住(gradient = 0) Small Batch每一次update的LF都是有差異的(是此Batch的LF),可能Batch1的LF會卡住,但Batch2的LF不會卡住 → Noisy的Gradient有幫助 ![螢幕擷取畫面 2024-02-08 165202](https://hackmd.io/_uploads/BJPDLMfjp.png) <br/> **Testing時,小的Batch有幫助** 實際案例看出,訓練時小Batch跟大Batch都達到幾乎一樣的結果,但測試階段小Batch表現較好 ![螢幕擷取畫面 2024-02-08 165820](https://hackmd.io/_uploads/ryI0wMfi6.png) 當大Batch及小Batch的Training Accuracy差不多(都很好),Testing時大Batch比小Batch差 → Overfitting Why? Traning LF有很多Local Minima,Loss都趨近於0; 假設訓練資料跟測試資的LF不一樣,Local Minima位置也不一樣(下圖) 對在盆地的Local Minima,在Training及Testing上的結果不會差太多 對在峽谷的Local Minima,在Training及Testing上的結果差距就相當大 因此Local Minima在盆地,是好Local Minima,如果在峽谷,是壞Local Minima 而大的Batch Size會傾向於走到峽谷,小的Batch Size會傾向於走到盆地 (而小Batch每次update的方向不一樣,且頻率很高,若在峽谷裡很可能一下就逃脫)(尚待研究) ![螢幕擷取畫面 2024-02-08 182410](https://hackmd.io/_uploads/rkvZnXfoa.png) <br/> **統整表格** ![螢幕擷取畫面 2024-01-28 201530](https://hackmd.io/_uploads/HJGtSpQcT.png) <br/> **期刊論文** [On Large-Batch Training for Deep Learning: Generalization Gap and Sharp Minima](https://arxiv.org/abs/1609.04836) [The effect of batch size on the generalizability of the convolutional neural networks on a histopathology dataset](https://www.sciencedirect.com/science/article/pii/S2405959519303455) [Large Batch Optimization for Deep Learning: Training BERT in 76 minutes](https://arxiv.org/abs/1904.00962) [Extremely Large Minibatch SGD: Training ResNet-50 on ImageNet in 15 Minutes](https://arxiv.org/abs/1711.04325) [Stochastic Weight Averaging in Parallel: Large-Batch Training That Generalizes Well](https://arxiv.org/abs/2001.02312) [Large Batch Training of Convolutional Networks ](https://arxiv.org/abs/1708.03888) [Accurate, large minibatch sgd: Training imagenet in 1 hour ](https://arxiv.org/abs/1706.02677) <br/><br/> ### Momentum #### 介紹 是可能可以對抗 Local Minima 和 Saddle Point 的技術 假設在物理上,Error Surface是斜坡,參數是一顆球,把球從斜坡上滾下來,因為慣性夠大且若動量夠大,有可能不會卡在 Local Minima 與 Saddle Point **Vanilla Gradient Descent** 從Θ0開始,計算其Gradient Descent g0,往g0的反方向update參數,重複以上步驟 為何要沿著梯度的反方向更新參數 因為要使損失函數值最小,而梯度方向是函數值增加為快的方向,因此要沿著梯度的反方向更新參數 為何梯度方向是函數值增加為快的方向 **Gradient Descent + Momentum** 原本:往Gradient的反方向 改成:往Gradient的反方向 + 前一步移動的方向 ![螢幕擷取畫面 2024-02-09 125926](https://hackmd.io/_uploads/H1BPb4Qi6.png) 可發現movement可寫成Gradient的weigted Sum Momentum可解讀成 1.Gradient的反方向 + 前一步移動的方向 2.考慮的Gradient是過去所有Gradient的總和 <br/><br/><br/> ## [6]類神經網路訓練不起來怎麼辦 (三):自動調整學習速率 (Learning Rate) 副標題 : Optimization 前言:Critical Point 不一定是訓練 network 時的最大障礙 (有可能根本還沒走到 Critical Point 訓練就停住了,為了不要讓訓練停住,因此此章探討 Adaptive Learning Rate 方法解決此問題) **Adaptive Learning Rate** : 給每一個參數不同的 Learning Rate ### **Critical Point不一定是訓練network時的最大障礙** ![螢幕擷取畫面 2024-01-30 223816](https://hackmd.io/_uploads/rkioD989a.png) 我們會一邊訓練一邊紀錄 Loss,當 Loss 不再下降,我們認為卡在Critical Point,且 Gradient 很小。但其實不一定!! 從 Gradient 的向量長度圖中可以得知,雖然 Loss 幾乎沒有變化,Gradient 也可能有變化 例如:有可能是 Gradient 在 Error suface 的山谷間來回震盪 此時 Gradient 仍然很大(並非遇到 Critical Point),只是 loss 不再減小。 **如果訓練時很少卡到 Saddle Point, Local minima,那下圖是怎麼畫的?** ![螢幕擷取畫面 2024-01-30 234019](https://hackmd.io/_uploads/H13Eu6w5p.png) 因為這張圖不是用一般的 Gradient descend 訓練 一般的 Gradient descend 不太能接近 Critical Point 多數的 Training 在接近 Critical Point 前(Gradient還很大),Loss 就已經停止下降 <br/> ### **如果Critical Point不是問題,為什麼Training會卡住?** ![螢幕擷取畫面 2024-01-30 223931](https://hackmd.io/_uploads/HJiAO58cT.png) 一個簡單 Error surface (Convex),只有兩個參數 (Convex:等高線是橢圓形,像狹長山谷。[Convex function - wikipedia](https://en.wikipedia.orG/wiki/Convex_function)) 直觀上感覺:這種 surface 就一路滑下去再走過去即可 事實上:使用 Gradient descend 時, Learning Rate大 → 步伐太大,在山谷間震盪 Learning Rate小 → 步伐太小,幾乎不會前進 用 Gradient descend 訓練,連這種簡單的 Error surface (Convex) 都做不好,所以其實是 Gradient descend 的問題,因此我們需要更好的 Gradient descend 版本。 <br/> ### **Adaptive Learning Rate** **怎麼把 Gradient descend 做好?** 所有參數都設同樣的 Learning Rate 是不夠的 → Learning Rate 要為每個參數客製化(自動調整) 客製化(自動調整) Learning Rate 原則: 若在某個方向很平坦 → Learning Rate大一點 → 走得快 (才會前進) 若在某個方向很陡峭 → Learning Rate小一點 → 走得穩 **Learning Rate如何自動的調整?** 修改 Gradient descend 的式子 原本的 Learning Rate 是固定的 η → 改寫成 η/σ 上標t下標i,此σ對於不同的參數i與迭代t有不同的值 → η改成 η/σ 後,得到一個 parameter dependent 的 learning rate (參數 Θ 上標t下標i,t : iteration,i : 參數號碼) (σ : Gradient 的 Root Mean Square) 參數 update 的方式: ![螢幕擷取畫面 2024-01-31 232213](https://hackmd.io/_uploads/SJbogQj9a.png) σ 是過去所有 gradient 的 Root Mean Square (平方合的平均開根號) <br/> **Adagrad** ![螢幕擷取畫面 2024-02-03 100849](https://hackmd.io/_uploads/rJOwgQsca.png) 為什麼此算式可以做到,當坡度大 Learning Rate 就減小,坡度小 Learning Rate 就放大? 針對不同的參數Θ,其Surface不一樣。 當 Surface 陡峭,Gradient 大,σ上標t下標i較大,Learning Rate 小 當 Surface 平緩,Gradient 小,σ上標t下標i較小,Learning Rate 大 ==上述方法的假設:一個參數 Gradient 的大小會固定== 事實上:Gradient 不會固定,因為 Error Surface 很複雜 → 就算同參數同方向,Learning Rate 也需要動態調整。 <br/> **RMS Prop** ![螢幕擷取畫面 2024-02-03 101603](https://hackmd.io/_uploads/rkuUzXic6.png) Adagrad 使用 Root Mean Square:每個 Gradient 有同等重要性 RMS Prop:可自行調整 Gradient 的重要性,透過 α 決定(g上標t下標i)的重要性,便可動態調整 σ Gradient 大→用 RMS Prop 可讓剛看到的 g 影響變大→σ大→步伐小 Gradient 小→用 RMS Prop 可讓剛看到的 g 影響變小→σ小→步伐大 α 越小,越看重於現在的 Gradient (α 是一個 hyperparameter) <br/> **Adam** 最常用的 Optimization 策略(又稱 Optimizer) Adam:RMS Prop + Momentum Pytorch 有內建此功能 [Adam: A Method for Stochastic Optimization - arXiv:1412.6980 ](https://arxiv.org/abs/1412.6980) <br/> ### **加上Adaptive Learning Rate後,剛剛簡單的Error surface 訓練的起來嗎?** ![螢幕擷取畫面 2024-02-03 102704](https://hackmd.io/_uploads/ryBCN7jc6.png) 卡住的地方加上 Adagrad 後走得動了 起始點顛簸,Gradient 大→σ大→步伐小 左轉後平坦,Gradient 小→σ小→步伐大,因此可以走下去 後面暴走了? 因為算 σ 時會參考過去所有的 Gradient 剛開始在y軸走了很遠,轉彎後雖 Gradient 很小,累積了很多小的 Gradient,σ 變很小,導致步伐變很大,突然噴飛到 Gradient 大的地方,又因 Gradient 大,步伐變小,震盪慢慢停下來回到中間。 **解決辦法 : Learning Rate Scheduling** 讓 η 跟時間有關 做法: ![螢幕擷取畫面 2024-02-03 103220](https://hackmd.io/_uploads/SJRCBXs5T.png) **做法1: Learning Rate Decay** 時間↑,η↓ 隨著時間前進,離目標越來越近,減少 η 讓參數更新慢下來 剛剛的情況加上 Learning Rate Scheduling 就不會震盪 **做法2: Warm Up** Learning Rate 先變大後變小 大小需自己調整,屬於 hyperparameter ++Residual Network++ 使用 Warm Up,Learning Rate 先設成0.01 之後設為 0.1 ++arXiv++ 收集物理、數學、計算機科學、生物學與數理經濟學的論文預印本的網站,前四數字為年月 ++Transformer++ Learning Rate 遵守一個 Warm Up Function,也有使用 Warm Up 為什麼要用 Warm Up 仍需探討 可能的解釋: 不管用 Adam、RMS Prop 或 Adagrad,都需要計算 σ:一個統計的結果,需要大量數據才會精準 → 一開始 σ 不精準,那一開始就不要走太遠,要慢慢收集情報 [On the Variance of the Adaptive Learning Rate and Beyond - arXiv:1908.03265](https://arxiv.org/abs/1908.03265) 總結:Gradient descend之進化 Vanilla Gradient descend:固定的步伐大小與當前Gradient方向 Various Improvements: 1.g:Momentum:考慮過去所有Gradient方向來調整方向 2.σ:Root Mean Square:考慮過去所有Gradient的大小來調整步伐幅度 3.η:Learning Rate Scheduling:考慮時間來調整參數的更新速度 不論是什麼Optimizer,幾乎都是考慮、調整這三個參數 ![螢幕擷取畫面 2024-02-09 134013](https://hackmd.io/_uploads/HJHJiEQsT.png) 詳細講解影片QRcode [[TA 補充課] Optimization for Deep Learning (1/2) (由助教簡仲明同學講授)](https://youtu.be/4pUmZ8hXlHM?si=46JxmmdvQKfY2uVJ) [[TA 補充課] Optimization for Deep Learning (2/2) (由助教簡仲明同學講授) ](https://youtu.be/e03YKGHXnL8?si=2M5qoFV758EZfPvb) Next Time 當 Error Surface 崎嶇,有好多山擋著,需要好的方法來繞過這些山,做 Optimization 這麼痛苦能不能直接把 Error Surface 夷平呢?能不能把山炸掉呢? <br/><br/><br/> ## [7]類神經網路訓練不起來怎麼辦 (四):損失函數 (Loss) 也可能有影響 副標題 : Classification 完整版影片: [ML Lecture 4: Classification](https://youtu.be/fZAZUYEeIMg?si=4bjAIGTpTm5TEEV7) [ML Lecture 5: Logistic Regression](https://youtu.be/hSXFuypLukA?si=AH3i_F3lvtWXYlMw) ### Classification **Regression(回歸):** 輸入一個向量 (vector)x,輸出一個數值 y,並期望此數值與正解 y hat 相近(有加 hat 為實際值) **把Classification當成Regression** 把目標 (y hat) Class 編號,變成數值 (class 1/class 2/...), 觀察 Model 輸出的數值 y,與目標 Class 編號的關係 問題:Class 的編號表示會預設其之間的關係 e.g. Class 1 與 Class 2 關係較近,Class 1 與 Class 3 關係較遠 **Class as one-hot vector** 比較常見的作法是把 Class 用 one-hot vector 表示 → N 個 Class 用 N 個 N * 1 維陣列表示(合併就是N維的單位矩陣) → 如此就沒有 Class 的編號之間有遠近關係的問題,one-hot vector 拿來算距離,兩兩之間的距離皆相同 **把output改成3個數值** 目標 y hat Class 是有 3 個數值的向量,output 應該也要有 3 個數值 怎麼把 network 從輸出 1 個數值改成輸出3個數值? → 把 output 方法重複 3 次:a1 a2 a3 乘上不同的 weight,加上不同的 bias 來輸出不同的 y1 y2 y3 **Claassification小結** Regression 是 input x ,output y,y 與 y hat 越接近越好 Claassification 也是 input x,output y,y 與 y hat 越接近越好,但 y 是一個向量 做 Claassification 時,會把 y 再通過 Function "Softmax" 得 y' 當作最終輸出 <br/> ### Softmax **為什麼要加Softmax?**(詳細解釋看另部影片) y hat 裡面的值只有 0 跟 1,但 y 的值是任意數值 →透過 Softmax 使 y 的值變成 0 與 1 之間,容易與 y hat 計算相似度 [使用 TensorFlow 學習 Softmax 回歸 (Softmax Regression)](https://medium.com/%E6%89%8B%E5%AF%AB%E7%AD%86%E8%A8%98/%E4%BD%BF%E7%94%A8-tensorflow-%E5%AD%B8%E7%BF%92-softmax-%E5%9B%9E%E6%AD%B8-softmax-regression-41a12b619f04) **Softmax作法** ![螢幕擷取畫面 2024-02-03 123104](https://hackmd.io/_uploads/rJZhWSjqT.png) 1.將 y 取以 e 為底數的指數函數 (讓y的值變成正的) 2.除以所有 y 的 exponential 的和(步驟1),得y' 做完 Softmax: 1>y'>0, 所有參數和為 1 **Softmax功能** 1.Normalize,讓所有y'範圍為 0 到 1 之間,且和為 1 2.加大值之間的差距 (?) Softmax的輸入通常稱為logit **2個Class的情況** 2 個 Class 取Sigmoid 與取 Softmax →兩者等價 <br/> ### Loss of Classification ![螢幕擷取畫面 2024-02-03 124644](https://hackmd.io/_uploads/HywRBSoq6.png) Claassification也是input x,output y,把y丟到Softmax得y',計算y'與y hat的距離(e) 計算距離e有不同的做法:Mean Square Error與Cross-entropy **Mean Square Error** Summation of (y hat - y')^2 →可計算兩個向量間的距離 當minimize Mean Square Error時,可以達到y hat = y' **Cross-entropy**(較常用) minimizing cross-entropy = Maximizing likelihood (一模一樣) (本次課堂並未講解likelihood) [何謂 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 Loss、Logistic Loss、Log-Loss是不是同樣的東西](https://flag-editors.medium.com/%E6%A9%9F%E5%99%A8%E5%AD%B8%E7%BF%92%E5%8B%95%E6%89%8B%E5%81%9Alesson-10-%E5%88%B0%E5%BA%95cross-entropy-loss-logistic-loss-log-loss%E6%98%AF%E4%B8%8D%E6%98%AF%E5%90%8C%E6%A8%A3%E7%9A%84%E6%9D%B1%E8%A5%BF-%E4%B8%8A%E7%AF%87-2ebb74d281d) 註 : pytorch 中 Cross-entropy 內建 Softmax 從 Optimization 的角度解釋 Cross-entropy 比 Mean Square Error 更適合 Classification 類任務 ![螢幕擷取畫面 2024-02-03 125545](https://hackmd.io/_uploads/SJx5wSoca.png) 舉例證明 做 3 個 Class 的分類,input x,output y1 y2 y3,y 做Softmax 得 y',再計算 y' 與 y hat [1 0 0] 的距離 e 將 y3 設為不影響結果的數值,只觀察 y1 y2 變動的結果 比較 e 是 Mean Square Error 與 Cross-entropy 時的不同: 當 y1 大 y2 小→接近正解[1 0 0],Loss 小 當 y1 小 y2 大→Loss 大 發現當 Loss 很大的時候(左上角) Cross-entropy : 有斜率 → 訓練較容易 Mean Square Error : 較平坦 → 訓練可能會卡住,雖然可以用 Adaptive Learning rate 解決,但 Traning 起步仍相當困難 總結 Changing the loss finction can change the difficuity of optimization Loss function 的定義也會影響 Training 的難易度 <br/><br/><br/> ## [8]類神經網路訓練不起來怎麼辦 (五): 批次標準化 (Batch Normalization) 簡介 **前言 : 為什麼需要Batch Normalization** 我們覺得 error surface 很崎嶇的時候比較難 train,那能不能夠直接把山剷平,讓它變得比較好 train 呢? Batch Normalization 就是其中一個把山剷平的想法 假設兩個參數對 Loss 的斜率差別非常大,如果是固定 learning rate,可能很難得到好的結果,因此需要adaptive learning rate,例如Adam 等較進階的 optimization 方法,才能夠得到好的結果 從另外一個方向想,直接把難做的 error surface 把它改掉看能不能夠改得好做一點 <br/> ### Feature Normalization **W1 跟 W2 的斜率差很多的狀況從何而來** ![螢幕擷取畫面 2024-02-03 193418](https://hackmd.io/_uploads/rJJkBjsca.png) **舉例 :** 一個 linear model,輸入是 x1、x2,對應參數 W1、W2 沒有 activation function,W1 乘 x1,W2 乘 x2 加上 b 以後就得到 y 計算 y 跟 y hat 之間的差距當做 e,把所有 training data e 加起來就是 Loss **W1 改變,對 Loss 的變化要怎麼看?** 當 W1 改變,比如加上 delta W1 → y改變 → e改變 → L改變,所以當 W1 改變 L 就跟著改變 可以從圖中看出 : 沿 W1 方向斜率小,沿 W2 方向斜率大 **什麼時候 W1 的改變會對 L 的影響很小?** 一個可能性是 : input 很小 假設 x1 的值都很小 (x1 的值在不同的 training example 裡值都很小) 因為 x1 直接乘上 w1,所以 x1 的值很小 W1 有變化的時候,對 y 的影響也是小的,對 e 的影響也是小的,對 L 的影響就會小 **什麼時候 W2 的改變會對 L 的影響很大?** 一個可能性是 : input 很大 假設 x2 的值都很大 (x2 的值在不同的 training example 裡值都很小) 因為 x2 直接乘上 w2,所以 x2 的值很大 W2 有變化的時候,對 y 的影響也是大的,對 e 的影響也是大的,對 L 的影響就會大 **結論** 當 input 的 feature 的每一個 dimension 的值 scale 差距很大, 就可能產生像這樣的 error surface(不同方向斜率差距很大) 因此出現一個目標 : 讓 feature 裡面不同 dimension 有同樣的數值的範圍,製造比較好的 error surface,讓 training 變得較容易,此目標就是所謂的Feature Normalization <br/> ### Feature Normalization作法之一 ![螢幕擷取畫面 2024-02-09 160551](https://hackmd.io/_uploads/rJUNTUQj6.png) 假設 x1 到 xR 為所有訓練資料的 feature vector 將不同 feature vector 的同一個 dimension 裡的數值取出,計算第i個 dimension 的 mean(mi) 及 standard deviation(Σi) **standardization** x 減 (這個 dimension 算出來的) mean、除 standard deviation,得到新的數值叫 x tilde 做完 normalize 以後,這個 dimension 上的數值,平均是 0,variance 是 1 <br/> ### 多層 Network 的 Feature Normalization ![螢幕擷取畫面 2024-02-09 160602](https://hackmd.io/_uploads/HkrubDmj6.png) 對 W2 來說,a1 a2 z1 z3 也是 input (如果 x tilde 通過 W1 得到 z1,而 z1 不同的 dimension 間數值的分布仍然有很大的差異,train W2 第二層的參數也會有困難) 所以也應該要對這邊的 a 或 z 做 Feature Normalization **normalization 要在 activation function 之前或之後做?** Ans : 實作上兩者差異不大 **多層 Network 的 Feature Normalization 的影響** z1 如果沒有做 Feature Normalization,改變 z1 的值,只改變 a1 的值,每一個 x1 tilde x2 tilde x3 tilde 是獨立分開處理的 但若有 normalization, 因為 μ 跟 Σ 是根據 z1 z2 z3 算出來的,所以當改變 z1,μ 跟 Σ 會跟著改變,z2 a2 z3 a3 的值也會跟著改變,做 Feature Normalization 以後這三個 example變得彼此關聯了 之前的 network 都只吃一個 input 得到一個 output 現在有一個比較大的 network,輸入一堆 input,算出 μ 跟 Σ,再產生一堆 output ![螢幕擷取畫面 2024-02-09 160627](https://hackmd.io/_uploads/rJtjzwmoa.png) 因此產生問題: 訓練資料非常多,GPU 的 memory 無法把整個 data set 都 load 進去 ### Batch Normalization 前面提到的 Feature Normalization 流程,以一個 Batch 為單位 **舉例** batch 設 64 : 對於這個巨大的 network 把 64 筆 data 讀進去 算這 64 筆 data 的 μ 算這 64 筆 data 的 σ 對這 64 筆 data 做 normalization **一個常搭配 Batch Normalization 的設計** 把 z tilde 乘上另外一個向量 γ (element wise 的相乘) 再加上 β 這個向量得到 z hat WHY? 因為如果做 normalization 後,z tilde 的平均是 0 平均是 0 會給 network 一些限制,所以我們把 β 跟 γ 加回去 讓 network 的 hidden layer 的 output 平均不是 0 **Batch Normalization - Testing** 註:testing 有時候又叫 inference PyTorch 處理方式 在 training 的時候,用每一個 batch 計算出來的 μ 跟 Σ,計算 moving average μ bar 跟 Σ bar ![螢幕擷取畫面 2024-02-09 224139](https://hackmd.io/_uploads/S1_TFh7o6.png) [arxiv - Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift](https://arxiv.org/abs/1502.03167) **Batch Normalization 為什麼會有幫助** Batch Normalization 可以讓 error surface 比較不崎嶇 [arxiv - How Does Batch Normalization Help Optimization?](https://arxiv.org/abs/1805.11604) <br/><br/><br/> ## [9]卷積神經網路 (Convolutional Neural Networks, CNN) [ML Lecture 10: Convolutional Neural Network](https://youtu.be/FrKWiRv254g?si=DSIbzxsG3B00WnOK) CNN: 專門用於影像的架構 ![螢幕擷取畫面 2024-02-09 235552](https://hackmd.io/_uploads/r1lViaXi6.png) 把所有圖片都先 Rescale 成相同大小並輸入模型 模型的輸出是一個向量 y',希望 y' 和 y^的 Cross Entropy 越小越好 因為模型的目標是分類,所以會把每一個類別表示成一個 One-Hot Vector 假設現在類別是貓,那貓對應的 Dimension 數值為 1,其他東西對應的 Dimension 數值為 0 向量長度決定了模型可以辨識出多少不同種類的東西 ![螢幕擷取畫面 2024-02-09 235725](https://hackmd.io/_uploads/Byq2jTQsT.png) 一張圖片是一個三維的 Tensor 包含圖片的寬、高、Channel 數目 Channel 是什麼 : 彩色圖片的每一個 Pixel 是由 R G B 三個顏色所組成 所以這三個 Channel 就代表了 R G B 三個顏色 長跟寬代表圖片的解析度(像素的數目) 把這一個三維的 Tensor 拉直可以當成Network的輸入 ### **Fully Connected Layer** ![螢幕擷取畫面 2024-02-10 105803](https://hackmd.io/_uploads/rJIXvvVia.png) Fully Connected Layer : 每一個 Neuron 跟 Input 的每一個 Dimension 都有一個 Weight 但其實不需要每一個 Neuron 都去看一張完整的圖片,用 Neuron 判斷有沒有某種 Pattern 出現即可 ### **Receptive Field** ![螢幕擷取畫面 2024-02-10 115741](https://hackmd.io/_uploads/BJaPD1Si6.png) 每一個 Neuron 只關心自己的 Receptive Field 例如 : 定義這個藍色的 Neuron,它的守備範圍是這一個 Receptive Field,裡面有 3×3×3 個數值 也就是 27 維的向量,把這個向量作為這個 Neuron 的輸入,這個 Neuron 給向量的 每一個 Dimension 一個 Weight,加上 Bias 得到輸出 **Receptive Field 可以根據對問題的理解決定** Receptive Field 可以 : - 彼此之間重疊 - 有大有小 - 只考慮某些 Channel (Network Corporation) - 是長方形 **Receptive Field - 經典設定** ![螢幕擷取畫面 2024-02-10 105940](https://hackmd.io/_uploads/BJlyKkBjp.png) 1. 看所有的 Channel 2. Kernel Size 3×3 3. Receptive Field 移動的量叫做 Stride Stride 往往不會設太大,因為希望這些 Receptive Field 之間有重疊,以避免 Pattern 正好出現在兩個 Receptive Field 的交界上 4. 超出範圍做 Padding (補0) ### Parameter Sharing 兩個 Neuron 的 weights 一樣,但它們守備的 Receptive Field 不一樣,讓這些 Neuron 共享參數 ### Benefit of Convolutional Layer ![螢幕擷取畫面 2024-02-10 203739](https://hackmd.io/_uploads/S1GUAJSs6.png) Fully Connected 的 Network 彈性最大 Receptive Field 限制看一個小範圍 Receptive Field 加上 Parameter Sharing 是 Convolutional Layer,有用 Convolutional Layer 的 Network 叫 Convolutional Neural Network ### another explain ![螢幕擷取畫面 2024-02-10 211224](https://hackmd.io/_uploads/rkRAIeHsp.png) Convolutional Layer 裡面有很多的 Filter,每一個 Filter 都是一個 3 × 3 × Channel 的 Tensor,Filter 的作用是去圖片抓取 Pattern 把 Filter 放在圖片左上角,把 Filter 內的 9 個值跟這個範圍裡面的 9 個值做 Inner Product,接著往右移,並重複以上步驟。如果有 64 個 Filter 就會得到 64 群數字,這些數字叫做 Feature Map 這個 Feature Map 可以當成下一個 Convolutional Layer 的輸入 (channel 為 64) ![螢幕擷取畫面 2024-02-10 211237](https://hackmd.io/_uploads/H1WVweSo6.png) ### **如何看比較大範圍的 Pattern** ![螢幕擷取畫面 2024-02-10 232501](https://hackmd.io/_uploads/S1_dSGBoa.png) 當考慮第一個 Convolutional Layer 的輸出的 Feature Map 上 3 × 3 的範圍時其實是考慮了原來影像上 5 × 5 的範圍 所以 Network 疊得越深,同樣是 3 × 3 大小的 Filter 看的範圍就會越來越大 所以 Network 夠深就不用怕偵測不到比較大的 Pattern 第一個版本的故事裡說不同的 Neuron 可以 Share Weight 去守備不同的範圍 而 Share Weight 其實就是把 Filter 掃過一張圖片 把 Filter 掃過一張圖片就是 Convolution ### Pooling - Max Pooling 把一張比較大的圖片做 Subsampling 一般在實作上 Convolution 跟 Pooling 交替使用 ### CNN 運算流程 ![image](https://hackmd.io/_uploads/HykrE79GR.png =60%x) ### 參考資料 [卷積神經網路 (Convolutional Neural , CNN)](https://hackmd.io/@allen108108/rkn-oVGA4) 本文內容以李宏毅 Machine Learning (2017) 第十講 : Convolutional Neural Network ( CNN ) 為主,搭配參考資料編輯而成。 [Spatial Transformer Layer](https://www.youtube.com/watch?v=SoCywZ1hZak&list=WL&index=4) <br/><br/><br/> ## [10]自注意力機制 (Self-attention) (上) <br/><br/><br/> ## [11]自注意力機制 (Self-attention) (下)

    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