Module 14 · Intermediate · Building reliable models

Project: compare ML algorithms fairly

ML project: compare seven algorithms fairly on red wine quality data with repeated cross-validation, split-by-split comparisons and error analysis.

By theprogrammers team · · 14 min read

"Which algorithm is best?" is one of the first questions beginners ask, and it has no general answer. It has a specific answer for your data, if you compare fairly: the same folds for every model, a sensible metric, a baseline, and an honest look at whether the winner really won or just got lucky. This machine learning project compares seven algorithms from this course on one real dataset, red wine quality, and it ends with a decision you could defend to a sceptical colleague.

What you need first: cross-validation, confusion matrix, ROC and AUC, learning curves, error analysis, and the algorithms from modules 6 to 12.

Key terms

  • Fair comparison: every model trained and scored on exactly the same splits, with the same metric.
  • Repeated cross-validation: k-fold cross-validation run several times with different shuffles, giving more scores per model.
  • Paired comparison: comparing two models split by split, rather than only by their averages.
  • ROC AUC: the chance that a model scores a random positive example above a random negative one; 0.5 is guessing, 1.0 is perfect.

The goal

  • Data: 1,599 Portuguese red wines, each with 11 lab measurements (acidity, sugar, sulphates, alcohol and so on) and a quality score from 0 to 10 given by tasters.
  • Task: predict whether a wine is good, meaning a score of 7 or more. Imagine a wine shop that wants to flag promising wines before paying for a tasting.
  • Metric: ROC AUC, because only about 1 wine in 7 is good, so accuracy would flatter a model that says "not good" to everything, and the shop will choose its own threshold later.
  • Baseline: a single measurement, alcohol, used directly as the score.

Download the data: wine-quality-red.csv (94 KB), or from the original source, the UCI Machine Learning Repository. The code below loads it for you, so you only need the file to open it in a spreadsheet or work offline: load it with pd.read_csv("wine-quality-red.csv", sep=";").

Step 1: load the data and hold out a test set

import urllib.request
from pathlib import Path
import numpy as np
import pandas as pd

path = Path("winequality_red.csv")
if not path.exists():
    urllib.request.urlretrieve(
        "https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-red.csv", path)
wine = pd.read_csv(path, sep=";")

X = wine.drop(columns="quality")
y = (wine["quality"] >= 7).astype(int)
print(wine.shape)
print(f"share of good wines: {y.mean():.3f}")
print(wine["quality"].value_counts().sort_index())
(1599, 12)
share of good wines: 0.136
quality
3     10
4     53
5    681
6    638
7    199
8     18
Name: count, dtype: int64

The file separates columns with ; rather than commas, hence sep=";". y is 1 for good wines and 0 for the rest.

from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, stratify=y, random_state=0)
print(len(X_train), "training wines,", len(X_test), "test wines")
1199 training wines, 400 test wines

The test set is locked away until step 6. Every choice before then uses only the training wines.

Step 2: the baseline

from sklearn.metrics import roc_auc_score

print(f"alcohol alone, AUC on training wines: {roc_auc_score(y_train, X_train['alcohol']):.3f}")
alcohol alone, AUC on training wines: 0.838

roc_auc_score accepts any score where higher means "more likely good", so the alcohol column can be used as it is.

One column, no model, and the AUC is already 0.838: pick a random good wine and a random ordinary one, and the good one has more alcohol 84% of the time. Any model has to beat that to be worth its complexity, and one of the seven models below fails to.

Step 3: compare ML algorithms on identical folds

Seven models, each with sensible default settings. Models that depend on distances or on coefficients get a scaler in a pipeline, so scaling is learned inside each fold.

Predict first: which will win, and by how much? Will the simple logistic regression be far behind the ensembles?

from sklearn.model_selection import RepeatedStratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.naive_bayes import GaussianNB
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier, HistGradientBoostingClassifier

