• Simple Linear Regression:ONE


    前言


    对于一些库的说明
    numpy:支持矩阵运算,在矩阵运算这方面可以完全替代基于向量编程的matlab
    pandas:这个是一个数据存储库,是以表单(dataframe)为基本单位,这个库的好处在于行列
    索引并不是规定死的0和1(numpy就是规定死了的,numpy是以矩阵作为基本单位),索引可以改为文字
    数字等符号,灵活性很好
    scipy:一个科学运算的库,里面封装了很多科学计算的模块
    statsmodels:这是一个包含很多统计模型的库,这个是统计学学生最常用的库了
    前面这四个库是回归课程里面最常用的库,当然这门课程要求的编程能力不高,主要掌握应用回归的
    内核即可,毕竟现在很多软件都能做应用回归,甚至比python更方便

    案例 

    对于森林火灾数据进行线性回归分析

    1. import numpy as np
    2. import statsmodels.api as sm
    3. import statsmodels.formula.api as smf
    4. import matplotlib.pyplot as plt
    5. import pandas as pd
    6. from patsy import dmatrices#patsy.dmatrices把数据按要求分割
    7. from statsmodels.stats.api import anova_lm#anova_lm计算方差
    8. import scipy

    #  Load data
     

    1. df = pd.read_csv('C:/Users/33035/Desktop/data2.1.csv')
    2. df.head(15)

    #显示所有列

    pd.set_option('display.max_columns',None)

    #显示所有行

    pd.set_option('display.max_rows', None)

    #设置value的显示长度为100,默认为50

    pd.set_option('max_colwidth',200)

    # 计算相关系数

    1. cor_matrix = df.corr(method='pearson') # 使用皮尔逊系数计算列与列的相关性
    2. #cor_matrix = df.corr(method='kendall')使用Kendall计算算列与列的相关性
    3. #cor_matrix = df.corr(method='spearman')使用spearman计算列与列的相关性
    4. print(cor_matrix)

    #answer

              x         y
    x  1.000000  0.960978
    y  0.960978  1.000000
    

    #一元线性回归建模(最小二乘法)

    1. # ==========第一种建模方式======================================
    2. # y,X = dmatrices('y~x', data=df, return_type = 'dataframe')
    3. # print(X)
    4. # mod = sm.OLS(y,X)
    5. # result = mod.fit()
    6. # ==========第二种建模方式(类R语言方式)======================================
    7. result = smf.ols('y~x', data=df).fit()
    8. #值得注意的是:'y是因变量对于x自变量,数据是df中的数据,
    9. 进行ols(最小二乘法)来进行线性回归拟合,自变量与因变量的符号要与df中的符号一致,
    10. 不然无法定位数据'
    1. print(result.summary())#summary摘要,
    2. 注意的是在进行ols返回的结果已经把线性回归中所需要的计算量都已经计算好了,
    3. 存在result里面,现在把概要以表单形式返回

                                OLS Regression Results                           
    ==============================================================================
    Dep. Variable:                      y   R-squared:                       0.923
    Model:                            OLS   Adj. R-squared:                  0.918
    Method:                 Least Squares   F-statistic:                     156.9
    Date:                Wed, 28 Sep 2022   Prob (F-statistic):           1.25e-08
    Time:                        16:46:19   Log-Likelihood:                -32.811
    No. Observations:                  15   AIC:                             69.62
    Df Residuals:                      13   BIC:                             71.04
    Df Model:                           1                                        
    Covariance Type:            nonrobust                                        
    ==============================================================================
                     coef    std err          t      P>|t|      [95.0% Conf. Int.]
    ------------------------------------------------------------------------------
    Intercept     10.2779      1.420      7.237      0.000         7.210    13.346
    x              4.9193      0.393     12.525      0.000         4.071     5.768
    ==============================================================================
    Omnibus:                        2.551   Durbin-Watson:                   1.318
    Prob(Omnibus):                  0.279   Jarque-Bera (JB):                1.047
    Skew:                          -0.003   Prob(JB):                        0.592
    Kurtosis:                       1.706   Cond. No.                         9.13
    ==============================================================================
     

    # 注解

    Intercept:截距,对应于p0 x:x前的系数,对应于p1 coef:p0 p1 系数估计值 t分布:看p值与0.05比较 conf int:参数估计的置信区间

    Intercept:截距,对应于p0
    x:x前的系数,对应于p1
    coef:p0 p1 系数估计值
    t分布:看p值与0.05比较
    conf int:参数估计的置信区间'

    y_fitted = result.fittedvalues#把拟合曲线上的y值调出来
    print(y_fitted)
    0     27.003653
    1     19.132724
    2     32.906850
    3     21.592389
    4     25.527854
    5     37.334248
    6     13.721460
    7     25.035921
    8     23.068188
    9     31.431051
    10    20.608523
    11    15.689192
    12    40.285846
    13    33.890716
    14    28.971385
    dtype: float64
    
    

    #画图(线性回归) 

    1. fig, ax = plt.subplots(figsize=(8, 6))#fig是画布,ax是坐标系
    2. ax.plot(df['x'], df['y'], 'o', label='data')
    3. ax.plot(df['x'], y_fitted, 'r-', label='OLS')
    4. ax.legend(loc='best')
    5. plt.show()

    # 方差分析(F检验:对整个模型进行分析,看P值<0.05)

    1. table = anova_lm(result, typ=2)#对于结果进行方差分析即可,
    2. 会自动匹配到result对应的估计值与实际值 、均值等所需数据

    print(table)
                  sum_sq    df          F        PR(>F)
    x         841.766358   1.0  156.88616  1.247800e-08
    Residual   69.750975  13.0        NaN           NaN
    

    # pearson相关系数检验(看x与y的相关性程度:这一步感觉放在回归前更好)

    1. cortest = scipy.stats.pearsonr(df['x'], df['y'])
    2. print(cortest)
    (0.96097771513210861, 1.2478000079204785e-08)
    

    # 计算残差(比3大的就是异常值)

    1. eres = result.resid
    2. print(eres)
    0    -0.803653
    1    -1.332724
    2    -1.606850
    3     1.507611
    4     1.972146
    5    -1.334248
    6     0.378540
    7    -2.735921
    8    -3.468188
    9    -0.131051
    10    3.391477
    11    1.610808
    12    2.914154
    13    2.509284
    14   -2.871385
    dtype: float64
    

    # 标准化残差(找比3大的就是异常值)

    1. stand_eres = eres / np.sqrt(result.scale)  # eres.std()
    2. print(stand_eres)
    0    -0.346949
    1    -0.575356
    2    -0.693700
    3     0.650857
    4     0.851404
    5    -0.576014
    6     0.163421
    7    -1.181136
    8    -1.497267
    9    -0.056576
    10    1.464149
    11    0.695409
    12    1.258082
    13    1.083294
    14   -1.239618
    dtype: float64
    

    # 学生化残差(找比3大的就是异常值)

    1. infl = result.get_influence()#学生化残差已经算好存在result中,只需要调用即可
    2. # studentied_eres = infl.summary_table()
    3. studentied_eres = infl.resid_studentized_internal
    4. print(studentied_eres)
    [-0.35920557 -0.61671822 -0.7381288   0.68389288  0.88172686 -0.64739155
      0.18972092 -1.2240712  -1.56097482 -0.05952374  1.54912299  0.77909572
      1.49866138  1.16347978 -1.28850409]
    

    #置信区间(想看参数估计的置信区间,这里的做法好在我可以调alpha)

    1. confinterval = result.conf_int(alpha=0.05, cols=None)
    2. print(confinterval)
    '
    运行
                      0          1
    Intercept  7.209605  13.346252
    x          4.070851   5.767811
    

    以上就是已经把回归模型训练好了(回归模型对象为result)
    下面进行应用


    # 预测新值

    1. # 单值
    2. predictvalues = result.predict(pd.DataFrame({'x': [3.5]}))
    3. #需要注意的是pandas的基本单位是表单df,所以预测的x应该是以表单形式写入“键”:[值]
    4. print(predictvalues)
    [ 27.49558609]
    

    1. # 单值
    2. predictvalues = result.predict(pd.DataFrame({'x': [3.5]}))
    3. #需要注意的是pandas的基本单位是表单df,所以预测的x应该是以表单形式写入“键”:[值]
    4. print(predictvalues)
    [ 27.49558609  28.47945224]

    代码总述

     

    1. # -*- coding: UTF-8 -*-
    2. import numpy as np
    3. import statsmodels.api as sm
    4. import statsmodels.formula.api as smf
    5. import matplotlib.pyplot as plt
    6. import pandas as pd
    7. #from patsy import dmatrices
    8. from statsmodels.stats.api import anova_lm
    9. import scipy
    10. # 显示所有列
    11. pd.set_option('display.max_columns', None)
    12. # 显示所有行
    13. pd.set_option('display.max_rows', None)
    14. # 设置value的显示长度为100,默认为50
    15. pd.set_option('max_colwidth', 200)
    16. # # Load data
    17. df = pd.read_csv('data2.1.csv')
    18. # 计算相关系数
    19. cor_matrix = df.corr(method='pearson') # 使用皮尔逊系数计算列与列的相关性
    20. # cor_matrix = df.corr(method='kendall')
    21. # cor_matrix = df.corr(method='spearman')
    22. # print(cor_matrix)
    23. # ==========第一种建模方式======================================
    24. # y,X = dmatrices('y~x', data=df, return_type = 'dataframe')
    25. # print(X)
    26. # mod = sm.OLS(y,X)
    27. # result = mod.fit()
    28. # ==========第二种建模方式(类R语言方式)======================================
    29. result = smf.ols('y~x', data=df).fit()
    30. # print(result.params)
    31. print(result.summary())
    32. y_fitted = result.fittedvalues
    33. fig, ax = plt.subplots(figsize=(8, 6))
    34. ax.plot(df['x'], df['y'], 'o', label='data')
    35. ax.plot(df['x'], y_fitted, 'r-', label='OLS')
    36. ax.legend(loc='best')
    37. # plt.show()
    38. # 方差分析
    39. table = anova_lm(result, typ=2)
    40. # print(table)
    41. # print(result.scale)
    42. # pearson相关系数检验
    43. cortest = scipy.stats.pearsonr(df['x'], df['y'])
    44. print(cortest)
    45. # 计算残差
    46. eres = result.resid
    47. # print(eres)
    48. fig, ax = plt.subplots(figsize=(8, 6))
    49. ax.plot(eres, 'o', label='resid')
    50. # plt.show()
    51. # 标准化残差
    52. stand_eres = eres / np.sqrt(result.scale) # eres.std()
    53. print(stand_eres)
    54. # 学生化残差
    55. infl = result.get_influence()
    56. # studentied_eres = infl.summary_table()
    57. studentied_eres = infl.resid_studentized_internal
    58. print(studentied_eres)
    59. ##置信区间
    60. confinterval = result.conf_int(alpha=0.05, cols=None)
    61. print(confinterval)
    62. # =========预测新值======================================================
    63. # 单值
    64. predictvalues = result.predict(pd.DataFrame({'x': [3.5]}))
    65. print(predictvalues)
    66. # 区间
    67. predictions = result.get_prediction(pd.DataFrame({'x': [3.5]}))
    68. print(predictions.summary_frame(alpha=0.05))

  • 相关阅读:
    分布式事务—基于消息补偿的最终一致性方案(本地消息表、消息队列)
    基于知识问答的上下文学习中的代码风格11.20
    C# 任务调度 c# TaskScheduler
    【原创】不同RTOS中POSIX接口的实现差异
    手把手教你使用Python写贪吃蛇游戏(pygame)
    Qt Design Studio
    2023-9-22 没有上司的舞会
    B. Phoenix and Beauty
    Easyexcel·读取excel
    短视频入口打开,重新定义小程序
  • 原文地址:https://blog.csdn.net/m0_56902859/article/details/127080157