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实现的金山快盘的签到程序
Jan 17 Python
Python爬虫辅助利器PyQuery模块的安装使用攻略
Apr 24 Python
解决python文件字符串转列表时遇到空行的问题
Jul 09 Python
详谈Python高阶函数与函数装饰器(推荐)
Sep 30 Python
Python3实现带附件的定时发送邮件功能
Dec 22 Python
django解决跨域请求的问题详解
Jan 20 Python
python GUI库图形界面开发之PyQt5中QWebEngineView内嵌网页与Python的数据交互传参详细方法实例
Feb 26 Python
jupyter notebook 多环境conda kernel配置方式
Apr 10 Python
keras多显卡训练方式
Jun 10 Python
Python实现一个优先级队列的方法
Jul 31 Python
Python中使用tkFileDialog实现文件选择、保存和路径选择
May 20 Python
Python+pyaudio实现音频控制示例详解
Jul 23 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
使用Apache的rewrite技术
2006/06/22 PHP
php删除文件夹及其文件夹下所有文件的函数代码
2013/01/23 PHP
探讨捕获php错误信息方法的详解
2013/06/09 PHP
php使用GD实现颜色渐变实例
2015/06/02 PHP
PHP字符串和十六进制如何实现互相转换
2020/07/16 PHP
php实现统计IP数及在线人数的示例代码
2020/07/22 PHP
省市选择的简单实现(基于zepto.js)
2016/06/21 Javascript
JS选取DOM元素的简单方法
2016/07/08 Javascript
AngularJS基础 ng-disabled 指令详解及简单示例
2016/08/01 Javascript
Angular2学习教程之TemplateRef和ViewContainerRef详解
2017/05/25 Javascript
angularJs使用$watch和$filter过滤器制作搜索筛选实例
2017/06/01 Javascript
JS兼容所有浏览器的DOMContentLoaded事件
2018/01/12 Javascript
JS实现的合并两个有序链表算法示例
2019/02/25 Javascript
Angular CLI 使用教程指南参考小结
2019/04/10 Javascript
微信小程序 scroll-view的使用案例代码详解
2020/06/11 Javascript
vue实现多个echarts根据屏幕大小变化而变化实例
2020/07/19 Javascript
[03:11]完美世界DOTA2联赛PWL DAY8集锦
2020/11/09 DOTA
[01:28]国服启动器接入蒸汽平台操作流程视频
2021/03/11 DOTA
在Python的while循环中使用else以及循环嵌套的用法
2015/10/14 Python
分析Python中设计模式之Decorator装饰器模式的要点
2016/03/02 Python
python爬虫爬取淘宝商品信息
2018/02/23 Python
python 拷贝特定后缀名文件,并保留原始目录结构的实例
2018/04/27 Python
python实现交并比IOU教程
2020/04/16 Python
python3.7中安装paddleocr及paddlepaddle包的多种方法
2020/11/27 Python
Happy Socks英国官网:购买五颜六色的袜子
2020/11/03 全球购物
俄罗斯园林植物网上商店:Garshinka
2020/07/16 全球购物
深圳茁壮笔试题
2015/05/28 面试题
同学聚会欢迎辞
2014/01/14 职场文书
关于工资低的辞职信
2014/01/14 职场文书
网络研修随笔感言
2014/02/17 职场文书
党建示范点实施方案
2014/03/12 职场文书
化工工艺设计求职信
2014/06/25 职场文书
80后婚前协议书范本
2014/10/24 职场文书
催款律师函范文
2015/05/27 职场文书
Python可视化学习之matplotlib内置单颜色
2022/02/24 Python
解决MySQL报“too many connections“错误
2022/04/19 MySQL