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.
What runs in CodeSplash
- Friedman test (repeated measures, ranks) Verified in Python and R
- Cochran's Q test (several paired proportions) Verified in Python and R
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
Ten scores
ReadPima, seven features, same folds. Cross-validated AUC:
| Model | AUC |
|---|---|
| Elastic net | 0.858 |
| Logistic | 0.857 |
| Small neural network | 0.856 |
| Naive Bayes | 0.845 |
| Extra trees | 0.844 |
| XGBoost | 0.843 |
| Random forest | 0.835 |
| LightGBM | 0.829 |
| Histogram boosting | 0.822 |
| Single tree | 0.777 |
Where would you draw a line? The top of that table isn't far from the middle.
Many pairs inflate false alarms
ExploreTen 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?
Commit your prediction above to see the result
Make your prediction to see the result.
That's why comparing many models starts with one question: do they differ at all?
Ranks across folds
ReadThe 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:
for models on folds. Holm-adjusted tests compare each model with the best-ranked one.
Read the diagram
PredictPredict first
In the diagram below, two models sit under one thick bar. What does the bar say?
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, is large, so wide bars are common.
View data
| model | mean rank |
|---|---|
| Gradient boosting | 1.660 |
| Random forest | 2.030 |
| Elastic net | 2.930 |
| k-nearest neighbors | 3.980 |
| Decision tree | 4.470 |
What these tests can't claim
ReadFolds 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 -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.
Check your understanding
CheckpointCheck yourself
You compare 12 models. How many pairs is that?
Show the answer
Answer: 66
. Testing each at 5% alone would almost guarantee false alarms.
Check yourself
For models on folds, with , what is the critical difference? Give two decimals.
Show the answer
Answer: 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.
Compare a shortlist
In the appOn 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.
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))))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)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