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 一維線性回歸 內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
pip matplotlib報錯equired packages can not be built解決
這篇文章主要介紹了pip matplotlib報錯equired packages can not be built解決,具有一定借鑒價值,需要的朋友可以參考下2018-01-01
Python常用驗證碼標注和識別(需求分析和實現(xiàn)思路)
通過本文的介紹,我們了解了Python在常用驗證碼標注和識別方面的應用,在實際項目中,我們可以根據(jù)具體需求選擇合適的模型和工具,實現(xiàn)高效、準確的驗證碼標注和識別,感興趣的朋友跟隨小編一起看看吧2024-03-03
python把數(shù)組中的數(shù)字每行打印3個并保存在文檔中的方法
今天小編就為大家分享一篇python把數(shù)組中的數(shù)字每行打印3個并保存在文檔中的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-07-07
Python三十行代碼實現(xiàn)簡單人臉識別的示例代碼
這篇文章主要介紹了Python三十行代碼實現(xiàn)簡單人臉識別的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-03-03
在交互式環(huán)境中執(zhí)行Python程序過程詳解
這篇文章主要介紹了在交互式環(huán)境中執(zhí)行Python程序過程詳解,運行Python腳本程序的方式有多種,目前主要的方式有:交互式環(huán)境運行、命令行窗口運行、開發(fā)工具上運行等,其中在不同的操作平臺上還互不相同,需要的朋友可以參考下2019-07-07

