如何在Python中计算线性回归模型的AIC?

YNr*_*YNr 7 python linear-regression

我想为线性模型计算AIC以比较它们的复杂性.我做了如下:

regr = linear_model.LinearRegression()
regr.fit(X, y)

aic_intercept_slope = aic(y, regr.coef_[0] * X.as_matrix() + regr.intercept_, k=1)

def aic(y, y_pred, k):
   resid = y - y_pred.ravel()
   sse = sum(resid ** 2)

   AIC = 2*k - 2*np.log(sse)

return AIC
Run Code Online (Sandbox Code Playgroud)

但是我收到一个divide by zero encountered in log错误.

Bra*_*mon 9

sklearnLinearRegression是良好的预测,而是因为你已经发现初具雏形. statsmodels.regression.linear_model.OLS具有属性属性AIC和许多其他预先固定的属性.

但是,请注意,您需要手动将单位矢量添加到X矩阵中,以在模型中包含截距.

from statsmodels.regression.linear_model import OLS
from statsmodels.tools import add_constant

regr = OLS(y, add_constant(X)).fit()
print(regr.aic)
Run Code Online (Sandbox Code Playgroud)

如果您正在寻找另一种在仍然使用时手动编写的方法,则源位于此处sklearn.