这里是一个AIC的示例实现,来自于之前回答中提供的链接。
from statsmodels.regression.linear_model import OLS
from statsmodels.tools import add_constant
import numpy as np
from sklearn import linear_model
x = np.array([1,2,3,4,5])
y = np.array([0.3, 0.4, 0.4, 0.5, 0.6])
p = 1+1
lr = linear_model.LinearRegression()
lr = lr.fit(x.reshape(-1, 1), y)
pr = lr.predict(x.reshape(-1, 1))
def llf_(y, X, pr):
nobs = float(X.shape[0])
nobs2 = nobs / 2.0
nobs = float(nobs)
resid = y - pr
ssr = np.sum((resid)**2)
llf = -nobs2*np.log(2*np.pi) - nobs2*np.log(ssr / nobs) - nobs2
return llf
def aic(y, X, pr, p):
llf = llf_(y, X, pr)
return -2*llf+2*p
regr = OLS(y, add_constant(x.reshape(-1, 1))).fit()
print(regr.aic)
print(aic(y, x, pr, p))
输出:
-18.903519181693923
-18.903519181693916