python 還原梯度下降算法實(shí)現(xiàn)一維線性回歸
首先我們看公式:
這個(gè)是要擬合的函數(shù)
然后我們求出它的損失函數(shù), 注意:這里的n和m均為數(shù)據(jù)集的長度,寫的時(shí)候忘了
注意,前面的theta0-theta1x是實(shí)際值,后面的y是期望值接著我們求出損失函數(shù)的偏導(dǎo)數(shù):
最終,梯度下降的算法:
學(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)!
相關(guān)文章:
1. 在Android中使用WebSocket實(shí)現(xiàn)消息通信的方法詳解2. 淺談python出錯(cuò)時(shí)traceback的解讀3. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向4. Python importlib動(dòng)態(tài)導(dǎo)入模塊實(shí)現(xiàn)代碼5. windows服務(wù)器使用IIS時(shí)thinkphp搜索中文無效問題6. 利用promise及參數(shù)解構(gòu)封裝ajax請(qǐng)求的方法7. python matplotlib:plt.scatter() 大小和顏色參數(shù)詳解8. .NET中l(wèi)ambda表達(dá)式合并問題及解決方法9. JSP數(shù)據(jù)交互實(shí)現(xiàn)過程解析10. Nginx+php配置文件及原理解析
