欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python實現(xiàn)的簡單線性回歸算法實例分析

 更新時間:2018年12月26日 12:01:42   作者:瘋琴  
這篇文章主要介紹了Python實現(xiàn)的簡單線性回歸算法,結(jié)合實例形式分析了線性回歸算法相關(guān)原理、功能、用法與操作注意事項,需要的朋友可以參考下

本文實例講述了Python實現(xiàn)的簡單線性回歸算法。分享給大家供大家參考,具體如下:

用python實現(xiàn)R的線性模型(lm)中一元線性回歸的簡單方法,使用R的women示例數(shù)據(jù),R的運行結(jié)果:

> 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實現(xiàn)的功能包括:

  1. 計算pearson相關(guān)系數(shù)
  2. 使用最小二乘法計算回歸系數(shù)
  3. 計算擬合優(yōu)度判定系數(shù)R2R2
  4. 計算估計標(biāo)準(zhǔn)誤差Se
  5. 計算顯著性檢驗的F和P值
import numpy as np
import scipy.stats as ss
class Lm:
  """簡單一元線性模型,計算回歸系數(shù)、擬合優(yōu)度的判定系數(shù)和
  估計標(biāo)準(zhǔn)誤差,顯著性水平"""
  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
  # 計算協(xié)方差
  @staticmethod
  def cov_custom(x, y):
    result = sum((x - np.mean(x)) * (y - np.mean(y))) / (len(x) - 1)
    return result
  # 計算相關(guān)系數(shù)
  @staticmethod
  def corr_custom(x, y):
    return Lm.cov_custom(x, y) / (np.std(x, ddof=1) * np.std(y, ddof=1))
  # 計算回歸系數(shù)
  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
  # 計算擬合優(yōu)度的判定系數(shù)R方,即相關(guān)系數(shù)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
  # 計算估計標(biāo)準(zhǔn)誤差
  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執(zhí)行結(jié)果:

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

其中求回歸系數(shù)時用矩陣轉(zhuǎn)置求逆再用numpy內(nèi)置的解線性方程組的方法是最快的:

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)

更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python數(shù)學(xué)運算技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門與進階經(jīng)典教程

希望本文所述對大家Python程序設(shè)計有所幫助。

相關(guān)文章

  • ?python中的元類metaclass詳情

    ?python中的元類metaclass詳情

    這篇文章主要介紹了python中的metaclass詳情,在python中的metaclass就是幫助developer實現(xiàn)元編程,更多詳細內(nèi)容需要的小伙伴可以參考一下
    2022-05-05
  • 20非常有用的Python單行代碼分享

    20非常有用的Python單行代碼分享

    有用的 Python 單行代碼片段,只需一行代碼即可解決特定編碼問題!本文將分享20 個 Python 一行代碼,你可以在 30 秒或更短的時間內(nèi)輕松學(xué)習(xí)它們。這種單行代碼將節(jié)省你的時間,并使你的代碼看起來更干凈且易于閱讀
    2022-11-11
  • pytest中conftest.py使用小結(jié)

    pytest中conftest.py使用小結(jié)

    conftest.py文件是Pytest框架里面一個很重要的東西,本文主要介紹了pytest中conftest.py使用小結(jié),具有一定的參考價值,感興趣的可以了解一下
    2023-09-09
  • pytest解讀fixtures中yield與addfinalizer區(qū)別

    pytest解讀fixtures中yield與addfinalizer區(qū)別

    這篇文章主要為大家介紹了pytest官方解讀fixtures中yield與addfinalizer區(qū)別,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-06-06
  • 解決Pytorch中Batch Normalization layer踩過的坑

    解決Pytorch中Batch Normalization layer踩過的坑

    這篇文章主要介紹了解決Pytorch中Batch Normalization layer踩過的坑,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-05-05
  • 七種Python代碼審查工具推薦

    七種Python代碼審查工具推薦

    這篇文章主要介紹了七種Python代碼審查工具推薦,幫助大家更好的理解和學(xué)習(xí)使用python,感興趣的朋友可以了解下
    2021-03-03
  • pandas交換行的具體實現(xiàn)

    pandas交換行的具體實現(xiàn)

    Pandas?是專注于表格數(shù)據(jù)處理的?Python?第三方庫,能幫助我們完成各種各樣的表格數(shù)據(jù)操作,本文主要介紹了pandas交換行的具體實現(xiàn),具有一定的參考價值,感興趣的可以了解一下
    2024-04-04
  • 利用Python判斷你的密碼難度等級

    利用Python判斷你的密碼難度等級

    很多網(wǎng)站在用戶注冊賬號的時候為了保證賬戶的安全,都會自動檢測用戶密碼的強度并給出提醒讓用戶設(shè)置一個相對安全的密碼。這篇文章主要給大家介紹了關(guān)于利用Python判斷你的密碼難度等級,需要的朋友可以參考下
    2021-06-06
  • python利用Guetzli批量壓縮圖片

    python利用Guetzli批量壓縮圖片

    本篇文章主要介紹了python利用Guetzli批量壓縮圖片,詳細的介紹了谷歌的開源圖片壓縮工具Guetzli,非常具有實用價值,需要的朋友可以參考下。
    2017-03-03
  • Pycharm打印大數(shù)據(jù)文件顯示不全的解決方法

    Pycharm打印大數(shù)據(jù)文件顯示不全的解決方法

    這篇文章主要介紹了Pycharm打印大數(shù)據(jù)文件顯示不全的解決方法,昨晚寫了個小爬蟲,簡單分析下發(fā)現(xiàn)可以修改請求的url,直接獲取所有目標(biāo)的數(shù)據(jù),想先打印在控制臺看看,發(fā)現(xiàn)打印的數(shù)據(jù)不全,所以本文記錄了一下解決方法,需要的朋友可以參考下
    2024-03-03

最新評論