带有二项式回归的Python和R的不同GLM结果

问题描述

我有以下带有二项式回归的R代码适合x的y和多项式

res = glm(df.mat ~ poly(x,deg=degree),family=binomial(link="logit"))

结果是

R code result

但是,当我在Python中使用 statsmodels GLM函数时,

import statsmodels.api as sm

def poly(x,d):
    x = np.array(x)
    X = np.transpose(np.vstack((x**k for k in range(d+1))))
    return np.linalg.qr(X)[0][:,1:]

res_m = sm.GLM(np.array(df_mat),poly(x,7),family = sm.families.Binomial())
result = res_m.fit()

具有由Python equivalent to R poly() function?创建的多项式函数 那么结果是

Python result

解决方法

According to the documentation,statsmodels GLM不会自动包含R模型所包含的拦截项。尝试在您作为exog传递给sm.GLM的矩阵中包括一列。文档指出,为此目的存在一个便捷功能:statsmodels.tools.add_constant