梯度下降、AdaGrad算法內容及實現


梯度下降、AdaGrad算法內容及實現

AdaGrad算法

在一般的優化算法中,目標函數自變量的每一個變量都采用統一的學習率來進行迭代。

\[w = w-\eta\frac{\partial f}{\partial w},\\ b = b-\eta\frac{\partial f}{\partial b} \]

但是AdaGrad算法根據自變量在每個維度的梯度值大小來調整各個維度上的學習率,從而避免統一的學習率難以適應所有維度的問題。

自適應學習率的優化算法(來自以上鏈接)

  • 該算法的思想是獨立地適應模型的每個參數具有較大偏導的參數相應有一個較大的學習率,而具有小偏導的參數則對應一個較小的學習率
  • 具體來說,每個參數的學習率會縮放各參數反比於其歷史梯度平方值總和的平方根
  • AdaGrad 算法描述
  • img
  • AdaGrad 存在的問題
    • 學習率是單調遞減的,訓練后期學習率過小會導致訓練困難,甚至提前結束
    • 需要設置一個全局的初始學習率

代碼

import math
import matplotlib.pyplot as plt
import numpy as np
‘’‘
初始數據
’‘’
xdata = np.array([8., 3., 9., 7., 16., 05., 3., 10., 4., 6.]).reshape(-1, 1)
ydata = np.array([30., 21., 35., 27., 42., 24., 10., 38., 22., 25.]).reshape(-1, 1)
m = xdata.shape[0]
w_g = 8
b_g = 90
w_a = 8
b_a = 90
h_w = 0
h_b = 0
eps = 1e-5
tw_g = []
tb_g = []
tw_a = []
tb_a = []
iter = 10000

一、代價函數

def cost(w, b):
    tsum = 0
    for i in range(m):
        tsum += (w * xdata[i] + b - ydata[i]) ** 2
    return tsum / (2 * m)

二、梯度

def grad(w, b):
    dw = (1 / m) * ((w * xdata + b - ydata) * xdata).sum()
    db = (1 / m) * (w * xdata + b - ydata).sum()
    return dw, db

三、梯度下降

def graddescent(alpha, w, b, iter):
    Cost = np.zeros(iter)
    for i in range(iter):
        tw_g.append(w)
        tb_g.append(b)
        w, b = Cal_Gradient(alpha, w, b)
        Cost[i] = cost(w, b)
    return w, b, Cost

四、AdaGrad實現

def Cal_Adagrad(lr, w, b, h_w, h_b, eps):
    dw, db = grad(w, b)
    h_w += dw ** 2
    h_b += db ** 2
    w = w - lr * (1 / math.sqrt(h_w + eps)) * dw
    b = b - lr * (1 / math.sqrt(h_b + eps)) * db
    return w, b


def Adagrad(lr, w, b, iter):
    Cost = np.zeros(iter)
    for i in range(iter):
        tw_a.append(w)
        tb_a.append(b)
        w, b = Cal_Adagrad(lr, w, b, h_w, h_b, eps)
        Cost[i] = cost(w, b)
    return w, b, Cost

五、圖像

w_g, b_g, Cost_g = graddescent(0.01, w_g, b_g, iter)
w_a, b_a, Cost_a = Adagrad(0.03, w_a, b_a, iter)
x = np.linspace(3, 16, 100)
y = w_a * x + b_a
cx = np.arange(0, iter)
plt.figure()
plt.subplot(221)
plt.plot(x, y, 'orange')
plt.scatter(xdata, ydata)
plt.subplot(222)
w = np.linspace(-10, 10, 10)
b = np.linspace(-100, 100, 10)
w_, b_ = np.meshgrid(w, b)
Z = cost(w_, b_)
plt.contourf(b_, w_, Z, 30)
plt.contour(b_, w_, Z)
plt.plot(tb_g, tw_g,marker = 'o',c='black',linewidth = 2)
plt.plot(tb_a, tw_a,marker = '.', c='green',linewidth = 1)
plt.scatter(b_a,w_a,s = 200,c = 'yellow',marker='x')
plt.subplot(223)
plt.plot(cx, Cost_g,label = 'BGD',marker = '*',color = 'black',linewidth = 2)
plt.plot(cx,Cost_a, label = 'Adagrad',marker = '.',c = 'green',linewidth = 1)
plt.legend()
plt.show()


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM