国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python+numpy+matplotalib實現梯度下降法

2020-01-04 14:36:41
字體:
來源:轉載
供稿:網友

這個階段一直在做和梯度一類算法相關的東西,索性在這兒做個匯總,

一、算法論述

梯度下降法(gradient  descent)別名最速下降法(曾經我以為這是兩個不同的算法-.-),是用來求解無約束最優化問題的一種常用算法。下面以求解線性回歸為題來敘述:

設:一般的線性回歸方程(擬合函數)為:(其中python,numpy,matplotalib,梯度下降法的值為1)

python,numpy,matplotalib,梯度下降法  

python,numpy,matplotalib,梯度下降法這一組向量參數選擇的好與壞就需要一個機制來評估,據此我們提出了其損失函數為(選擇均方誤差):

python,numpy,matplotalib,梯度下降法

我們現在的目的就是使得損失函數python,numpy,matplotalib,梯度下降法取得最小值,即目標函數為:

python,numpy,matplotalib,梯度下降法

如果python,numpy,matplotalib,梯度下降法的值取到了0,意味著我們構造出了極好的擬合函數,也即選擇出了最好的python,numpy,matplotalib,梯度下降法值,但這基本是達不到的,我們只能使得其無限的接近于0,當滿足一定精度時停止迭代。

那么問題來了如何調整python,numpy,matplotalib,梯度下降法使得python,numpy,matplotalib,梯度下降法取得的值越來越小呢?方法很多,此處以梯度下降法為例:

分為兩步:(1)初始化python,numpy,matplotalib,梯度下降法的值。

                  (2)改變python,numpy,matplotalib,梯度下降法的值,使得python,numpy,matplotalib,梯度下降法按梯度下降的方向減少。

python,numpy,matplotalib,梯度下降法值的更新使用如下的方式來完成:

python,numpy,matplotalib,梯度下降法

  python,numpy,matplotalib,梯度下降法      

其中python,numpy,matplotalib,梯度下降法為步長因子,這里我們取定值,但注意如果python,numpy,matplotalib,梯度下降法取得過小會導致收斂速度過慢,python,numpy,matplotalib,梯度下降法過大則損失函數可能不會收斂,甚至逐漸變大,可以在下述的代碼中修改python,numpy,matplotalib,梯度下降法的值來進行驗證。后面我會再寫一篇關于隨機梯度下降法的文章,其實與梯度下降法最大的不同就在于一個求和符號。

二、代碼實現

import numpy as npimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import axes3dfrom matplotlib import style  #構造數據def get_data(sample_num=10000):  """  擬合函數為  y = 5*x1 + 7*x2  :return:  """  x1 = np.linspace(0, 9, sample_num)  x2 = np.linspace(4, 13, sample_num)  x = np.concatenate(([x1], [x2]), axis=0).T  y = np.dot(x, np.array([5, 7]).T)   return x, y#梯度下降法def GD(samples, y, step_size=0.01, max_iter_count=1000):  """  :param samples: 樣本  :param y: 結果value  :param step_size: 每一接迭代的步長  :param max_iter_count: 最大的迭代次數  :param batch_size: 隨機選取的相對于總樣本的大小  :return:  """  #確定樣本數量以及變量的個數初始化theta值  m, var = samples.shape  theta = np.zeros(2)  y = y.flatten()  #進入循環內  print(samples)  loss = 1  iter_count = 0  iter_list=[]  loss_list=[]  theta1=[]  theta2=[]  #當損失精度大于0.01且迭代此時小于最大迭代次數時,進行  while loss > 0.001 and iter_count < max_iter_count:    loss = 0    #梯度計算    theta1.append(theta[0])    theta2.append(theta[1])    for i in range(m):      h = np.dot(theta,samples[i].T)      #更新theta的值,需要的參量有:步長,梯度      for j in range(len(theta)):        theta[j] = theta[j] - step_size*(1/m)*(h - y[i])*samples[i,j]    #計算總體的損失精度,等于各個樣本損失精度之和    for i in range(m):      h = np.dot(theta.T, samples[i])      #每組樣本點損失的精度      every_loss = (1/(var*m))*np.power((h - y[i]), 2)      loss = loss + every_loss     print("iter_count: ", iter_count, "the loss:", loss)        iter_list.append(iter_count)    loss_list.append(loss)        iter_count += 1  plt.plot(iter_list,loss_list)  plt.xlabel("iter")  plt.ylabel("loss")  plt.show()  return theta1,theta2,theta,loss_listdef painter3D(theta1,theta2,loss):  style.use('ggplot')  fig = plt.figure()  ax1 = fig.add_subplot(111, projection='3d')  x,y,z = theta1,theta2,loss  ax1.plot_wireframe(x,y,z, rstride=5, cstride=5)  ax1.set_xlabel("theta1")  ax1.set_ylabel("theta2")  ax1.set_zlabel("loss")  plt.show()def predict(x, theta):  y = np.dot(theta, x.T)  return y    if __name__ == '__main__':  samples, y = get_data()  theta1,theta2,theta,loss_list = GD(samples, y)  print(theta) # 會很接近[5, 7]   painter3D(theta1,theta2,loss_list)  predict_y = predict(theta, [7,8])  print(predict_y)

三、繪制的圖像如下:

迭代次數與損失精度間的關系圖如下:步長為0.01

python,numpy,matplotalib,梯度下降法

變量python,numpy,matplotalib,梯度下降法python,numpy,matplotalib,梯度下降法與損失函數loss之間的關系:(從初始化之后會一步步收斂到loss滿足精度,之后python,numpy,matplotalib,梯度下降法、python,numpy,matplotalib,梯度下降法會變的穩定下來)

python,numpy,matplotalib,梯度下降法

下面我們來看一副當步長因子變大后的圖像:步長因子為0.5(很明顯其收斂速度變緩了)

python,numpy,matplotalib,梯度下降法

python,numpy,matplotalib,梯度下降法

當步長因子設置為1.8左右時,其損失值已經開始震蕩

python,numpy,matplotalib,梯度下降法

          python,numpy,matplotalib,梯度下降法

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。


注:相關教程知識閱讀請移步到python教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 鹰潭市| 罗江县| 张家口市| 监利县| 漳州市| 临洮县| 谷城县| 深泽县| 郎溪县| 湘潭市| 西青区| 都匀市| 濮阳县| 克什克腾旗| 乳山市| 红安县| 邢台市| 大关县| 肃北| 彭泽县| 南郑县| 巴东县| 蓝田县| 菏泽市| 正安县| 揭东县| 特克斯县| 长沙市| 湖北省| 玛纳斯县| 沧源| 长顺县| 宜宾县| 北安市| 北海市| 庆城县| 鄂伦春自治旗| 宁强县| 绿春县| 越西县| 惠来县|