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

 更新时间:2018年12月26日 12:01:42   作者:疯琴  
这篇文章主要介绍了Python实现的简单线性回归算法,结合实例形式分析了线性回归算法相关原理、功能、用法与操作注意事项,需要的朋友可以参考下

本文实例讲述了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数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

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

相关文章

  • PyCharm中代码字体大小调整方法

    PyCharm中代码字体大小调整方法

    在本篇文章里小编给大家分享了关于PyCharm中代码字体大小调整方法以及相关知识点,需要的朋友们学习下。
    2019-07-07
  • python matplotlib中的subplot函数使用详解

    python matplotlib中的subplot函数使用详解

    今天小编就为大家分享一篇python matplotlib中的subplot函数使用详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-01-01
  • 解决pyqt5异常退出无提示信息的问题

    解决pyqt5异常退出无提示信息的问题

    这篇文章主要介绍了解决pyqt5异常退出无提示信息的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-04-04
  • python使用代理IP爬取猫眼电影专业评分数据

    python使用代理IP爬取猫眼电影专业评分数据

    在编写爬虫程序的过程中,IP封锁无疑是一个常见且棘手的问题,尽管网络上存在大量的免费IP代理网站,但其质量往往参差不齐,令人堪忧,本篇文章中介绍一下如何使用Python的Requests库和BeautifulSoup库来抓取猫眼电影网站上的专业评分数据,需要的朋友可以参考下
    2024-03-03
  • 浅析Flask如何使用日志功能

    浅析Flask如何使用日志功能

    这篇文章主要为大家详细介绍了Flask是如何使用日志功能的,文中的示例代码讲解详细,对我们深入了解Flask有一定的帮助,需要的可以参考一下
    2023-05-05
  • Python中的变量与常量

    Python中的变量与常量

    本文基于Python基础,主要介绍了Python基础中变量和常量的区别,对于变量的用法做了详细的讲解,用丰富的案例 ,代码效果图的展示帮助大家更好理解,需要的朋友可以参考下
    2021-11-11
  • python实现批量修改服务器密码的方法

    python实现批量修改服务器密码的方法

    这篇文章主要介绍了python实现批量修改服务器密码的方法,本文通过实例代码给大家介绍的非常详细,具有一定的参考借鉴价值 ,需要的朋友可以参考下
    2019-08-08
  • Python打开文件,将list、numpy数组内容写入txt文件中的方法

    Python打开文件,将list、numpy数组内容写入txt文件中的方法

    今天小编就为大家分享一篇Python打开文件,将list、numpy数组内容写入txt文件中的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-10-10
  • python目录与文件名操作例子

    python目录与文件名操作例子

    这篇文章主要介绍了python目录与文件名操作例子,需要的朋友可以参考下
    2016-08-08
  • Python matplotlib中更换画布背景颜色的3种方法

    Python matplotlib中更换画布背景颜色的3种方法

    这篇文章主要给大家介绍了关于Python matplotlib中更换画布背景颜色的3种方法,在Matplotlib中,我们可以使用set_facecolor()方法来设置背景颜色,文中通过图文以及代码介绍的非常详细,需要的朋友可以参考下
    2023-11-11

最新评论