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实现apahce网站日志分析示例
Apr 02 Python
python实现可以断点续传和并发的ftp程序
Sep 13 Python
实现python版本的按任意键继续/退出
Sep 26 Python
解决python2.7 查询mysql时出现中文乱码
Oct 09 Python
浅谈Python爬取网页的编码处理
Nov 04 Python
python使用xpath中遇到:到底是什么?
Jan 04 Python
Python实现上下班抢个顺风单脚本
Feb 07 Python
python实现二叉查找树实例代码
Feb 08 Python
tensorflow学习笔记之简单的神经网络训练和测试
Apr 15 Python
keras .h5转移动端的.tflite文件实现方式
May 25 Python
python IP地址转整数
Nov 20 Python
为了顺利买到演唱会的票用Python制作了自动抢票的脚本
Oct 16 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 服务器调试 Zend Debugger 的安装教程
2009/09/25 PHP
PHP 编程安全性小结
2010/01/08 PHP
PHP中SESSION使用中的一点经验总结
2012/03/30 PHP
fetchAll()与mysql_fetch_array()的区别详解
2013/06/05 PHP
ThinkPHP CURD方法之where方法详解
2014/06/18 PHP
支付宝服务窗API接口开发php版本
2016/07/20 PHP
php基于curl实现的股票信息查询类实例
2016/11/11 PHP
PHP Mysqli 常用代码集合
2016/11/12 PHP
php实现留言板功能
2017/03/05 PHP
Js 随机数产生6位数字
2010/05/13 Javascript
基于jquery的气泡提示效果
2010/05/31 Javascript
DIV+CSS+JS不间断横向滚动实现代码
2013/03/19 Javascript
js操作输入框提示信息且响应鼠标事件
2014/03/25 Javascript
理运用命名空间让js不产生冲突避免全局变量的泛滥
2014/06/15 Javascript
网页运行时提示对象不支持abigimage属性或方法
2014/08/10 Javascript
js判断浏览器类型及设备(移动页面开发)
2015/07/30 Javascript
Bootstrap每天必学之轮播(Carousel)插件
2016/04/25 Javascript
Reactjs实现通用分页组件的实例代码
2017/01/19 Javascript
原生JS中slice()方法和splice()区别
2017/03/06 Javascript
Vue自定义全局Toast和Loading的实例详解
2019/04/18 Javascript
nodeJs的安装与npm全局环境变量的配置详解
2020/01/06 NodeJs
vue 函数调用加括号与不加括号的区别
2020/10/29 Javascript
在Python中使用swapCase()方法转换大小写的教程
2015/05/20 Python
python解析基于xml格式的日志文件
2017/02/25 Python
python绘制散点图并标记序号的方法
2018/12/11 Python
在pycharm中设置显示行数的方法
2019/01/16 Python
使用Python3内置文档高效学习以及官方中文文档
2019/05/19 Python
基于django micro搭建网站实现加水印功能
2020/05/22 Python
CSS3实现div从下往上滑入滑出效果示例
2020/04/28 HTML / CSS
canvas绘制树形结构可视图形的实现
2020/04/03 HTML / CSS
社区母亲节活动记录
2014/03/06 职场文书
精彩广告词大全
2014/03/19 职场文书
生产车间标语
2014/06/11 职场文书
锦旗标语大全
2014/06/23 职场文书
婚礼答谢礼品
2015/01/20 职场文书
与Windows10相比Windows11有哪些改进?值不值得升级?
2021/11/21 数码科技