首页 > 解决方案 > 如何对线性和对数线性模型应用 statsmodels.stats.diagnostic.compare_j 测试

问题描述

我想statsmodels.stats.diagnostic.compare_j对线性和对数线性模型进行测试。线性模型公式为

Sale_Price ~ Overall_Qual + Gr_Liv_Area + Neighborhood + MS_SubClass + Bsmt_Exposure + Roof_Matl + Misc_Feature + Overall_Cond + Year_Built + Bsmt_Full_Bath + Total_Bsmt_SF + 1.

对数线性模型公式为

np.log(Sale_Price) ~ Overall_Qual + Gr_Liv_Area + Neighborhood + MS_SubClass + Bsmt_Exposure + Roof_Matl + Misc_Feature + Overall_Cond + Year_Built + Bsmt_Full_Bath + Total_Bsmt_SF + 1

(相同的功能,但np.log(Sale_Price)不是Sale_Price)。

当我运行测试时出现错误

ValueError: endogenous variables in models are not the same

是否可以使用这种方法比较线性和对数线性模型?在这种情况下是否有任何意义或没有模型优于?因为如果我尝试解决方法

log_model.model.endog = np.exp(log_model.model.endog)

我明白了

ValueError: The exog in results_x and in results_z are nested. J comparison requires that models are non-nested.

标签: pythonstatisticsstatsmodels

解决方案


我不知道您是否正在使用数据框,您需要使用日志 Sale_Price 创建一个新列并使用它进行回归:

df['log_Sale_Price'] = np.log(df['Sale_Price'])
mod = smf.ols(formula='log_Sale_Price ~ Overall_Qual + Gr_Liv_Area..', data=df)

至于你的第二个问题,你不应该使用statsmodels.stats.diagnostic.compare_j,因为因变量在不同的尺度上。这个函数应该在 R 中实现 J 测试,所以根据手册:

J 检验统计量只是增强模型中拟合值的边际检验。

由于对数模型的预测值与未记录的值不同,因此这不起作用。

如果我理解你的问题,你想看看你的因变量的对数转换是否更适合。

转换因变量的主要原因是确保残差更接近高斯分布。您可以简单地绘制残差与预测值来检查这种关系,例如在这个例子中。您还可以应用Breusch-Pagan 测试并检查它是否通过对数转换得到改善。


推荐阅读