python 数学公式_线性回归数学推导及Python实现

原标题:线性回归数学推导及Python实现

线性回归的数学推导以及Python实现;

假如有这么一堆数据,可以找到一条趋势线

这条线满足每个点到线的距离平方和最小,如何找到这条线?

bb100e8afa2d41568e47cc7dea6bc25c.png

其实就是求解W

a、具体推导如下图所示:

e9d195017db84f35be5b29e3b212a636.jpeg

如何用计算机语言表达数学公式?

当然是神器numpy

b、Python实现

~矩阵解法

7f43e727583744e6ad0956d17b75dd78.jpeg

如果通过上述数学公式进行求解参数W,仅需20行代码可以搞定,但在实际应用中,并不是所有的矩阵都可以进行求逆操作,因此在大多数机器学习算法中使用更多的则是使用迭代法(梯度下降),对参数W求解最优解;

c、使用梯度下降对线性模型进行求解,具体代码如下所示

~梯度下降解法

defcost(theta0,theta1,theta2,x,y ):

J =0

m =len (x )

fori inrange (m ):

h =theta0 +theta1 *x [i ][0]+theta2 *x [i ][1]

J +=(h -y [i ])**2

J /=(2*m )

returnJ

defpart_theta0(theta0,theat1,theta2,x,y ):

h =theta0 +theat1 *x [:, 0]+theta2 *x [:, 1]

diff =(h -y )

partial =diff.sum ()/x.shape [0]

returnpartial

defpart_theta1(theta0,theat1,theta2,x,y ):

h =theta0 +theat1 *x [:, 0] +theta2 *x [:, 1]

diff =(h -y )*x [:, 0]

partial =diff.sum ()/x.shape [0]

returnpartial

defpart_theta2(theta0,theat1,theta2,x,y ):

h =theta0 +theat1 *x [:, 0] +theta2 *x [:, 1]

diff =(h -y )*x [:, 1]

partial =diff.sum ()/x.shape [0]

returnpartial

defgradient(x,y,aph =0.01,theta0 =0,theta1 =0,theta2 =0):

maxer =50000

counter =0

c =cost (theta0,theta1,theta2,data_x,data_y )

costs =[c ]

c1 =c +10

theta0s =[theta0 ]

theta1s =[theta1 ]

theta2s =[theta2 ]

wucha =0.0000001

while(np.abs (c -c1 )>wucha )and(counter

c1 =c

update_theta0 =aph *part_theta0 (theta0,theta1,theta2,x,y )

update__theta1 =aph *part_theta1 (theta0,theta1,theta2,x,y )

update__theta2 =aph *part_theta2 (theta0,theta1,theta2,x,y )

theta0 -=update_theta0

theta1 -=update__theta1

theta2 -=update__theta2

theta0s.append (theta0 )

theta1s.append (theta1 )

theta2s.append (theta2 )

c =cost (theta0,theta1,theta2,data_x,data_y )

costs.append (c )

counter +=1

returntheta0,theta1,theta2,counter

defpredict(X ):

theta0,theta1,theta2,counter =gradient (data_x,data_y )

print(counter )

y_pred =theta0 +theta1 *X [:, 0]+theta2 *X [:, 1]

returny_pred

print(predict (np.array ([[20, 5]])))

欢迎加群一起讨论学习~

b9fd08ca347d4fff909c932feb6613ce.gif

www.vbafans.com返回搜狐,查看更多

责任编辑:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值