Skip to content

Comparing many models at once

Rank each model per fold, test the ranks with Friedman, and read which models the critical difference can separate. Know what these tests can claim, and what they can't.

Advanced ~10 min8 steps

What runs in CodeSplash

You will be able to

  • Read a critical difference diagram
  • Explain the Friedman test with the Nemenyi follow-up on fold ranks
  • Say why rank tests order models, not settle pairs

Read first

01

Ten scores

Read

Pima, seven features, same folds. Cross-validated AUC:

ModelAUC
Elastic net0.858
Logistic0.857
Small neural network0.856
Naive Bayes0.845
Extra trees0.844
XGBoost0.843
Random forest0.835
LightGBM0.829
Histogram boosting0.822
Single tree0.777

Where would you draw a line? The top of that table isn't far from the middle.

02

Many pairs inflate false alarms

Explore

Ten models make 45 pairs. Raise Tests to 45, with no real effects, and read how likely at least one false alarm is. Then see what a correction costs.

BExplorable · The family-wise error rate

If you run many tests, how likely is at least one false alarm, and what does correcting cost?

Without correction, how often does this family produce at least one false alarm?

0.50
How sure?
45
0
3.0
0.050
Simulating…

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

That's why comparing many models starts with one question: do they differ at all?

03

Ranks across folds

Read

The Friedman testFriedman testRank test for differences between conditions measured on the same subjects, or models scored on the same folds. ranks the models within each fold (1 = best), then asks whether the mean ranks differ by more than chance. The app reports it with Iman–Davenport's F.

The critical differenceCritical difference (CD)The smallest gap in average rank that counts as significant in a Nemenyi comparison. (Nemenyi) then says how far apart two mean ranks must be:

CD=qαk(k+1)6NCD = q_\alpha \sqrt{\frac{k(k+1)}{6N}}

for kk models on NN folds. Holm-adjusted tests compare each model with the best-ranked one.

04

Read the diagram

Predict

Predict first

In the diagram below, two models sit under one thick bar. What does the bar say?

They differ reliablyThe test can't separate themThe right-hand one is better
Reveal

The test can't separate them. A bar joins models whose mean ranks are closer than the critical difference. It doesn't say they're equal. With only 5 folds, CDCD is large, so wide bars are common.

Critical-difference diagramAcross folds, which models are reliably better than which?
View data
modelmean rank
Gradient boosting1.660
Random forest2.030
Elastic net2.930
k-nearest neighbors3.980
Decision tree4.470
05

What these tests can't claim

Read

Folds aren't independent datasets: they share training rows, so rank tests are optimistic. In the app they order the models. Claims about one pair should rest on the corrected t or the Bayesian test.

Demšar's method was designed for many independent datasets. Using folds of one dataset is a convenient reading aid, not a formal result.

Cochran's QCochran's Q testTests whether yes/no outcomes differ across three or more matched conditions, or models scored on the same rows. asks on the locked test rows whether all the error rates are equal. For a 5×25 \times 2-fold plan, the app adds Dietterich's 5×2cv5×2 cross-validation testCompares two models with five repeats of 2-fold cross-validation; keeps false alarms near α, unlike a naive t-test. paired t and Alpaydin's combined F.

06

Check your understanding

Checkpoint

Check yourself

You compare 12 models. How many pairs is that?

Show the answer

Answer: 66

12×11/2=6612 \times 11 / 2 = 66. Testing each at 5% alone would almost guarantee false alarms.

Check yourself

For k=3k = 3 models on N=5N = 5 folds, with q0.05=2.343q_{0.05} = 2.343, what is the critical difference? Give two decimals.

Show the answer

Answer: 1.48

2.343×(3×4)/(6×5)=2.343×0.632≈1.482.343 \times \sqrt{(3 \times 4)/(6 \times 5)} = 2.343 \times 0.632 \approx 1.48. Out of a possible gap of 2 in mean rank, that's a high bar.

Check yourself

Why treat the Friedman result on folds as a guide, not a proof?

Show the answer

Answer: a

The test assumes independent blocks. Folds overlap, which makes it optimistic.

07

Compare a shortlist

In the app

On the Leaderboard, tick three or more runs and press Compare. You'll get the mean-rank table, the Friedman result and a critical difference diagram alongside the pairwise table. To firm things up, raise Repeats in Validation for a new set of runs.

Python
import numpy as np
import pandas as pd
from scipy import stats
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.naive_bayes import GaussianNB
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.tree import DecisionTreeClassifier

df = pd.read_csv("pima.csv")
X, y = df.drop(columns="diabetic"), df["diabetic"]
cv = StratifiedKFold(5, shuffle=True, random_state=1)
models = {"logit": make_pipeline(StandardScaler(), LogisticRegression()), "nb": GaussianNB(),
          "forest": RandomForestClassifier(200, random_state=1),
          "tree": DecisionTreeClassifier(max_depth=6, random_state=1)}
scores = np.array([cross_val_score(m, X, y, cv=cv, scoring="roc_auc") for m in models.values()])
print(stats.friedmanchisquare(*scores))
ranks = stats.rankdata(-scores, axis=0).mean(axis=1)
print(dict(zip(models, ranks.round(2))))
R
library(ranger)
library(rpart)
df <- rbind(MASS::Pima.tr, MASS::Pima.te)
set.seed(1)
fold <- sample(rep(1:5, length.out = nrow(df)))
auc <- function(y, p) as.numeric(pROC::auc(y, p, quiet = TRUE))
scores <- t(sapply(1:5, function(k) {
  tr <- df[fold != k, ]; te <- df[fold == k, ]
  c(logit = auc(te$type, predict(glm(type ~ ., binomial, tr), te, type = "response")),
    nb = auc(te$type, predict(e1071::naiveBayes(type ~ ., tr), te, type = "raw")[, "Yes"]),
    forest = auc(te$type, predict(ranger(type ~ ., tr, num.trees = 200, probability = TRUE, seed = 1), te)$predictions[, "Yes"]),
    tree = auc(te$type, predict(rpart(type ~ ., tr, control = rpart.control(maxdepth = 6, cp = 0)), te)[, "Yes"]))
}))
friedman.test(scores)
round(colMeans(t(apply(-scores, 1, rank))), 2)
08

Recap

Recap
  • Many pairs inflate false alarms, so rank the models across folds and test the ranks first.
  • A critical difference diagram shows which models can't be separated.
  • Folds aren't independent. Use these results to shortlist, and the corrected tests for pairs.

Concepts in this lesson