av一区二区在线观看_亚洲男人的天堂网站_日韩亚洲视频_在线成人免费_欧美日韩精品免费观看视频_久草视

您的位置:首頁技術文章
文章詳情頁

python 還原梯度下降算法實現一維線性回歸

瀏覽:4日期:2022-07-07 15:00:22

首先我們看公式:

python 還原梯度下降算法實現一維線性回歸

這個是要擬合的函數

然后我們求出它的損失函數, 注意:這里的n和m均為數據集的長度,寫的時候忘了

python 還原梯度下降算法實現一維線性回歸

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

python 還原梯度下降算法實現一維線性回歸

最終,梯度下降的算法:

python 還原梯度下降算法實現一維線性回歸

學習率一般小于1,當損失函數是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.theta1def main():data = [[1, 2], [2, 5], [4, 8], [5, 9], [8, 15]] # 這里換成你想擬合的數[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 還原梯度下降算法實現一維線性回歸 的文章就介紹到這了,更多相關python 一維線性回歸 內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Python 編程
相關文章:
主站蜘蛛池模板: av在线播放一区二区 | 亚洲精品二区 | 在线视频国产一区 | 久久精品国产亚洲夜色av网站 | 中文字幕精品一区二区三区精品 | 日韩欧美国产成人一区二区 | 亚洲最大av网站 | 99福利在线观看 | 国产情侣一区 | 久久综合九九 | 国精产品一区一区三区免费完 | 2022精品国偷自产免费观看 | 91精品国产色综合久久 | 伊人91在线 | 亚洲一区 | 99精品久久久久久 | 中文字幕二区 | 精品国产乱码久久久久久1区2区 | 国产a视频| 亚洲欧美国产精品久久 | 精品在线 | 欧美在线a | 狠狠干狠狠操 | 亚洲毛片在线 | 国产一级片免费在线观看 | 99精品视频一区二区三区 | 欧美日韩在线免费 | 嫩草最新网址 | 成人无遮挡毛片免费看 | 久久欧美精品 | 欧美一级欧美三级在线观看 | 中文字幕一区二区三区精彩视频 | 7777在线视频免费播放 | 一区二区三区视频 | a黄视频| 激情久久网| 欧美5区| 国产情侣在线看 | 午夜视频免费网站 | 国产美女精品 | 久久国产精品久久久久 |