Statistical modeling with Python · Lesson 15 of 16

Comparing models: AIC and cross-validation

Choose between models with AIC and BIC, test nested models with a likelihood-ratio test, and score predictions on unseen data with cross-validation.

About 18 minutes · code runs in your browser, nothing to install

Adding predictors always makes a model fit the data it learned from a little better, even if the new predictor is pure noise. So "which model is better?" needs tools that charge a price for complexity or that test the model on data it has not seen. This lesson covers both.

AIC and BIC

The AIC (Akaike information criterion) is based on the log-likelihood (how probable the data are under the model) plus a penalty of 2 per coefficient. BIC uses a bigger penalty (log n per coefficient) and prefers smaller models. For both: lower is better, and only differences matter. As rules of thumb, a gap of 2 or less is small; 10 or more is strong.

Pythoneditable
import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf

df = pd.read_csv("students.csv")

formulas = {
    "hours": "passed ~ hours",
    "+ absences": "passed ~ hours + absences",
    "+ prep": "passed ~ hours + absences + C(prep)",
    "+ course": "passed ~ hours + absences + C(prep) + C(course)",
}
rows = []
for name, f in formulas.items():
    m = smf.glm(f, data=df, family=sm.families.Binomial()).fit()
    rows.append({"model": name, "k": len(m.params), "llf": m.llf,
                 "AIC": m.aic, "BIC": m.bic_llf})
print(pd.DataFrame(rows).round(1).to_string(index=False))
Output
     model  k   llf   AIC   BIC
     hours  2 -51.4 106.7 111.9
+ absences  3 -47.5 101.0 108.8
    + prep  4 -45.0  98.0 108.4
  + course  6 -38.3  88.7 104.3

k = number of coefficients. For GLMs use bic_llf: plain .bic uses an older formula and prints a warning in some versions.

How to read it: each step down to + prep lowers the AIC, so each predictor earns its place. Adding course lowers both again, by about 9 (AIC) and 4 (BIC): even with the harder penalty, the course is worth its two extra coefficients. The model with every predictor wins here.

Likelihood-ratio test for nested models

When one model is the other plus some extra terms (nested models), the likelihood-ratio test asks whether the extra terms improve the fit more than chance would. The statistic is 2 × (difference in log-likelihood), compared with a chi-square distribution whose degrees of freedom are the number of extra coefficients. It also tests a whole categorical variable at once, here both course coefficients together.

Pythoneditable
import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf

df = pd.read_csv("students.csv")

from scipy import stats

small = smf.glm("passed ~ hours + absences + C(prep)", data=df,
                family=sm.families.Binomial()).fit()
big = smf.glm("passed ~ hours + absences + C(prep) + C(course)", data=df,
              family=sm.families.Binomial()).fit()
lr = 2 * (big.llf - small.llf)
extra = len(big.params) - len(small.params)
p = stats.chi2.sf(lr, extra)
print(f"LR = {lr:.2f}, extra coefficients = {extra}, p = {p:.3f}")
Output
LR = 13.29, extra coefficients = 2, p = 0.001

p = 0.001: strong evidence that the course matters for passing, on top of hours, absences and prep. The AIC said the same. For linear models, sm.stats.anova_lm(small, big) does the same job with an F-test.

Prediction on new data: train and test

If the model will be used to predict, the honest test is data it never saw. train_test_split keeps part of the rows aside. scikit-learn needs numbers, so the yes/no prep column becomes a 0/1 column first. stratify=y keeps the pass rate the same in both parts, and random_state fixes which rows go where, so the result is repeatable.

Pythoneditable
import pandas as pd
from sklearn.linear_model import LogisticRegression

df = pd.read_csv("students.csv")
df["prep_yes"] = (df["prep"] == "yes").astype("int64")
X = df[["hours", "absences", "prep_yes"]]
y = df["passed"]

from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, roc_auc_score

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.3, random_state=1, stratify=y)
clf = LogisticRegression().fit(X_train, y_train)
print("train rows:", len(X_train), "test rows:", len(X_test))
print(f"test accuracy: {accuracy_score(y_test, clf.predict(X_test)):.3f}")
print(f"test AUC: {roc_auc_score(y_test, clf.predict_proba(X_test)[:, 1]):.3f}")
Output
train rows: 70 test rows: 30
test accuracy: 0.733
test AUC: 0.851
Note: scikit-learn's LogisticRegression applies L2 regularisation by default: a penalty that shrinks the coefficients towards 0 (C=1.0 by default; a larger C means less shrinking), so its coefficients differ from statsmodels', which are unpenalised maximum likelihood. It is built for prediction, not for p-values.

Cross-validation. One split depends on luck: which 30 students landed in the test set. k-fold cross-validation splits the data into k parts, trains on k − 1 and tests on the last, k times, so every row is tested once. Report the mean (and the spread) of the k scores. If the rows of the file are in some order (by date, by class), shuffle them into folds with a fixed random_state so the result is repeatable.

Pythoneditable
import pandas as pd
from sklearn.linear_model import LogisticRegression

df = pd.read_csv("students.csv")
df["prep_yes"] = (df["prep"] == "yes").astype("int64")
X = df[["hours", "absences", "prep_yes"]]
y = df["passed"]

from sklearn.model_selection import StratifiedKFold, cross_val_score

folds = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
scores = cross_val_score(LogisticRegression(), X, y, cv=folds, scoring="roc_auc")
print("AUC per fold:", scores.round(3))
print(f"mean AUC: {scores.mean():.3f}")

small = cross_val_score(LogisticRegression(), X[["hours"]], y, cv=folds, scoring="roc_auc")
print(f"hours only: {small.mean():.3f}")
Output
AUC per fold: [0.879 0.828 0.778 0.885 0.818]
mean AUC: 0.838
hours only: 0.823

The full model ranks unseen students only a little better than hours alone (0.838 against 0.823): on new data, the extra predictors help less than the training fit suggested. That is exactly what cross-validation is for. The same function works for linear regression with scoring="r2", as in the exercise.

✎ Exercise

Use cross_val_score with LinearRegression() and the folds given (cv=folds) to predict score from hours and absences (scoring="r2"). Print the five scores and their mean, both rounded to 3 decimals.

Hint: cross_val_score(LinearRegression(), df[["hours", "absences"]], df["score"], cv=folds, scoring="r2")

Your codewrite your answer, then Run
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import KFold, cross_val_score

df = pd.read_csv("students.csv")
folds = KFold(n_splits=5, shuffle=True, random_state=0)
# your code here

Expected output:

[0.585 0.351 0.448 0.518 0.284]
0.437
Show a solution
Solutioneditable
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import KFold, cross_val_score

df = pd.read_csv("students.csv")
folds = KFold(n_splits=5, shuffle=True, random_state=0)
scores = cross_val_score(LinearRegression(), df[["hours", "absences"]], df["score"],
                         cv=folds, scoring="r2")
print(scores.round(3))
print(round(float(scores.mean()), 3))
Output
[0.585 0.351 0.448 0.518 0.284]
0.437

Check yourself

1. Model A has AIC 110, model B has AIC 98 on the same data. Which is preferred?

2. When can you use a likelihood-ratio test?

3. Why use cross-validation instead of the accuracy on the training data?

Spotted a mistake on this page? Tell us