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

Different GLM result for Python and R with binomial regression

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

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

结果是

但是,当我在 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()

使用 创建的多项式函数 那么结果是

According to the documentation, the statsmodels GLM does not automatically include an intercept term, which the R model does. Try including a column of ones in the matrix you pass as exog to the sm.GLM. The documentation notes a convenience function exists for this very purpose: statsmodels.tools.add_constant.