【问题标题】:how to compare hierarchical regression models in python?如何比较python中的层次回归模型?
【发布时间】:2020-07-07 14:10:05
【问题描述】:

我拟合了两个回归模型,一个只有 1 个预测变量,另一个有 3 个预测变量。现在我想比较这两个模型。我怎样才能做到这一点?我知道如何在 R 中做到这一点,但不知道如何在 python 中做到这一点。这是 R 中用于比较两个模型的代码 -

anova(albumSales.2, albumSales.3)

结果 -

Model 1: sales ~ adverts
Model 2: sales ~ adverts + airplay + attract
  Res.Df    RSS Df Sum of Sq      F    Pr(>F)    
1    198 862264                                  
2    196 434575  2    427690 96.447 < 2.2e-16 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
> 

基于上述结果,我们可以看到,与 albumSales.2 相比,albumSales.3 显着提高了模型对数据的拟合度,F(2, 196) = 96.44, p

我如何在 python 中做到这一点?

【问题讨论】:

    标签: python statistics statsmodels anova


    【解决方案1】:

    在方差分析中,您基本上计算 RSS 的差异。 您可以在vignette for ANOVA in statsmodels下查看更多信息:

    import pandas as pd
    import seaborn as sns
    import numpy as np
    
    iris = sns.load_dataset('iris')
    
    from statsmodels.formula.api import ols
    from statsmodels.stats.anova import anova_lm
    
    iris.head()
    
        sepal_length    sepal_width petal_length    petal_width species
    0   5.1 3.5 1.4 0.2 setosa
    1   4.9 3.0 1.4 0.2 setosa
    2   4.7 3.2 1.3 0.2 setosa
    3   4.6 3.1 1.5 0.2 setosa
    4   5.0 3.6 1.4 0.2 setosa
    

    我们运行两个模型并进行方差分析:

    full_lm = ols("sepal_length ~ petal_length+petal_width", data=iris).fit()
    reduced_lm = ols("sepal_length ~ petal_length", data=iris).fit()
    anova_lm(reduced_lm,full_lm)
    
        df_resid    ssr df_diff ss_diff F   Pr(>F)
    0   148.0   24.525034   0.0 NaN NaN NaN
    1   147.0   23.880694   1.0 0.64434 3.9663  0.048272
    

    它会引发一些警告(您可以在我上面链接的网站上看到它),因为对于第一行它无法计算 F 等。

    注意,这与计算其他答案中提出的 Rsquare 不同。需要注意的一个重要问题是,如果您包含更多项,理论上您的 R 平方会增加,并且您想查看这些项是否显着解释了额外的方差,这就是您使用方差分析的原因。

    【讨论】:

      【解决方案2】:

      我不知道有一个函数可以直接比较两个模型作为 R 的样本,但是 Scikit-Learn 包是数据科学和机器学习中非常常用的 Python 包。它支持与回归模型相关的各种指标,让您可以创建自己的比较。

      例如,它支持 R2 度量。下面的例子来自 Scikit 的documentation on R2

      >>> from sklearn.metrics import r2_score
      >>> y_true = [3, -0.5, 2, 7]
      >>> y_pred = [2.5, 0.0, 2, 8]
      >>> r2_score(y_true, y_pred)
      0.948...
      >>> y_true = [[0.5, 1], [-1, 1], [7, -6]]
      >>> y_pred = [[0, 2], [-1, 2], [8, -5]]
      >>> r2_score(y_true, y_pred,
      ...          multioutput='variance_weighted')
      0.938...
      >>> y_true = [1, 2, 3]
      >>> y_pred = [1, 2, 3]
      >>> r2_score(y_true, y_pred)
      1.0
      >>> y_true = [1, 2, 3]
      >>> y_pred = [2, 2, 2]
      >>> r2_score(y_true, y_pred)
      0.0
      >>> y_true = [1, 2, 3]
      >>> y_pred = [3, 2, 1]
      >>> r2_score(y_true, y_pred)
      -3.0
      

      通过对您的两个模型执行此操作,您可以获得与从 R 获得的类似比较。

      【讨论】:

        猜你喜欢
        • 2018-08-10
        • 1970-01-01
        • 1970-01-01
        • 2021-08-15
        • 1970-01-01
        • 2014-10-13
        • 2019-10-15
        • 1970-01-01
        • 2016-02-27
        相关资源
        最近更新 更多