//2019.08.06
機器學習算法中的梯度下降法(gradient descent)
1、對於梯度下降法,具有以下幾點特別說明:
(1)不是一種機器學習算法,不可以解決分類或者回歸問題;
(2)是一種基於搜索的最優化方法;
(3)作用是最小化損失函數;
(4)梯度上升法:最大化效用函數。
2、梯度下降法就是在原來函數的基礎上乘以一個步長,使得其整體始終為負值,然后從一個起始點開始走起來,一直到函數的極小值點處找到相應的最小值。
圖1
3、對於步長η的取值,也叫作學習率,是一個0-1之間的數字,不能太大,也不能太小,原因是:
如果太大,則會減慢收斂學習的速度,如果太大,則容易導致不收斂。
圖2
4、對於梯度下降法的步長η,它稱為學習率,具有以下特點:
(1)η的取值大小會影響取最優解的速度和效率;
(2)η取值不合適,甚至得不到最優解;
(3)η是梯度下降法的一個超參數。
5、對於梯度下降法的應用,並不一定所有的函數都有唯一的極小值,因此解決方案是:多次運行,隨機化初始點,其初始點也是梯度下降法的一個超參數。
6、梯度下降法的python代碼原理實現過程如下:
其中的函數以二次函數為例:
#1-1導入相應的模塊
import numpy as np
import matplotlib.pyplot as plt
#1-2定義函數的相應變量取值范圍為以及函數的表達式
plot_x=np.linspace(-1,6,141)
plot_y=(plot_x-2.5)**2-1
plt.figure()
theta=0.0
eta=0.1
erro=1e-100
theta_history=[theta]
theta1=[]
def DJ(theta):
return 2*(theta-2.5)
def J(theta):
return (theta-2.5)**2-1
###1-3將梯度下降法封裝起來成為一個梯度下降函數,以便后續的使用和調節參數,使用起來比較方便
(其中最重要的超參數是1初始點的值x0,2梯度下降的定義步長eta,3最多的循環次數,4函數值的誤差范圍)
def gradient_descent(eta,theta_initial,erro=1e-8, n=1e2):
theta=theta_initial
theta_history.append(theta_initial)
i=0
while i<n:
gradient = DJ(theta)
last_theta = theta
theta = theta - gradient * eta
theta_history.append(theta)
if (abs(J(theta) - J(last_theta))) < erro:
break
i+=1
def plot_theta_history():
plt.plot(plot_x,plot_y)
plt.plot(np.array(theta_history),J(np.array(theta_history)),color="r",marker="+")
plt.show()
#1-4設置自己的初始超參數,直接進行結果的輸出與相應的查詢
eta=1.1
x0=0.0
theta_history=[]
gradient_descent(eta,x0)
plot_theta_history()
print(len(theta_history))
print(theta_history[-1])