本文小編為大家詳細介紹“Python機器學習之隨機梯度下降法如何實現”,內容詳細,步驟清晰,細節處理妥當,希望這篇“Python機器學習之隨機梯度下降法如何實現”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學習新知識吧。
為什么使用隨機梯度下降法?
如果當我們數據量和樣本量非常大時,每一項都要參與到梯度下降,那么它的計算量時非常大的,所以我們可以采用隨機梯度下降法。
隨機梯度下降法中的學習率必須是隨著循環的次數增加而遞減的。如果eta取一樣的話有可能在非常接近我們的最優值時會跳過,所以隨著迭代次數的增加,學習率eta要隨之減小,我們可以用模擬退火的思想實現(如下圖所示),t0和t1是一個常數,定值,其通常是根據經驗取得一些值。
隨機梯度下降法的公式如下圖所示,其中挑出一個樣本出來計算。
先創建x,y,以下取10000個樣本
import numpy as np m = 10000 x = np.random.random(size=m) y = x*3 + 4 + np.random.normal(size=m)
寫入函數
def dj_sgd(theta, x_i, y_i): # 傳入一個樣本,獲取對應的梯度 return x_i.T.dot(x_i.dot(theta)-y_i)*2 # MSE def sgd(X_b, y, initial_theta, n_iters): # 求出整個theta的函數 def learning_rate(i_iter): t0 = 5 t1 = 50 return t0/(i_iter+t1) theta = initial_theta i_iter = 1 while i_iter <= n_iters: index = np.random.randint(0, len(X_b)) x_i = X_b[index] y_i = y[index] gradient = dj_sgd(theta, x_i, y_i) # 求導數 theta = theta - gradient*learning_rate(i_iter) # 求步長 i_iter += 1 return theta
調用函數,求出截距和系數
以上隨機梯度的缺點是不能照顧到每一點,因此需要進行改進。
以下對其中的函數進行修改。
def dj_sgd(theta, x_i, y_i): # 傳入一個樣本,獲取對應的梯度 return x_i.T.dot(x_i.dot(theta)-y_i)*2 # MSE def sgd(X_b, y, initial_theta, n_iters): # 求出整個theta的函數 def learning_rate(i_iter): t0 = 5 t1 = 50 return t0/(i_iter+t1) theta = initial_theta m = len(X_b) for cur_iter in range(n_iters): # 每一次循環都把樣本打亂,n_iters的代表整個樣本看幾輪 random_indexs = np.random.permutation(m) X_random = X_b[random_indexs] y_random = y[random_indexs] for i in range(m): theta = theta - learning_rate(cur_iter*m+i) * (dj_sgd(theta, X_random[i], y_random[i])) return theta
與前邊運算結果進行對比,其耗時更長。
讀到這里,這篇“Python機器學習之隨機梯度下降法如何實現”文章已經介紹完畢,想要掌握這篇文章的知識點還需要大家自己動手實踐使用過才能領會,如果想了解更多相關內容的文章,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。