models = {
    "Logistic regression": make_pipeline(StandardScaler(), LogisticRegression(max_iter=2000)),
    "Naive Bayes": GaussianNB(),
    "KNN": make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=15)),
    "SVM": make_pipeline(StandardScaler(), SVC(random_state=0)),
    "Decision tree": DecisionTreeClassifier(max_depth=5, random_state=0),
    "Random forest": RandomForestClassifier(n_estimators=500, random_state=0, n_jobs=-1),
    "Gradient boosting": HistGradientBoostingClassifier(random_state=0),
}
cv = RepeatedStratifiedKFold(n_splits=5, n_repeats=3, random_state=0)
scores = {name: cross_val_score(model, X_train, y_train, cv=cv, scoring="roc_auc")
          for name, model in models.items()}
summary = pd.DataFrame({"mean AUC": {n: s.mean() for n, s in scores.items()},
                        "spread (std)": {n: s.std() for n, s in scores.items()}})
print(summary.sort_values("mean AUC", ascending=False).round(3))
                     mean AUC  spread (std)
Random forest           0.911         0.021
Gradient boosting       0.907         0.023
Logistic regression     0.891         0.018
Naive Bayes             0.868         0.023
SVM                     0.862         0.028
KNN                     0.860         0.031
Decision tree           0.788         0.058

RepeatedStratifiedKFold runs 5-fold cross-validation three times with different shuffles: 15 scores per model. Because cv has a fixed random_state, every model is scored on exactly the same 15 splits, which is what makes the comparison fair. SVC has no predict_proba by default, but AUC only needs a ranking, and cross_val_score uses its decision scores. Expect this to take a minute or so, most of it for the forest.

The two tree ensembles lead, random forest at 0.911 and gradient boosting at 0.907, with plain logistic regression not far behind at 0.891. Naive Bayes, the SVM and KNN form a middle group around 0.86 to 0.87, only a little better than alcohol alone. The single decision tree is last at 0.788, below the one-column baseline, and has by far the largest spread (0.058): a single tree depends heavily on which wines it was trained on, exactly the weakness that random forests fix.

import matplotlib.pyplot as plt

order = summary.sort_values("mean AUC").index
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.boxplot([scores[name] for name in order], vert=False)
ax.set_yticks(range(1, len(order) + 1), order)
ax.axvline(roc_auc_score(y_train, X_train["alcohol"]), color="grey", linestyle="--", label="alcohol alone")
ax.set_xlabel("ROC AUC on each of the 15 validation folds")
ax.legend(loc="upper left")
plt.show()
Horizontal box plots of 15 validation-fold AUC scores for seven models, best at the top: random forest and gradient boosting centred around 0.91, logistic regression around 0.89, then Naive Bayes, SVM and KNN around 0.86 to 0.87, and the decision tree around 0.79 with the widest spread, from about 0.70 to 0.90. A dashed grey line at about 0.84 marks alcohol alone; the decision tree's box sits mostly to its left.

Each box shows a model's 15 fold scores: the box covers the middle half, the line inside is the median, and the whiskers reach the rest.

The boxes overlap a lot. The forest's and gradient boosting's boxes cover almost the same range, and the spread within any one model, from its worst fold to its best, is bigger than most gaps between models. The ranking from the averages is less certain than the table makes it look.

Step 4: is the winner really better?

The two forests of trees are close. Because every model saw the same 15 splits, they can be compared split by split. Experiment: count how often the random forest beats gradient boosting, and the SVM, on the same split.

for rival in ["Gradient boosting", "Logistic regression", "SVM"]:
    diff = scores["Random forest"] - scores[rival]
    print(f"forest minus {rival:19}: mean {diff.mean():+.3f}, forest ahead on {(diff > 0).sum()} of 15 splits")
forest minus Gradient boosting  : mean +0.005, forest ahead on 8 of 15 splits
forest minus Logistic regression: mean +0.020, forest ahead on 14 of 15 splits
forest minus SVM                : mean +0.050, forest ahead on 15 of 15 splits

diff holds 15 differences, one per split. A model that's really better should be ahead on nearly every split, not just on average.

Against gradient boosting, the forest is ahead on only 8 of the 15 splits: a coin toss. Their 0.005 difference in the average is noise, and the honest summary is "tied". Against logistic regression, the forest is ahead on 14 of 15 splits, and against the SVM on all 15. Those gaps are real.

