Python实现的简单线性回归算法实例分析


Posted in Python onDecember 26, 2018

本文实例讲述了Python实现的简单线性回归算法。分享给大家供大家参考,具体如下:

用python实现R的线性模型(lm)中一元线性回归的简单方法,使用R的women示例数据,R的运行结果:

> summary(fit)
Call:
lm(formula = weight ~ height, data = women)
Residuals:
    Min      1Q  Median      3Q     Max
-1.7333 -1.1333 -0.3833  0.7417  3.1167
Coefficients:
             Estimate Std. Error t value Pr(>|t|)
(Intercept) -87.51667    5.93694  -14.74 1.71e-09 ***
height        3.45000    0.09114   37.85 1.09e-14 ***
---
Signif. codes:  0 ‘***' 0.001 ‘**' 0.01 ‘*' 0.05 ‘.' 0.1 ‘ ' 1
Residual standard error: 1.525 on 13 degrees of freedom
Multiple R-squared:  0.991, Adjusted R-squared:  0.9903
F-statistic:  1433 on 1 and 13 DF,  p-value: 1.091e-14

python实现的功能包括:

  1. 计算pearson相关系数
  2. 使用最小二乘法计算回归系数
  3. 计算拟合优度判定系数R2R2
  4. 计算估计标准误差Se
  5. 计算显著性检验的F和P值
import numpy as np
import scipy.stats as ss
class Lm:
  """简单一元线性模型,计算回归系数、拟合优度的判定系数和
  估计标准误差,显著性水平"""
  def __init__(self, data_source, separator):
    self.beta = np.matrix(np.zeros(2))
    self.yhat = np.matrix(np.zeros(2))
    self.r2 = 0.0
    self.se = 0.0
    self.f = 0.0
    self.msr = 0.0
    self.mse = 0.0
    self.p = 0.0
    data_mat = np.genfromtxt(data_source, delimiter=separator)
    self.xarr = data_mat[:, :-1]
    self.yarr = data_mat[:, -1]
    self.ybar = np.mean(self.yarr)
    self.dfd = len(self.yarr) - 2 # 自由度n-2
    return
  # 计算协方差
  @staticmethod
  def cov_custom(x, y):
    result = sum((x - np.mean(x)) * (y - np.mean(y))) / (len(x) - 1)
    return result
  # 计算相关系数
  @staticmethod
  def corr_custom(x, y):
    return Lm.cov_custom(x, y) / (np.std(x, ddof=1) * np.std(y, ddof=1))
  # 计算回归系数
  def simple_regression(self):
    xmat = np.mat(self.xarr)
    ymat = np.mat(self.yarr).T
    xtx = xmat.T * xmat
    if np.linalg.det(xtx) == 0.0:
      print('Can not resolve the problem')
      return
    self.beta = np.linalg.solve(xtx, xmat.T * ymat) # xtx.I * (xmat.T * ymat)
    self.yhat = (xmat * self.beta).flatten().A[0]
    return
  # 计算拟合优度的判定系数R方,即相关系数corr的平方
  def r_square(self):
    y = np.mat(self.yarr)
    ybar = np.mean(y)
    self.r2 = np.sum((self.yhat - ybar) ** 2) / np.sum((y.A - ybar) ** 2)
    return
  # 计算估计标准误差
  def estimate_deviation(self):
    y = np.array(self.yarr)
    self.se = np.sqrt(np.sum((y - self.yhat) ** 2) / self.dfd)
    return
  # 显著性检验F
  def sig_test(self):
    ybar = np.mean(self.yarr)
    self.msr = np.sum((self.yhat - ybar) ** 2)
    self.mse = np.sum((self.yarr - self.yhat) ** 2) / self.dfd
    self.f = self.msr / self.mse
    self.p = ss.f.sf(self.f, 1, self.dfd)
    return
  def summary(self):
    self.simple_regression()
    corr_coe = Lm.corr_custom(self.xarr[:, -1], self.yarr)
    self.r_square()
    self.estimate_deviation()
    self.sig_test()
    print('The Pearson\'s correlation coefficient: %.3f' % corr_coe)
    print('The Regression Coefficient: %s' % self.beta.flatten().A[0])
    print('R square: %.3f' % self.r2)
    print('The standard error of estimate: %.3f' % self.se)
    print('F-statistic: %d on %s and %s DF, p-value: %.3e' % (self.f, 1, self.dfd, self.p))

python执行结果:

The Regression Coefficient: [-87.51666667   3.45      ]
R square: 0.991
The standard error of estimate: 1.525
F-statistic:  1433 on 1 and 13 DF,  p-value: 1.091e-14

