python 還原梯度下降算法實現(xiàn)一維線性回歸
首先我們看公式:

這個是要擬合的函數(shù)
然后我們求出它的損失函數(shù), 注意:這里的n和m均為數(shù)據(jù)集的長度,寫的時候忘了

注意,前面的theta0-theta1x是實際值,后面的y是期望值
接著我們求出損失函數(shù)的偏導數(shù):

最終,梯度下降的算法:

學習率一般小于1,當損失函數(shù)是0時,我們輸出theta0和theta1.
接下來上代碼!
class LinearRegression():
def __init__(self, data, theta0, theta1, learning_rate):
self.data = data
self.theta0 = theta0
self.theta1 = theta1
self.learning_rate = learning_rate
self.length = len(data)
# hypothesis
def h_theta(self, x):
return self.theta0 + self.theta1 * x
# cost function
def J(self):
temp = 0
for i in range(self.length):
temp += pow(self.h_theta(self.data[i][0]) - self.data[i][1], 2)
return 1 / (2 * self.m) * temp
# partial derivative
def pd_theta0_J(self):
temp = 0
for i in range(self.length):
temp += self.h_theta(self.data[i][0]) - self.data[i][1]
return 1 / self.m * temp
def pd_theta1_J(self):
temp = 0
for i in range(self.length):
temp += (self.h_theta(data[i][0]) - self.data[i][1]) * self.data[i][0]
return 1 / self.m * temp
# gradient descent
def gd(self):
min_cost = 0.00001
round = 1
max_round = 10000
while min_cost < abs(self.J()) and round <= max_round:
self.theta0 = self.theta0 - self.learning_rate * self.pd_theta0_J()
self.theta1 = self.theta1 - self.learning_rate * self.pd_theta1_J()
print('round', round, ':\t theta0=%.16f' % self.theta0, '\t theta1=%.16f' % self.theta1)
round += 1
return self.theta0, self.theta1
def main():
data = [[1, 2], [2, 5], [4, 8], [5, 9], [8, 15]] # 這里換成你想擬合的數(shù)[x, y]
# plot scatter
x = []
y = []
for i in range(len(data)):
x.append(data[i][0])
y.append(data[i][1])
plt.scatter(x, y)
# gradient descent
linear_regression = LinearRegression(data, theta0, theta1, learning_rate)
theta0, theta1 = linear_regression.gd()
# plot returned linear
x = np.arange(0, 10, 0.01)
y = theta0 + theta1 * x
plt.plot(x, y)
plt.show()
到此這篇關于python 還原梯度下降算法實現(xiàn)一維線性回歸 的文章就介紹到這了,更多相關python 一維線性回歸 內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
使用LibTorch進行C++調(diào)用pytorch模型方式
這篇文章主要介紹了使用LibTorch進行C++調(diào)用pytorch模型方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-12-12
Python+pyecharts繪制雙動態(tài)曲線教程詳解
pyecharts 是一個用于生成 Echarts 圖表的類庫。Echarts 是百度開源的一個數(shù)據(jù)可視化 JS 庫。用 Echarts 生成的圖可視化效果非常棒。本文將用pyecharts繪制雙動態(tài)曲線,需要的可以參考一下2022-06-06
為什么黑客都用python(123個黑客必備的Python工具)
python支持功能強大的黑客攻擊模塊,而且Python提供多種庫,用于支持黑客攻擊,Python提供了ctypes庫, 借助它, 黑客可以訪問Windows、OS X、Linux等系統(tǒng)提供 DLL與共享庫,還有Python語言易學易用,這對黑客攻擊而言是個巨大的優(yōu)勢。2020-01-01