Step 5: choose

The evidence says:

  • The tree ensembles beat everything else, consistently.
  • The random forest and gradient boosting are tied.
  • Logistic regression is clearly, but not hugely, behind (0.020 AUC).

Between the tied two, the random forest gets the nod here: it worked well with no tuning at all and is hard to break with bad settings. Gradient boosting would be an equally defensible choice, and was much quicker to train in this run. If the shop needed to explain every decision in plain words, logistic regression's small loss might be a price worth paying. All three go to the final test, to check that nothing has gone badly wrong; the test isn't used to change the choice.

Step 6: the final test

finalists = ["Random forest", "Gradient boosting", "Logistic regression"]
test_scores = {}
for name in finalists:
    model = models[name].fit(X_train, y_train)
    test_scores[name] = model.predict_proba(X_test)[:, 1]
    print(f"{name:20} test AUC {roc_auc_score(y_test, test_scores[name]):.3f}")
print(f"{'alcohol alone':20} test AUC {roc_auc_score(y_test, X_test['alcohol']):.3f}")
Random forest        test AUC 0.905
Gradient boosting    test AUC 0.901
Logistic regression  test AUC 0.830
alcohol alone        test AUC 0.778

The finalists are scored once each on the 400 test wines, which were never used for any decision.

The forest scores 0.905 and gradient boosting 0.901, close to their cross-validated 0.911 and 0.907, so the choice holds up on new wines. Logistic regression drops much further, from 0.891 to 0.830. With only 54 good wines among the 400 test wines, a single test score swings a lot, so this drop may be partly bad luck. But it's in the same direction as the 14-out-of-15 result in step 4, and together they confirm that the tree ensembles are the better choice for this data. All three beat alcohol alone (0.778 on the test wines).

Step 7: error analysis

AUC is a single number. Which wines does the forest get wrong? Take the shop's point of view: the forest flags its 40 highest-scoring test wines for tasting.

proba = test_scores["Random forest"]
flagged = np.argsort(proba)[::-1][:40]
review = pd.DataFrame({"quality": wine.loc[X_test.index, "quality"].to_numpy(),
                       "flagged": np.isin(np.arange(len(X_test)), flagged)})
print(f"good wines among the 40 flagged: {y_test.to_numpy()[flagged].sum()} (good wines in the test set: {y_test.sum()})")
print(pd.crosstab(review["quality"], review["flagged"], margins=True))
good wines among the 40 flagged: 29 (good wines in the test set: 54)
flagged  False  True  All
quality                  
3            3     0    3
4           12     1   13
5          184     0  184
6          136    10  146
7           22    26   48
8            3     3    6
All        360    40  400

np.argsort(proba)[::-1][:40] gives the positions of the 40 highest probabilities. wine.loc[X_test.index, "quality"] looks up the original taster's score for each test wine, so mistakes can be seen on the 0 to 10 scale rather than just good or not good.

Of the 40 wines the forest flags, 29 are good: about 73%, against 13.5% if the shop picked 40 at random. Those 29 are just over half of the 54 good wines in the test set. The table shows what the mistakes look like. Of the 11 flagged wines that aren't good, 10 scored 6, just below the line, so they're near misses, and only one is a poor wine (a 4). The good wines it misses are mostly 7s (22 of them); half of the six excellent 8s are flagged. For a shop deciding which wines to taste, that's a useful shortlist: almost nothing on it is bad, and the tasting itself would catch the 6s.

Limitations

  • One dataset. The ranking here is about these 1,599 wines. On a different dataset, the order of models could change completely; that's the point of comparing on your own data.
  • Default settings. Each model was compared with sensible defaults. Tuning, as in hyperparameter tuning with Optuna, could reorder the close ones, but should be done for every contender, not just the favourite.
  • Subjective labels. Quality is the median of at least three tasters' scores. The line between a 6 and a 7 is partly taste, which caps how well any model can do.
  • One region, one period. All wines are variants of one Portuguese wine style, so the model says little about other wines.