其中求回归系数时用矩阵转置求逆再用numpy内置的解线性方程组的方法是最快的:

a = np.mat(women.xarr); b = np.mat(women.yarr).T
timeit (a.I * b)
99.9 µs ± 941 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
timeit ata.I * (a.T*b)
64.9 µs ± 717 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
timeit np.linalg.solve(ata, a.T*b)
15.1 µs ± 126 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

希望本文所述对大家Python程序设计有所帮助。

Python 相关文章推荐
python脚本实现分析dns日志并对受访域名排行
Sep 18 Python
Python代码调试的几种方法总结
Apr 15 Python
Python 遍历列表里面序号和值的方法(三种)
Feb 17 Python
详解python如何在django中为用户模型添加自定义权限
Oct 15 Python
python 检查文件mime类型的方法
Dec 08 Python
Python为何不能用可变对象作为默认参数的值
Jul 01 Python
Python开发之基于模板匹配的信用卡数字识别功能
Jan 13 Python
解决tensorflow训练时内存持续增加并占满的问题
Jan 19 Python
Python HTMLTestRunner可视化报告实现过程解析
Apr 10 Python
使用sklearn对多分类的每个类别进行指标评价操作
Jun 11 Python
OpenCV-Python实现轮廓的特征值
Jun 09 Python
LyScript实现绕过反调试保护的示例详解
Aug 14 Python
Python基于聚类算法实现密度聚类(DBSCAN)计算【测试可用】
Dec 26 #Python
python使用knn实现特征向量分类
Dec 26 #Python
python调用staf自动化框架的方法
Dec 26 #Python
Django unittest 设置跳过某些case的方法
Dec 26 #Python
python 2.7 检测一个网页是否能正常访问的方法
Dec 26 #Python
在python中使用requests 模拟浏览器发送请求数据的方法
Dec 26 #Python
Django+JS 实现点击头像即可更改头像的方法示例
Dec 26 #Python
You might like
php Undefined index的问题
2009/06/01 PHP
php数组函数序列之array_combine() - 数组合并函数使用说明
2011/10/29 PHP
php中is_null,empty,isset,unset 的区别详细介绍
2013/04/28 PHP
解决php接收shell返回的结果中文乱码问题
2014/01/23 PHP
php实现根据IP地址获取其所在省市的方法
2015/04/30 PHP
PHP使用CURL模拟登录的方法
2015/07/08 PHP
PHP is_array() 检测变量是否是数组的实现方法
2016/06/13 PHP
PHP文字转图片功能原理与实现方法分析
2017/08/31 PHP
JS 获取span标签中的值的代码 支持ie与firefox
2009/08/24 Javascript
javascript动态的改变IFrame的高度实现自动伸展
2013/10/12 Javascript
jQuery满意度星级评价插件特效代码分享
2015/08/19 Javascript
Vue系列:通过vue-router如何传递参数示例
2017/01/16 Javascript
node.js的事件机制
2017/02/08 Javascript
vue项目中用cdn优化的方法
2018/01/03 Javascript
手写简单的jQuery雪花飘落效果实例
2018/04/22 jQuery
微信小程序 授权登录详解(附完整源码)
2019/08/23 Javascript
微信小程序 行的删除和增加操作实现详解
2019/09/29 Javascript
JavaScript实现简单随机点名器
2019/11/21 Javascript
特征脸(Eigenface)理论基础之PCA主成分分析法
2018/03/13 Python
Python中矩阵创建和矩阵运算方法
2018/08/04 Python
Python2与Python3的区别实例分析
2019/04/11 Python
python做反被爬保护的方法
2019/07/01 Python
python之拟合的实现
2019/07/19 Python
Django实现文件上传下载功能
2019/10/06 Python
django 模版关闭转义方式
2020/05/14 Python
HTML5拖拽文件上传的示例代码
2021/03/04 HTML / CSS
雷曼兄弟的五金店:Lehman’s Hardware Store
2019/04/10 全球购物
三星加拿大官方网上商店:Samsung CA
2020/12/18 全球购物
什么是事务?事务有哪些性质?
2012/03/11 面试题
金属材料工程个人求职的自我评价
2013/12/04 职场文书
土木工程求职信
2014/05/29 职场文书
党员创先争优心得体会
2014/09/11 职场文书
十八大宣传标语
2014/10/09 职场文书
预备党员转正党小组意见
2015/06/01 职场文书
springboot+WebMagic+MyBatis爬虫框架的使用
2021/08/07 Java/Android
Python 绘制多因子柱状图
2022/05/11 Python