李宏毅機器學習(三)回歸實例

老師舉的樣例提出實際運行regression可能遇到的困難

樣例中初始x,y的數(shù)據(jù)為x_data,y_data,

x,y,Z用于標出損失函數(shù)等高線,b,w為初始值為-120,-4,

指定學習率lr=0.0000001,迭代次數(shù)iteration=100000

畫圖中在最終實際參數(shù)w,b的位置畫上了橘黃色的X,每次迭代畫出歷史w,b的位置

插圖1
插圖2
插圖3

代碼段

(不得不吐槽簡書沒有好的程序塊插入,行間隔太長了)

import numpy as np

import matplotlib.pyplot as plt

x_data = np.array([338,333,328,207,226,25,179,60,208,606],dtype=np.float)

y_data = np.array([640,633,619,393,428,27,193,66,226,1591],dtype=np.float)

x = np.arange(-200,-100,1)

y = np.arange(-5,5,0.1)

Z = np.zeros((len(x),len(y)))

X,Y = np.meshgrid(x,y)

for i in range(len(x)):

? ? for j in range(len(y)):

? ? ? ? b = x[i]

? ? ? ? w = y[j]

? ? ? ? Z[i][j] = 0

? ? ? ? for n in range(len(x_data)):

? ? ? ? ? ? Z[j][i] = Z[j][i] + (y_data[n] - b - w * x_data[n])**2

? ? ? ? Z[j][i] = Z[j][i]/(len(x_data))

w = -4

b = -120

lr = 0.0000001

iteration = 100000

b_history = [b]

w_history = [w]

for i in range(iteration):

? ? b_grad=0.0

? ? w_grad=0.0

? ? for n in range(len(x_data)):

? ? ? ? b_grad = b_grad - 2.0*(y_data[n] - b - w * x_data[n]) * 1.0

? ? ? ? w_grad = w_grad - 2.0*(y_data[n] - b - w * x_data[n]) * x_data[n]

? ? b = b - lr * b_grad

? ? w = w - lr * w_grad

? ? b_history.append(b)

? ? w_history.append(w)

plt.contourf(x,y,Z,50,alpha=0.5,cmap=plt.get_cmap('jet'))

plt.plot([-188.4],[2.67],'x',ms=12,markeredgewidth=3,color='orange')

plt.plot(b_history,w_history,'o-',ms=3,lw=1.5,color='black')

plt.xlim(-200,-100)

plt.ylim(-5,5)

plt.xlabel('b',fontsize=16)

plt.ylabel('w',fontsize=16)

plt.show()


分析1

按如上代碼運行結(jié)果,迭代了100000次以后發(fā)現(xiàn)還沒有到x點,需要修改學習率lr

插圖4

分析2

我們講lr×10,得到如下路徑,圖中震蕩了幾次,但是靠向了終點些

插圖5

分析3

將學習率lr再×10,將強烈振蕩而無法趨近終點

插圖6

最后老師放了個大招解決問題,其實是我沒有聽清楚英語不知道是什么單詞,處理如下,此時學習率改成1就行,效果見后圖,老師說以后會講解,記住這個坑

插圖7
插圖8
最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容