python - 在 python 中对 GLM 进行 Anova 测试

标签 python statistics glm statsmodels

我正在尝试获取 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/

相关文章:

python - 使用 Scapy 缩短 TCP 有效负载会导致 [TCP 上一段未捕获]

python - 通过 pyodbc 连接到 Azure SQL 数据库

python - 获取 Python 函数的调用字符串,如在命令行中键入的那样

mysql - 在 MySQL GROUP BY 中计数 "repeats"

c++ - 如何使用 boost 正态分布类?

modeling - 如何将多个 roc 绘制在一起?

r - 使用 MCMCglmm 预先设置 G,具有分类响应和系统发育

python - 使用 Numba 在 Python 中求解最小二乘法

statistics - 使用 hadoop 进行简单统计计算的示例

r - 具有给定权重向量的ggplot平滑线glm模型