梯度下降是迭代法的一種,可以用于求解最小二乘問題(線性和非線性都可以)。在求解機器學習算法的模型參數(shù),即無約束優(yōu)化問題時,梯度下降(Gradient Descent)是最常采用的方法之一,另一種常用的方法是最小二乘法。在求解損失函數(shù)的最小值時,可以通過梯度下降法來一步步的迭代求解,得到最小化的損失函數(shù)和模型參數(shù)值。反過來,如果我們需要求解損失函數(shù)的最大值,這時就需要用梯度上升法來迭代了。
顧名思義,梯度下降法的計算過程就是沿梯度下降的方向求解極小值(也可以沿梯度上升方向求解極大值)。梯度方向我們可以通過對函數(shù)求導得到,步長的確定比較麻煩,太大了的話可能會發(fā)散,太小收斂速度又太慢。一般確定步長的方法是由線性搜索算法來確定,即把下一個點的坐標看做是ak+1的函數(shù),然后求滿足f(ak+1)的最小值的ak+1即可。因為一般情況下,梯度向量為0的話說明是到了一個極值點,此時梯度的幅值也為0.而采用梯度下降算法進行最優(yōu)化求解時,算法迭代的終止條件是梯度向量的幅值接近0即可,可以設置個非常小的常數(shù)閾值。
利用吳學恩機器學習課里的數(shù)據(jù)集進行代碼實現(xiàn)
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
def readData(path,name=[]):
??? data =pd.read_csv(path,names=name)
??? data =(data - data.mean()) / data.std()
???data.insert(0,'First',1)
??? returndata
def costFunction(X,Y,theta):
??? inner =np.power(((X * theta.T) - Y.T), 2)
??? returnnp.sum(inner) / (2 * len(X))
def gradientDescent(data,theta,alpha,iterations):
???eachIterationValue = np.zeros((iterations,1))
??? temp=np.matrix(np.zeros(theta.shape))
??? X =np.matrix(data.iloc[:,0:-1].values)
??? print(X)
??? Y=np.matrix(data.iloc[:,-1].values)
??? m =X.shape[0]
???colNum=X.shape[1]
??? for i inrange(iterations):
??????? error= (X * theta.T)-Y.T
??????? for jin range(colNum):
???????????term =np.multiply(error,X[:,j])
???????????temp[0,j] =theta[0,j]-((alpha/m) * np.sum(term))
??????? theta=temp
???????eachIterationValue[i,0]=costFunction(X,Y,theta)
??? returntheta,eachIterationValue ??
if __name__ == "__main__":
??? data =readData('ex1data2.txt',['Size', 'Bedrooms', 'Price'])
??? #data =(data - data.mean()) / data.std()
??? theta=np.matrix(np.array([0,0,0]))
???iterations=1500
??? alpha=0.01
???theta,eachIterationValue=gradientDescent(data,theta,alpha,iterations)
???print(theta)
??? plt.plot(np.arange(iterations),eachIterationValue)
???plt.title('CostFunction')
???plt.show()