演算法 梯度下降法求最優解,python原始碼

2021-09-11 02:53:38 字數 1719 閱讀 5124

簡單解釋:比如拿溫度感測器來說,就是根據之前一段時間的溫度資料計算下當前理論上應該測量到的溫度,如果超出這個最優解的一定比例,就可以理解為突發狀況了

**如下:

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

# 訓練集

# 每個樣本點有3個分量 (x0,x1,x2)

#x = [(1, 0., 3), (1, 1., 3), (1, 2., 3), (1, 3., 2), (1, 4., 4)]

x = [(1), (2), (1), (2), (1.1), (1.2), (1.3), (1.4), (1.5)]

# y[i] 樣本點對應的輸出

y = [85.364, 77.217205, 75.195834, 90.105519, 89.342380, 70.123323, 80.12233, 88.34353, 98.34353]

# 迭代閥值,當兩次迭代損失函式之差小於該閥值時停止迭代

epsilon = 0.0001

# 學習率

alpha = 0.01

diff = [0, 0]

max_itor = 1000

error1 = 0

error0 = 0

cnt = 0

m = len(x)  

# 初始化引數

theta0 = 0

theta1 = 0

theta2 = 0

while true:

cnt += 1

# 引數迭代計算

for i in range(m):

# 擬合函式為 y = theta0 * x[0] + theta1 * x[1] +theta2 * x[2]

# 計算殘差

#diff[0] = (theta0 + theta1 * x[i][1] + theta2 * x[i][2]) - y[i]

diff[0] = (theta0) - y[i]

print('xi=%d' % x[i])

# 梯度 = diff[0] * x[i][j]

theta0 -= alpha * diff[0] * x[i]

#theta1 -= alpha * diff[0] * x[i][1]

# theta2 -= alpha * diff[0] * x[i][2]

# 計算損失函式

error1 = 0

for lp in range(len(x)):

#error1 += (y[lp]-(theta0 + theta1 * x[lp][1] + theta2 * x[lp][2]))**2/2

error1 += (y[lp]-(theta0 ))**2/2

if abs(error1-error0) < epsilon:

break

else:

error0 = error1

print (' theta0 : %f, theta1 : %f, theta2 : %f, error1 : %f' % (theta0, theta1, theta2, error1))

print ('done: theta0 : %f, theta1 : %f, theta2 : %f' % (theta0, theta1, theta2))

print ('迭代次數: %d' % cnt)

print('最優解:%f' % theta0)

梯度下降法 求解最優解

import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import math from mpl toolkits.mplot3d import axes3d 設定在jupyter中matplotlib的...

最優化 梯度下降法

最優化問題就是求解函式極值的問題,包括極大值和極小值,幾乎所有機器學習演算法歸根到底都是在求解最優化問題。在高等數學 微積分中有求極值統一的思路 找函式導數等於0的點,只要函式可導我們就可以用這種方法。在機器學習中我們一般求函式的極小值,若求極大值我們只需要整體加負號。有些時候我們會對優化變數x有約...

梯度下降法演算法核心

非調庫方法實現梯度下降法多元線性回歸 在高等數學中,我們學習了導數,泰勒展開等等,我們一定做過一類題 求最小值 極小值,其實就是在求我們該如何取引數,使得目標函式取得最小值。這個數學問題有著深厚的工程應用背景,比如 深度學習中,我們該如何取神經網路的權值,使得學習誤差最小?這裡的權值就是我們要求的引...