This is Module 1 of the Machine Learning Engineer path. Everything later in the path, from pipelines to monitoring, assumes you can tell whether a model is actually good. This module shows three common ways that judgement goes wrong, with experiments you can run in a few seconds.

You need: Python and scikit-learn (pip install scikit-learn). All data is generated by the scripts with fixed seeds, so your numbers should match the ones shown closely; small differences between library versions are normal.

1. Leakage: when the test set helps train the model

Data leakage means information that wouldn’t be available at prediction time is used while building the model. The scores look better than reality, sometimes dramatically.

The cleanest demonstration uses data with nothing to learn: 200 rows, 10,000 random features and random labels. Any honest method should score about 50%. Save as leak_selection.py:

# Leakage through feature selection: on pure noise, the honest accuracy is about 50%.
import numpy as np
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline

rng = np.random.RandomState(0)
X = rng.normal(size=(200, 10_000))          # 10,000 random features
y = rng.randint(0, 2, size=200)             # random labels: nothing to learn

# Wrong: choose the 20 "best" features using ALL rows, then cross-validate.
X_selected = SelectKBest(f_classif, k=20).fit_transform(X, y)
wrong = cross_val_score(LogisticRegression(max_iter=1000), X_selected, y, cv=5).mean()

# Right: selection happens inside each training fold, as part of the pipeline.
pipe = make_pipeline(SelectKBest(f_classif, k=20), LogisticRegression(max_iter=1000))
right = cross_val_score(pipe, X, y, cv=5).mean()

print(f"selection before CV (leaky): {wrong:.2f}")
print(f"selection inside CV (honest): {right:.2f}")
selection before CV (leaky): 0.84
selection inside CV (honest): 0.48

Picking the 20 features that best match the labels using every row, test rows included, produces 84% accuracy on pure noise. The features were chosen because they happened to correlate with those exact labels, so the test folds were never really unseen. Put the selection inside a pipeline and cross-validation refits it on each training fold: the score drops to 48%, which is the truth.

The rule generalises: every step that learns from data (scaling, imputation, feature selection, encoding categories) belongs inside the pipeline, so it only ever sees training data.

2. Splitting by time when the future is what you predict

A random train/test split assumes rows are independent. When data is ordered in time, a random split lets the model train on days that come after the days it’s tested on. Save as leak_time.py:

# Random splits on time-ordered data: the model sees the future during training.
import numpy as np
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_absolute_error
from sklearn.model_selection import train_test_split

rng = np.random.RandomState(0)
days = np.arange(730)                                        # two years of daily data
demand = 100 + 0.1 * days + 15 * np.sin(2 * np.pi * days / 7) + rng.normal(0, 5, size=days.size)
X = np.column_stack([days, days % 7])                       # features: day number, weekday
y = demand

# Random split: test days are scattered between training days.
Xa, Xb, ya, yb = train_test_split(X, y, test_size=0.2, random_state=0)
rand_mae = mean_absolute_error(yb, RandomForestRegressor(random_state=0).fit(Xa, ya).predict(Xb))

# Time split: train on the first 80% of days, test on the last 20%, as in real use.
cut = int(len(days) * 0.8)
model = RandomForestRegressor(random_state=0).fit(X[:cut], y[:cut])
time_mae = mean_absolute_error(y[cut:], model.predict(X[cut:]))

print(f"random split MAE: {rand_mae:.1f}")
print(f"time split MAE:   {time_mae:.1f}")
random split MAE: 4.5
time split MAE:   10.0

The random split reports an error less than half the size of the time split. The reason is instructive: random forests can’t predict beyond the range of values they were trained on. With a random split, every test day sits between training days, so that weakness never shows. With a time split, the model faces later days, as it would in production, the upward trend continues past anything it saw, and the error doubles.

For time-ordered data, test on the most recent period, or use scikit-learn’s TimeSeriesSplit for cross-validation.

3. Every score needs a baseline

An error of 3.9 means nothing on its own. Compare it with what a trivial method achieves on the same split. Save as baseline.py:

# A baseline tells you whether the model is worth having.
import numpy as np
from sklearn.dummy import DummyRegressor
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error

rng = np.random.RandomState(0)
days = np.arange(730)
demand = 100 + 0.1 * days + 15 * np.sin(2 * np.pi * days / 7) + rng.normal(0, 5, size=days.size)
cut = int(len(days) * 0.8)
y_train, y_test = demand[:cut], demand[cut:]

naive = mean_absolute_error(y_test, demand[cut - 7:-7])        # "same as one week earlier"
mean = mean_absolute_error(y_test, DummyRegressor().fit(np.zeros((cut, 1)), y_train).predict(np.zeros((len(y_test), 1))))
X = np.column_stack([days, np.sin(2 * np.pi * days / 7), np.cos(2 * np.pi * days / 7)])
linear = mean_absolute_error(y_test, LinearRegression().fit(X[:cut], y_train).predict(X[cut:]))

print(f"predict the training mean:   MAE {mean:.1f}")
print(f"same day last week (naive):  MAE {naive:.1f}")
print(f"linear model (trend + week): MAE {linear:.1f}")
predict the training mean:   MAE 35.9
same day last week (naive):  MAE 5.5
linear model (trend + week): MAE 3.9

Predicting the average is far worse than either alternative, but “same day last week” is already close to the model. The linear model wins, by 1.6 units of error, not by an order of magnitude. That’s the number to weigh against the cost of building, deploying and monitoring it.

A checklist before you trust a score

  • Does every step that learns from data sit inside the pipeline, fitted on training folds only?
  • If you’re predicting the future, is the test set later in time than the training set?
  • Is the score reported next to at least one simple baseline?
  • Could any feature contain information that only exists after the outcome is known?

Project

Take a model you’ve built before and audit it with the checklist. Fix one problem you find, re-run the evaluation, and write two sentences on how the score changed and why. A drop in the score is a good result: it means the new number can be trusted.

Next: Module 2, features and pipelines.

Prepared with AI assistance and reviewed by an editor before publication. Editorial & AI policy.