如何比较python中的分层回归模型?

2024-04-28 09:10:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我拟合了两个回归模型,一个只有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.3与albumSales.2相比,显著提高了模型与数据的拟合度。F(2196)=96.44,p<。001.

我如何用python实现它


Tags: of代码模型dfmodelsqres因子
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

在方差分析中,您基本上计算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平方会增加,你想看看这些项是否能显著解释额外的方差,这就是为什么你要使用方差分析

相关问题 更多 >