我正在尝试获取 GLM 中每个协变量的 F 统计量和 p 值。在 Python 中,我使用 stats mode.formula.api 来执行 GLM。
formula = 'PropNo_Pred ~ Geography + log10BMI + Cat_OpCavity + CatLes_neles + CatRural_urban + \
CatPred_Control + CatNative_Intro + Midpoint_of_study'
mod1 = smf.glm(formula=formula, data=A2, family=sm.families.Binomial()).fit()
mod1.summary()
之后,我尝试使用 statsmodels.stats 中的方差分析对该模型进行方差分析
table1 = anova_lm(mod3)
print table1
但是我收到一条错误消息: “GLMResults”对象没有属性“ssr”
看起来这个 anova_lm 函数只适用于线性模型 python 中是否有一个模块可以对 GLM 进行 anova 测试?
最佳答案
这是我尝试推出你自己的。
嵌套模型的 F 统计量定义为:
(D_s - D_b)/(addtl_parameters * phi_b)
地点:
D_s
是小模型的偏差D_b
是较大(“大)”模型的偏差addtl_parameters
是模型之间自由度的差异。phi_b
是较大模型的色散参数估计值'
“统计理论说,F-statistic
服从 F 分布,分子自由度等于
添加的参数和等于 n - p_b
的分母自由度,或数字
记录减去大模型中的参数数量。”
我们将其转化为代码:
from scipy import stats
def calculate_nested_f_statistic(small_model, big_model):
"""Given two fitted GLMs, the larger of which contains the parameter space of the smaller, return the F Stat and P value corresponding to the larger model adding explanatory power"""
addtl_params = big_model.df_model - small_model.df_model
f_stat = (small_model.deviance - big_model.deviance) / (addtl_params * big_model.scale)
df_numerator = addtl_params
# use fitted values to obtain n_obs from model object:
df_denom = (big_model.fittedvalues.shape[0] - big_model.df_model)
p_value = stats.f.sf(f_stat, df_numerator, df_denom)
return (f_stat, p_value)
这是一个可重现的示例,遵循 statsmodels ( https://www.statsmodels.org/stable/glm.html ) 中的 gamma GLM 示例:
import numpy as np
import statsmodels.api as sm
data2 = sm.datasets.scotland.load()
data2.exog = sm.add_constant(data2.exog, prepend=False)
big_model = sm.GLM(data2.endog, data2.exog, family=sm.families.Gamma()).fit()
# Drop one covariate (column):
smaller_model = sm.GLM(data2.endog, data2.exog[:, 1:], family=sm.families.Gamma()).fit()
# Using function defined in answer:
calculate_nested_f_statistic(smaller_model, big_model)
# (9.519052917304652, 0.004914748992474178)
来源: https://www.casact.org/pubs/monographs/papers/05-Goldburd-Khare-Tevet.pdf
关于python - 在 python 中对 GLM 进行 Anova 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27328623/