国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術(shù)文章
文章詳情頁

python 還原梯度下降算法實(shí)現(xiàn)一維線性回歸

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

首先我們看公式:

python 還原梯度下降算法實(shí)現(xiàn)一維線性回歸

這個(gè)是要擬合的函數(shù)

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

python 還原梯度下降算法實(shí)現(xiàn)一維線性回歸

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

python 還原梯度下降算法實(shí)現(xiàn)一維線性回歸

最終,梯度下降的算法:

python 還原梯度下降算法實(shí)現(xiàn)一維線性回歸

學(xué)習(xí)率一般小于1,當(dāng)損失函數(shù)是0時(shí),我們輸出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]] # 這里換成你想擬合的數(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()

到此這篇關(guān)于python 還原梯度下降算法實(shí)現(xiàn)一維線性回歸 的文章就介紹到這了,更多相關(guān)python 一維線性回歸 內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!

標(biāo)簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 芮城县| 平潭县| 安达市| 保定市| 公安县| 灯塔市| 迭部县| 青铜峡市| 嘉黎县| 峨眉山市| 霸州市| 随州市| 子洲县| 花莲县| 凤山市| 蕉岭县| 三明市| 渝北区| 嵊州市| 远安县| 乌审旗| 温宿县| 全南县| 饶阳县| 城口县| 左贡县| 延庆县| 海宁市| 浦县| 成安县| 虹口区| 望都县| 冀州市| 盐源县| 哈尔滨市| 高尔夫| 长沙市| 温州市| 巍山| 兴国县| 出国|