基礎(chǔ)
(1)梯度下降法本身不是一個機器學習算法
(2)梯度下降法是一種基于搜索的最優(yōu)化方法
(3)梯度下降法的作用:最小化一個損失函數(shù)
(4)梯度上升法:最大化一個效用函數(shù)
學習率eta如果太小,減慢收斂學習速度鸳碧;太大的話订框,會導致不收斂。
并不是所有函數(shù)都有唯一的極致點奉件。
解決方案:多次運行星瘾,隨機化初始點
梯度下降法的初始點也是一個超參數(shù)坐桩。
原理
封裝:
def gradient_descent(initial_theta,eta,epsilon=1e-8):
??? theta=initial_theta
???theta_history.append(initial_theta)
??? while True:
??????? gradient=dJ(theta)
??????? last_theta=theta
???????theta=theta-eta*gradient
???????theta_history.append(theta)
???? ???if(abs(J(theta)-J(last_theta ))
??????????? break
def plot_theta_history():
???plt.plot(plot_x,J(plot_x))
???plt.plot(np.array(theta_history),J(np.array(theta_history)),color="red",marker="+")
??? plt.show
調(diào)用:
eta=0.01
theta_history=[]
gradient_descent(0.,eta)
plot_theta_history()
結(jié)果:
eta過長的:
避免死循環(huán)的產(chǎn)生:設(shè)置n_iters最多次數(shù)
普遍說,eta默認設(shè)置0.01是普遍的方法及塘,通過繪制的方法可以查看eta是否設(shè)置過大莽使。
多元線性回歸中的梯度下降法
封裝:
(1) def J
def J(theta,X_b,y):
??? try:
??????? returnnp.sum((y-X_b.dot(theta))**2)/len(X_b)
??? except:
??????? returnfloat('inf')
(2) def dJ
def dJ(theta,X_b,y):
???res=np.empty(len(theta))
???res[0]=np.sum(X_b.dot(theta)-y)
??? for i inrange(1,len(theta)):
??????? res[i]=(X_b.dot(theta)-y).dot(X_b[:,i])
return res*2/len(X_b)
(3) gradient_descent梯度下降
defgradient_descent(X_b,y,initial_theta,eta,n_iters=1e4,epsilon=1e-8):
??? theta=initial_theta
??? i_iter=0
??? whilei_iter
???????gradient=dJ(theta,X_b,y)
??????? last_theta=theta
???????theta=theta-eta*gradient
??????? if(abs(J(theta,X_b,y)-J(last_theta,X_b,y))
??????????? break
??????? i_iter+=1
??? return theta
使用梯度下降法前,最好對數(shù)據(jù)進行歸一化
fromsklearn.preprocessing import StandardScaler
批量梯度下降法BatchGradientDescent
實現(xiàn):
def dJ_sgd(theta,X_b_i,y_i):
??? returnX_b_i.T.dot(X_b_i.dot(theta)-y_i)*2
def sgd(X_b,y,initial_theta,n_iters):
??? t0=5
??? t1=50
??? def learning_rate(t):
??????? return t0/(t+t1)
??? theta=initial_theta
??? for cur_iter inranage(n_iters):
???????rand_i=np.random.randint(0,len(X_b))
???????gradient=dJ_sgd(theta,X_b[rand_i],y[rand_i])
???????theta=theta-learning_rate(cur_iter)*gradient
??? return theta
調(diào)用:
X_b=np.hstack([np.ones((len(X),1)),X])
initial_theta=np.zeros(X_b.shape[1])
theta=sgd(X_b,y,initial_theta,n_iters=len(X_b)//3)
關(guān)于梯度的調(diào)試
def dJ_debug(theta,X_b,y,epsilon=0.01):
???res=np.empty(len(theta))
??? for i inrange(len(theta)):
???????theta_1=theta.copy()
?? ?????theta_1[i]+=epsilon
???????theta_2=theta.copy()
???????theta_2[i]-=epsilon
???????res[i]=(J(theta_1,X_b,y)-J(theta_2,X_b,y))/(2*epsilon)
??? return res
總結(jié)
批量梯度下降法:BatchGradientDescent
優(yōu)點:穩(wěn)定磷蛹,一定能向損失函數(shù)最快的方向前進
缺點:求解的速度比較慢
隨機梯度下降法:StochasticGradientDescent
優(yōu)點:求解的速度比較快
缺點:不穩(wěn)定吮旅,損失函數(shù)方向不確定,甚至有可能向反方向前進
小批量梯度下降法:Mini-BatchGradient Descent
每次看k個樣本,兼顧上兩者的優(yōu)點庇勃。
?
隨機:
優(yōu)點:跳出局部最優(yōu)解檬嘀;更快的運行速度
機器學習領(lǐng)域中很多算法都會使用隨機的特點:例如:隨機搜索,隨機森林责嚷。
梯度上升法:求最大值鸳兽,最大化一個效用函數(shù)
更多: