Python之隨機梯度下降

2022-05-06 13:24:12 字數 1284 閱讀 3110

實現:

# -*- coding: utf-8 -*-

"""練習使用隨機梯度下降演算法

"""import numpy as np

import math

__author__ = 'zhen'

# 生成測試資料

x = 2 * np.random.rand(100, 1) # 隨機生成100*1的二維陣列,值分別在0~2之間

y = 4 + 3 * x + np.random.randn(100, 1) # 隨機生成100*1的二維陣列,值分別在4~11之間

x_b = np.c_[np.ones((100, 1)), x]

print("x矩陣內容如下:\n{}".format(x_b[0:3]))

n_epochs = 100

t0, t1 = 1, 10

m = n_epochs

def learning_schedule(t): # 模擬實現動態修改步長

return t0 / (t + t1)

theta = np.random.randn(2, 1)

for epoch in range(n_epochs):

for i in range(m):

random_index = np.random.randint(m)

x_i = x_b[random_index:random_index+1]

y_i = y[random_index:random_index+1]

gradients = 2 * x_i.t.dot(x_i.dot(theta)-y_i) # 呼叫公式

learning_rate = learning_schedule(epoch * m + i)

theta = theta - learning_rate * gradients

if epoch % 30 == 0:

print("抽樣檢視:\n{}".format(theta))

print("最終結果:\n{}".format(theta))

# 計算誤差

error = math.sqrt(math.pow((theta[0][0] - 4), 2) + math.pow((theta[1][0] - 3), 2))

print("誤差:\n{}".format(error))

結果:

梯度下降 隨機梯度下降 批梯度下降

下面的h x 是要擬合的函式,j 損失函式,theta是引數,要迭代求解的值,theta求解出來了那最終要擬合的函式h 就出來了。其中m是訓練集的記錄條數,j是引數的個數。梯度下降法流程 1 先對 隨機賦值,可以是乙個全零的向量。2 改變 的值,使j 按梯度下降的方向減少。以上式為例 1 對於我們的...

stanford 梯度 梯度下降,隨機梯度下降

一 梯度gradient 在標量場f中的一點處存在乙個向量g,該向量方向為f在該點處變化率最大的方向,其模也等於這個最大變化率的數值,則向量g稱為標量場f的梯度。在向量微積分中,標量場的梯度是乙個向量場。標量場中某一點上的梯度指向標量場增長最快的方向,梯度的長度是這個最大的變化率。更嚴格的說,從歐氏...

梯度下降 隨機梯度下降和批量梯度下降

對比梯度下降和隨機梯度下降和批量梯度下降 之前看的知識比較零散,沒有乙個系統的解釋說明,看了一些網上的博主的分析,總結了一下自己的理解。例子這裡我參照其他博主的例子做了一些修改,首先是梯度下降 coding utf 8 import random this is a sample to simula...