Take it further

  1. Predict the score itself. Treat quality as a number and compare regression models by mean absolute error. Hint: reuse the same cv, with scoring="neg_mean_absolute_error".
  2. Add the white wines. The UCI page also has 4,898 white wines. Does a model trained on red wines work on white ones? Hint: train on one, test on the other, then try training on both with a "colour" column.
  3. Tune the top three fairly. Give the random forest, gradient boosting and logistic regression the same tuning budget, then repeat step 4. Hint: nest the tuning inside the cross-validation, so tuning never sees the validation fold.
  4. Explain the winner. Use SHAP on the forest. Do alcohol and sulphates lead, and do their effects rise steadily or level off?

Practice

  1. Why must all models be scored on the same folds?
Show the answer

Different folds contain different wines, and some splits are harder than others. If model A happened to get easier folds, its higher average could come from luck rather than skill. With identical folds, every difference between two models comes from the models themselves, and they can be compared split by split.

  1. Without running code: model A averages 0.910 and model B 0.906 over 15 splits, and A is ahead on 8 of them. What would you conclude?
Show the answer

That there's no evidence either is better: 8 of 15 is what a coin toss gives. Pick between them on other grounds, such as speed, simplicity or ease of explanation.

  1. How many good wines would a model that flags 40 random test wines find, on average?
Show the answer

About 40 × 0.136 ≈ 5.4, because 13.6% of the wines are good. Compare that with the number the forest found in step 7.

  1. Score the logistic regression on the test set by average precision as well as AUC. Why might a shop prefer average precision?
Show the answer
from sklearn.metrics import average_precision_score
for name in finalists:
    print(f"{name:20} average precision {average_precision_score(y_test, test_scores[name]):.3f}")
Random forest        average precision 0.696
Gradient boosting    average precision 0.634
Logistic regression  average precision 0.411

The forest's average precision is 0.696, gradient boosting's 0.634 and logistic regression's 0.411. Average precision summarises precision across all the thresholds the shop might use, and it focuses on the good wines, the rare class the shop cares about. AUC also gives credit for ranking ordinary wines correctly against each other, which the shop doesn't need. On this metric the forest's lead over gradient boosting looks bigger, but it rests on the same 54 good wines, so it's far from certain.

Interview questions

How do you compare machine learning models fairly?

Use the same cross-validation splits for every model, choose a metric that suits the problem before looking at results, include a simple baseline, and keep the test set out of all decisions. Then check close results split by split, not just by the average.

Two models' cross-validated scores differ by 0.005. Which do you pick?

First check whether the difference is real: if one model wins on only about half of the splits, it's noise. When models tie, pick on other grounds, such as speed, simplicity, explainability or cost to run.

Why might the test score disagree with the cross-validated ranking?

A test set is one sample. With few positive cases, as here with 54 good wines, the test score has a wide margin of error and can reorder close models by chance. The cross-validated ranking, over many splits, is usually the better guide.

Key takeaways

  • There's no best algorithm in general; there's a best choice for your data, found by a fair comparison.
  • Fair means identical folds for every model, a metric that suits the problem, and a simple baseline.
  • Compare close models split by split: being ahead on average isn't enough if it's only ahead on half the splits.
  • When models tie, choose on speed, simplicity and explainability, then confirm once on the test set.
  • Error analysis turns a score into insight: which wines are missed, and whether the mistakes are near misses.

Frequently asked questions

Should I use a statistical test to compare models?

It can help, but scores from repeated cross-validation aren't independent (the folds share training rows), so standard tests overstate certainty. Counting wins on identical splits and looking at the spread, as here, is a simple and honest guide. If you need a formal test, look up the corrected repeated k-fold t-test.

Why not just try every model in scikit-learn?

The more models you try, the more likely one wins by luck. A short list of different kinds of model, chosen with how to choose a machine learning algorithm, covers the important options with much less risk.

Is AutoML the same thing?

AutoML tools automate this search, along with tuning and feature processing. They're useful, but you still need to understand fair comparison to judge their results, and to notice when a "winner" isn't really better.

What to learn next

  1. Start grouping data without labels in k-means clustering explained, the next module.
  2. Revisit how to narrow the list of candidates in how to choose a machine learning algorithm.
  3. Revisit why one test score can mislead in cross-validation.