Bobo老師機器學習筆記第六課-梯度下降法
阿新 • • 發佈:2018-11-05
思維導圖筆記
數學基礎連結:
為什麼沿著梯度方向函式值上升的最快?
為什麼梯度反方向是函式值下降最快的方向?
練習程式碼
# -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt plot_x = np.linspace(-1, 6, 141) plot_y = (plot_x - 2.5) ** 2 - 1 def J(theta): """ 導數函式,損失函式 :param theta: :return: """ return 2 * (theta - 2.5) def DJ(x): """ 原函式 :param x: :return: """ return ((x - 2.5) ** 2) - 1 def gradient_descent(theta=0, eta=0.1): min_value = DJ(theta) theta_list = [theta] j_plot = [min_value] while True: delta = eta * (- J(theta)) theta = theta + delta theta_list.append(theta) j_plot.append(DJ(theta)) # 第一種方法 限定僅僅迴圈到1000次 # if F(theta) < min_value: # min_value = F(theta) # 第二種方法 讓變化率小於 1e-15 if delta < 1e-15: break return theta_list, j_plot def draw_graph(): fit_theta_list, fit_j_plot = gradient_descent(theta=0, eta=0.1) large_list, large_j_plot = gradient_descent(theta=0, eta=0.8) small_eta_list, small_j_plot = gradient_descent(theta=0, eta=0.05) plt.plot(plot_x, plot_y, label='y=(x-2.5)**2 - 1') plt.plot(fit_theta_list, fit_j_plot, color='red', marker='+', label='eta=0.1, min=%s' % (fit_j_plot[-1])) plt.plot(small_eta_list, small_j_plot, color='blue', marker='*', label='eta=0.05, min=%s' % (small_j_plot[-1])) plt.plot(large_list, large_j_plot, color='green', marker='.', label='eta=0.8, min=%s' % (large_j_plot[-1])) plt.legend() plt.show() if __name__ == '__main__': draw_graph()
執行結果:
編碼總結:
1、eta代表的是步長,可以檢視eta越大,則收斂的速度越快,但是不一定越大越好,當eta太大的時候會超出範圍,導致找不到最低點。一般eta取值0.1
2、讓迴圈終止的辦法至少有2種,第一、設定次數比如不超過1000次,一般通常來說,只要eta設定合理,在1000以內就能找到最優解了。 第二、判斷當前etha和上一個etha在損失函式中的差,如果兩者差小於1e*10-16,那麼就滿足結果了。
3、注意方向導數和梯度直接的差別, 方向導數=梯度與單位向量的乘積。
要是你在西安,感興趣一起學習AIOPS,歡迎加入QQ群 860794445