【问题标题】:Adjusted R square for each predictor variable in pythonpython中每个预测变量的调整R平方
【发布时间】:2018-07-26 20:01:09
【问题描述】:

我有一个包含多列的 pandas 数据框。我需要执行多元线性回归。在此之前,我想分析每个自变量相对于因变量的 R、R2、调整后的 R2 和 p 值。 对于 R 和 R2 我没有问题,因为我可以计算 R 矩阵并仅选择因变量,然后查看它与所有自变量之间的 R 系数。然后我可以将这些值平方以获得 R2。 我的问题是如何对调整后的 R2 和 p 值做同样的事情 最后我想要得到的是这样的东西:

 Variable     R        R2       ADJUSTED_R2   p_value
 A            0.4193   0.1758   ...
 B            0.2620   0.0686   ...
 C            0.2535   0.0643   ...

所有的值都与因变量有关,比如 Y。

【问题讨论】:

    标签: python pandas linear-regression p-value pearson-correlation


    【解决方案1】:

    以下内容不会为您提供所有答案,但可以帮助您使用 python、pandas 和 statsmodels 进行回归分析。


    给定这样的数据框...

    # Imports
    import pandas as pd
    import numpy as np
    import itertools
    
    # A datafrane with random numbers
    np.random.seed(123)
    rows = 12
    listVars= ['y','x1', 'x2', 'x3']
    rng = pd.date_range('1/1/2017', periods=rows, freq='D')
    df_1 = pd.DataFrame(np.random.randint(100,150,size=(rows, len(listVars))), columns=listVars) 
    df_1 = df_1.set_index(rng)
    
    print(df_1)
    

    ...您可以使用 statsmodels 库并更改以下 sn-p 中的result = model.rsquared 部分来获得任何回归结果:

    x = df_1['x1']
    x = sm.add_constant(x)
    model = sm.OLS(df_1['y'], x).fit()    
    result = model.rsquared
    print(result)
    

    现在你有了 r-squared。使用 model.pvalues 作为 p 值。并使用dir(model)仔细查看其他模型结果(输出中的内容比您在下面看到的要多):

    现在,这应该可以让您获得所需的结果。 要获得所有变量/列组合的理想结果,here 问题和答案应该会让您走得很远。

    编辑:您可以使用model.summary() 仔细查看一些常见的回归结果。将它与dir(model) 一起使用,您可以看到并非所有回归结果都可用与pvalues 使用model.pvalues 的方式相同。例如,要获得 Durbin-Watson,您必须使用 durbinwatson = sm.stats.stattools.durbin_watson(model.fittedvalues, axis=0)This post 已获得有关此问题的更多信息。

    【讨论】:

      猜你喜欢
      • 2016-08-28
      • 2019-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-26
      • 2021-08-19
      • 2011-02-21
      相关资源
      最近更新 更多