我试图得到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中的ANOVA对这个模型进行方差分析。
table1 = anova_lm(mod3)
print table1但是,我看到一个错误:'GLMResults‘对象没有属性'ssr’。
看起来这个anova_lm函数只适用于线性模型,在python中是否有一个模块对GLMs进行anova测试?
发布于 2014-12-07 03:40:47
不幸的是没有。然而,您可以使用模型的假设测试方法对每个术语进行自己的操作。事实上,他们的一些ANOVA方法甚至不使用属性ssr (这是模型的平方残差之和,因此对于二项式GLM显然没有定义)。您可能可以修改此代码以进行GLM方差分析。
发布于 2020-03-20 06:08:37
这是我试着把你自己的。
嵌套模型的F统计量定义为:
(D_s - D_b ) / (addtl_parameters * phi_b)
其中:
D_s是小模型的偏差D_b是大(大)模型的偏差addtl_parameters是模型之间自由度的差异。phi_b是大模型的色散参数的估计统计理论认为F-统计服从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)下面是一个可重复的示例,遵循状态模型(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
https://stackoverflow.com/questions/27328623
复制相似问题