随机梯度下降法
#Python?3.3.5?? #?matrix_A??訓練集?? matrix_A?=?[[1,4],?[2,5],?[5,1],?[4,2]]?? Matrix_y?=?[19,26,19,20]?? theta?=?[2,5]?? #學習速率?? leraing_rate?=?0.005?? loss?=?50?? iters?=?1?? Eps?=?0.0001?? while?loss>Eps?and?iters?<1000?:?? ????loss?=?0?? ????for?i?in?range(3)?:?? ????????h?=?theta[0]*matrix_A[i][0]?+?theta[1]*matrix_A[i][1]??? ????????theta[0]?=?theta[0]?+?leraing_rate*(Matrix_y[i]-h)*matrix_A[i][0]?? ????????theta[1]?=?theta[1]?+?leraing_rate*(Matrix_y[i]-h)*matrix_A[i][1]?? ????for?i?in?range(3)?:?? ????????Error?=?0?? ????????Error?=?theta[0]*matrix_A[i][0]?+?theta[1]*matrix_A[i][1]?-?Matrix_y[i]?? ????????Error?=?Error*Error?? ????????loss?=?loss?+Error?? ????iters?=?iters?+1?? print?('theta=',theta)?? print?('iters=',iters)?? #Python 3.3.5
# matrix_A ?訓練集
matrix_A = [[1,4], [2,5], [5,1], [4,2]]
Matrix_y = [19,26,19,20]
theta = [2,5]
#學習速率
leraing_rate = 0.005
loss = 50
iters = 1
Eps = 0.0001
while loss>Eps and iters <1000 :loss = 0for i in range(3) :h = theta[0]*matrix_A[i][0] + theta[1]*matrix_A[i][1]?theta[0] = theta[0] + leraing_rate*(Matrix_y[i]-h)*matrix_A[i][0]theta[1] = theta[1] + leraing_rate*(Matrix_y[i]-h)*matrix_A[i][1]for i in range(3) :Error = 0Error = theta[0]*matrix_A[i][0] + theta[1]*matrix_A[i][1] - Matrix_y[i]Error = Error*Errorloss = loss +Erroriters = iters +1
print ('theta=',theta)
print ('iters=',iters)求解結(jié)果: [python] view plaincopyprint? >>>??? theta=?[2.9980959216157945,?4.001522800837675]?? iters=?75?? >>>
theta= [2.9980959216157945, 4.001522800837675]
iters= 75但如果對輸入數(shù)據(jù)添加一些噪聲 matrix_A?=?[[1.05,4],?[2.1,5],?[5,1],?[4,2]]?? matrix_A = [[1.05,4], [2.1,5], [5,1], [4,2]]求解結(jié)果為: >>>??? theta=?[3.0095950685197725,?3.944718521027671]?? iters=?1000?? >>>
theta= [3.0095950685197725, 3.944718521027671]
iters= 1000可見在有噪聲的情況下,要及時調(diào)整模型誤差精度、迭代次數(shù)上限,一期達到我們的需求。
以上圖片和公式均摘自:梯度下降法http://blog.csdn.net/zbc1090549839/article/details/38149561
隨機梯度下降法
分類: Algorithm 2014-07-26 21:45 98人閱讀 評論(0) 收藏 舉報 python算法迭代斯坦福大學機器學習剛剛看完斯坦福大學機器學習第四講(牛頓法),也對學習過程做一次總結(jié)吧。
一、誤差準則函數(shù)與隨機梯度下降:
數(shù)學一點將就是,對于給定的一個點集(X,Y),找到一條曲線或者曲面,對其進行擬合之。同時稱X中的變量為特征(Feature),Y值為預測值。
如圖:
一個典型的機器學習的過程,首先給出一組輸入數(shù)據(jù)X,我們的算法會通過一系列的過程得到一個估計的函數(shù),這個函數(shù)有能力對沒有見過的新數(shù)據(jù)給出一個新的估計Y,也被稱為構(gòu)建一個模型。
我們用X1、X2...Xn 去描述feature里面的分量,用Y來描述我們的估計,得到一下模型:
我們需要一種機制去評價這個模型對數(shù)據(jù)的描述到底夠不夠準確,而采集的數(shù)據(jù)x、y通常來說是存在誤差的(多數(shù)情況下誤差服從高斯分布),于是,自然的,引入誤差函數(shù):
關鍵的一點是如何調(diào)整theta值,使誤差函數(shù)J最小化。J函數(shù)構(gòu)成一個曲面或者曲線,我們的目的是找到該曲面的最低點:
假設隨機站在該曲面的一點,要以最快的速度到達最低點,我們當然會沿著坡度最大的方向往下走(梯度的反方向)
用數(shù)學描述就是一個求偏導數(shù)的過程:
這樣,參數(shù)theta的更新過程描述為以下:
? ?(α表示算法的學習速率)
二、算法實現(xiàn)與測試:
通過一組數(shù)據(jù)擬合 y = theta1*x1 +theta2*x2
[python] view plaincopyprint?
[python] view plaincopyprint?
[python] view plaincopyprint?
以上圖片和公式均摘自:梯度下降法http://blog.csdn.net/zbc1090549839/article/details/38149561
總結(jié)
- 上一篇: 优化算法-共轭梯度法
- 下一篇: 软件开发模式对比(瀑布、迭代、螺旋、敏捷