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单链表的简单实现方法
Sep 23 Python
Python中的列表知识点汇总
Apr 14 Python
Python递归遍历列表及输出的实现方法
May 19 Python
Python实现的彩票机选器实例
Jun 17 Python
详解Python中的分组函数groupby和itertools)
Jul 11 Python
IntelliJ IDEA安装运行python插件方法
Dec 10 Python
对Python信号处理模块signal详解
Jan 09 Python
Python3.7 读取 mp3 音频文件生成波形图效果
Nov 05 Python
python3 requests库实现多图片爬取教程
Dec 18 Python
安装python3.7编译器后如何正确安装opnecv的方法详解
Jun 16 Python
基于注解实现 SpringBoot 接口防刷的方法
Mar 02 Python
Python日志模块logging用法
Jun 05 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新手NOTICE错误常见解决方法
2011/12/07 PHP
PHP 第二节 数据类型之数组
2012/04/28 PHP
CentOS 6.3下安装PHP xcache扩展模块笔记
2014/09/10 PHP
Laravel5.5新特性之友好报错以及展示详解
2017/08/13 PHP
详解laravel安装使用Passport(Api认证)
2018/07/27 PHP
修改Laravel自带的认证系统的User类的命名空间的步骤
2019/10/15 PHP
JavaScript 实现模态对话框 源代码大全
2009/05/02 Javascript
jQuery插件jquery-barcode实现条码打印的方法
2015/11/25 Javascript
javascript 删除数组元素和清空数组的简单方法
2017/02/24 Javascript
微信小程序图片宽100%显示并且不变形
2017/06/21 Javascript
bootstrap时间控件daterangepicker使用方法及各种小bug修复
2017/10/25 Javascript
详解Vue.js使用Swiper.js在iOS
2018/09/10 Javascript
小程序兼容安卓和IOS数据处理问题及坑
2018/09/18 Javascript
JS去除字符串最后的逗号实例分析【四种方法】
2019/06/20 Javascript
python 中的列表解析和生成表达式
2011/03/10 Python
Python3.5实现的罗马数字转换成整数功能示例
2019/02/25 Python
如何使用python把ppt转换成pdf
2019/06/29 Python
python实现静态web服务器
2019/09/03 Python
python 实现从高分辨图像上抠取图像块
2020/01/02 Python
pycharm工具连接mysql数据库失败问题
2020/04/01 Python
python如何求100以内的素数
2020/05/27 Python
python学习笔记之多进程
2020/08/06 Python
简单几步用纯CSS3实现3D翻转效果
2019/01/17 HTML / CSS
Html5插件教程之添加浏览器放大镜效果的商品橱窗
2016/01/07 HTML / CSS
HTML5中的音频和视频媒体播放元素小结
2016/01/29 HTML / CSS
卡骆驰新加坡官网:Crocs新加坡
2018/06/12 全球购物
英国领先的酒杯和水晶玻璃器皿制造商:Dartington Crystal
2019/06/23 全球购物
VisionPros美国站:加拿大在线隐形眼镜和眼镜零售商
2020/02/11 全球购物
一篇.NET面试题
2014/09/29 面试题
基督教婚礼主持词
2014/03/14 职场文书
讲文明树新风演讲稿
2014/05/12 职场文书
单位个人查摆问题及整改措施
2014/10/28 职场文书
群众路线自查报告及整改措施
2014/11/04 职场文书
小班教师个人总结
2015/02/05 职场文书
二手手机买卖合同范本(2019年版)
2019/10/28 职场文书
SQL Server 忘记密码以及重新添加新账号
2022/04/26 SQL Server