日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Python機器學習之隨機梯度下降法的實現_python

作者:街?三?仔 ? 更新時間: 2023-06-19 編程語言

隨機梯度下降法

為什么使用隨機梯度下降法?

如果當我們數據量和樣本量非常大時,每一項都要參與到梯度下降,那么它的計算量時非常大的,所以我們可以采用隨機梯度下降法。

隨機梯度下降法中的學習率必須是隨著循環的次數增加而遞減的。如果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

與前邊運算結果進行對比,其耗時更長。

原文鏈接:https://blog.csdn.net/Oh_Python/article/details/129233709

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新