亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

6.線性回歸——單變量梯度下降算法的實現

標簽:
機器學習

权重和偏执的更新公式:
图片描述

import numpy as np 
import matplotlib.pyplot as plt 

def readData(path):
	data = np.loadtxt(path,dtype = float,delimiter = ",")
	return data

def costFunction(theta_0,theta_1,x,y,m):
	predictValue = theta_1 * x + theta_0
	return sum((predictValue - y) ** 2)/(2 * m)

def gradientDescent(data,theta_0,theta_1,iterations,alpha):
	eachIterationValue = np.zeros((iterations,1))
	#iterations 行,1列
	x = data[:,0]  #第0列
	y = data[:,1]  #第1列
	m = data.shape[0]  #data.shape[0]表示行数
	for i in range(0,iterations):
		hypothesis = theta_1 * x + theta_0
		temp_0 = theta_0 - alpha * ((1/m) * sum(hypothesis - y))
		#更新偏执 theta_0
		temp_1 = theta_1 - alpha * (1/m) * sum ((hypothesis - y) * x)
		#更新权重 theta_1
		theta_0 = temp_0
		theta_1 = temp_1
		costFunction_temp = costFunction(theta_0,theta_1,x,y,m)
		eachIterationValue[i,0] = costFunction_temp
		#依次列出损失函数的值

	return theta_0,theta_1,eachIterationValue

if __name__ == '__main__':
	data = readData('ex1data1.txt')
	iterations = 1500
	plt.scatter(data[:,0],data[:,1],color = 'g',s = 20)
	theta_0,theta_1,eachIterationValue = gradientDescent(data,0,0,iterations,0.01)
	hypothesis = theta_1 * data[:,0]  + theta_0
	plt.plot(data[:,0],hypothesis)
	plt.title('Fittingcurve')
	plt.show()
	plt.plot(np.arange(iterations),eachIterationValue)
	plt.title('CostFunction')
	plt.show()

运算结果:
图片描述
图片描述

點擊查看更多內容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
算法工程師
手記
粉絲
23
獲贊與收藏
45

關注作者,訂閱最新文章

閱讀免費教程

  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消