温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python实现最小二乘法线性拟合

发布时间:2020-09-24 12:59:03 来源:脚本之家 阅读:221 作者:王勇21633012 栏目:开发技术

本文python代码实现的是最小二乘法线性拟合,并且包含自己造的轮子与别人造的轮子的结果比较。

问题:对直线附近的带有噪声的数据进行线性拟合,最终求出w,b的估计值。

最小二乘法基本思想是使得样本方差最小。

代码中self_func()函数为自定义拟合函数,skl_func()为调用scikit-learn中线性模块的函数。

import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
 
n = 101
 
x = np.linspace(0,10,n)
noise = np.random.randn(n)
y = 2.5 * x + 0.8 + 2.0 * noise
 
def self_func(steps=100, alpha=0.01):
  w = 0.5
  b = 0
  alpha = 0.01
  for i in range(steps):
    y_hat = w*x + b
    dy = 2.0*(y_hat - y)
    dw = dy*x
    db = dy
    w = w - alpha*np.sum(dw)/n
    b = b - alpha*np.sum(db)/n
    e = np.sum((y_hat-y)**2)/n
    #print (i,'W=',w,'\tb=',b,'\te=',e)
  print ('self_func:\tW =',w,'\n\tb =',b)
  plt.scatter(x,y)
  plt.plot(np.arange(0,10,1), w*np.arange(0,10,1) + b, color = 'r', marker = 'o', label = 'self_func(steps='+str(steps)+', alpha='+str(alpha)+')')
 
def skl_func():
  lr = LinearRegression()
  lr.fit(x.reshape(-1,1),y)
  y_hat = lr.predict(np.arange(0,10,0.75).reshape(-1,1))
  print('skl_fun:\tW = %f\n\tb = %f'%(lr.coef_,lr.intercept_))
  plt.plot(np.arange(0,10,0.75), y_hat, color = 'g', marker = 'x', label = 'skl_func')
  
self_func(10000)
skl_func()
plt.legend(loc='upper left')
plt.show()

结果:

self_func:  W = 2.5648753825503197     b = 0.24527830841237772
skl_fun:     W = 2.564875                             b = 0.245278

python实现最小二乘法线性拟合

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI