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

yipeiwu_com6年前Python基础

本文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设计】。

相关文章

asyncio 的 coroutine对象 与 Future对象使用指南

coroutine 与 Future 的关系 看起来两者是一样的,因为都可以用以下的语法来异步获取结果, result = await future result = await...

Python中的浮点数原理与运算分析

本文实例讲述了Python中的浮点数原理与运算。分享给大家供大家参考,具体如下: 先看一个违反直觉的例子: >>> s = 0. >>> for...

python之django母板页面的使用

其实就是利用{% block xxx %}   {% endblock %}的方式定义一个块,相当于占位。存放在某个html中,比如base.html 然后在需要实现...

Python Selenium 之数据驱动测试的实现

Python Selenium 之数据驱动测试的实现

数据驱动模式的测试好处相比普通模式的测试就显而易见了吧!使用数据驱动的模式,可以根据业务分解测试数据,只需定义变量,使用外部或者自定义的数据使其参数化,从而避免了使用之前测试脚本中固定的...

基于Python 装饰器装饰类中的方法实例

基于Python 装饰器装饰类中的方法实例

title: Python 装饰器装饰类中的方法 comments: true date: 2017-04-17 20:44:31 tags: ['Python', 'Decorate'...