ML fundamentals18 / 22

Lesson 18 · In practice

Features, leakage and the workflow

The problem

Every lesson so far began with a tidy table: distance, traffic, rain, hour, items, and whether the delivery was late. Nobody hands you that table. The shop's till and app record something messier, the orders log:

ordertimestampwhere (km east, north)drivertraffic
10012026-03-17 18:121.83, −0.52Dara0
10032026-04-27 22:45−4.44, −2.29Asha0
10162026-03-08 19:47−1.01, −3.87Chen(blank)

The log also has the street address, the payment type, the number of items and rain. And it records what happened: whether a refund was issued, how many minutes the delivery took, and whether it was late. There are 300 orders, and they're the same orders as the deliveries table. The numbers are made up for this book.

A model can only do arithmetic on numbers. It can't read "2026-03-08 19:47", "Chen" or a blank. And some of these columns must never reach it, because the shop won't know them when it has to make a prediction.

This lesson turns the log into features, catches the columns that cheat, and puts every step into one object that can't cheat by accident.

From raw fields to features

Start with order 1016 and deal with one kind of field at a time.

Order 1016, raw
fieldvaluebecomes
order_id1016…
timestamp2026-03-08 19:47…
address73 Church Road…
east_km, north_km−1.005, −3.872…
driver_nameChen…
paymentcard…
items3…
rain0…
traffic(blank)…
refund_issued1…
minutes33.6…
late1…
Step 0 of 6

One raw order, as the till records it. A model can only do arithmetic, so most of these fields are no use yet.

→ new feature · ✓ kept · ✗ dropped · ◎ label

One raw order becomes a row of features. Each step handles one kind of field.

Things to notice:

  • Each new feature is a question the model can use: "Is it rush hour?" "How far away is it?" "Was it Chen driving?"
  • The timestamp alone becomes three features. None of them is the raw string.
  • Some fields are dropped on purpose. An order number is a label for the row, not a fact about the delivery.

Building useful input features from raw data is called feature engineering. A good feature makes the pattern easy for the model to see.

Predict first

Deliveries sent between 18:00 and 19:59 take about 5 minutes longer. For a logistic regression, which feature helps more: the hour as a number (17 to 22), or a rush-hour flag (1 for 18:00–19:59, else 0)?

One-hot encoding

The driver is a name. You could number the drivers, Asha = 0 to Eli = 4. But then the model would treat the numbers as amounts, as if Eli were 4 times Ben. The order would mean something it doesn't.

Instead, give each driver their own column:

driverAshaBenChenDaraEli
Chen00100
Asha10000

Each row has a single 1, in its own driver's column. This is one-hot encoding. A linear model then learns one weight per driver: how much that driver adds to the score. Payment type gets the same treatment: app, card, cash.

One-hot columns grow with the number of values. Five drivers is fine. Ten thousand menu items, or a customer ID, would add ten thousand columns, most of them almost always 0. For many values, neural networks learn a short vector per value instead: an embedding.

Missing values

Traffic wasn't recorded for 16 of the 300 orders. Most models can't use a blank. Missing values have three common fixes:

  • Drop the rows. Simple, but you lose 16 orders, and if blanks happen more on busy nights, the rows left are no longer typical.
  • Fill them in with a typical value, such as the median of the column. Filling blanks is called imputation. The median traffic level is 2.
  • Fill and flag. Fill them in, and add a 0/1 column saying "this was blank". Then the model can learn whether a missing reading means something.

The fill-in value is learned from data, so it's learned from the training rows only. More on why below.

DigressionDates, text and IDs: common feature recipesWhat to do with a timestamp, a sentence or a customer number. · 2 min

Dates and times. Split them into parts a model can use: hour, day of the week, month, "is it a holiday". For a cycle like the hour, a trick is to use two numbers, the sine and cosine of the angle around the clock. Then 23:00 and 00:00 end up close together instead of 23 apart.

Places. Coordinates are usually more useful than addresses. Turn them into distances to things that matter: the shop, the nearest busy road.

Text. Count words, as the bag of words in naive Bayes does, or use a language model's embedding.

IDs. An order number is only a counter: drop it. A customer ID can carry real information ("this customer lives up a hill"). But one-hot encoding thousands of customers is unwieldy, and the model can memorise them. Use features about the customer instead, such as their usual distance, computed from past orders only.

Ratios and differences. Sometimes the useful number is one column divided by another: items per minute of cooking time, or price per item.

Data leakage

Now try the refund column. Refunds are issued when an order goes wrong, so it should help predict late orders. It does: far too much.

Worked example

A refund column that knows too much

  1. The log has 148 late orders and 152 on time. A refund was issued on 105 orders: 101 late ones and 4 on-time ones.

Information that the model won't have when it makes real predictions, but that sneaks into training, is called data leakage. The validation score looks great, and the model fails after launch.

Known when the order is placed
Known only after the delivery

5-fold cross-validated accuracy: 88.0% (folds: 93%, 93%, 83%, 85%, 85%)

Choose which columns the model may use. The score is 5-fold cross-validated accuracy of the same pipeline: fill blanks, scale, one-hot encode, logistic regression.

Things to notice:

  • The honest columns score 88.0%. Adding "refund issued" lifts it to 93.7%.
  • The data was made by a known formula plus random noise. Even that formula, the best any model could do, scores about 90% on these orders. The leaky model beats it. That's impossible without cheating.
  • Press "Score each column alone". The refund column stands out far above every honest feature.
  • Drivers, payment and weekday score about 50% or less alone: in this data, they don't affect lateness.

So, three ways to spot a leak:

  1. The score is too good: better than seems possible, or a big jump from one new column.
  2. One column does too much on its own.
  3. Ask when each column is filled in. Draw a timeline from the moment of prediction. Anything filled in after it must go. That's the test that settles it.

Leaks are rarely labelled. Other columns can do the same thing. Watch for a "status" field updated after the fact, or a "notes" column written by the driver. A customer's lifetime total that includes future orders leaks too.

DigressionTarget encoding, and how it leaks if done carelesslyReplacing each category with its average label is useful, and a classic way to cheat. · 2 min

Instead of one-hot encoding the drivers, you could replace each driver's name with their late rate. Chen's orders were late 49% of the time, so "Chen" becomes 0.49. This is target encoding. It turns thousands of categories into one column.

But the late rate is computed from the labels. If you compute it on all the rows, each row's own label helped set its feature. A driver with a single order gets the rate 0 or 1: exactly that order's answer. The model learns to trust the column, and validation can't catch it, because the validation rows' labels went into it too.

The fix is the same as for everything else in this lesson: compute the rates on the training rows only. Within the training rows, compute each row's rate without that row, for example with cross-validation folds. scikit-learn's TargetEncoder does this for you.

Fit preparation on training rows only

Leakage doesn't need a suspicious column. It can come from the preparation steps.

Scaling, filling blanks and one-hot encoding all learn numbers from data: a mean, a median, a list of categories. Feature scaling showed the rule: fit them on the training rows, then apply them to everything else.

Predict first

You scale the features using the mean and standard deviation of the whole dataset, then split it into training and validation sets. Is the validation score honest, too high, or too low?

0123456789100distance (km)mean 3.00

● training rows · ◆ validation row · shaded band: mean ± 1 standard deviation

Mean 3.00 km, standard deviation 1.41 km, from the 5 training rows.

The 8 km validation delivery becomes 3.54 standard deviations above the mean.

This is how a new 8 km order will be scaled after launch: with numbers from data the model was trained on.

Five training distances and one validation distance. Scale with numbers from the training rows only, or from all rows.

Things to notice:

  • Fitted on the training rows (1, 2, 3, 4 and 5 km), the mean is 3 and the standard deviation 1.41. The 8 km delivery is 3.54 standard deviations out: far from typical.
  • Fitted on all six, the 8 km delivery pulls the mean to 3.83 and the spread to 2.27. Now it's only 1.84 standard deviations out. It helped set the scale, so it looks more ordinary.
  • After launch, a new 8 km order will be scaled with the training numbers. Validation should be scaled the same way.

The scaling leak is small. The same mistake with choosing columns is not. Take 500 columns of pure random numbers and the real late labels. Keep the 10 columns that best match "late", then cross-validate a model on them.

The columns are random numbers, so an honest score beats guessing only by luck. The leaky score beats it by a wide margin.

500 columns of noise. Choose the 10 that best match the labels using all rows (leak), or inside each training fold (honest), then cross-validate.

Things to notice:

  • Choosing on all rows scores well above 50%, usually 62–70%, on columns that contain nothing.
  • Among 500 random columns, a few match the labels well by chance, on these 300 rows. The validation rows helped pick them, so they match the validation rows too.
  • Chosen inside each fold, using only that fold's training rows, the columns match nothing in the validation rows. The score falls back to about 50%, give or take luck.

The rule: every step that learns from data is fitted on the training rows only. That includes scaling, filling blanks, the category list, choosing columns, and target encoding.

Pipelines

Doing that by hand inside every fold of cross-validation is fiddly, and easy to get wrong. So bundle the steps.

A pipeline is a fixed sequence of preparation steps followed by a model, treated as one model. Fitting the pipeline fits each step in turn on the training rows, passing the transformed rows along. Predicting runs new rows through the same steps with the numbers already learned.

In: the 240 training orders (folds 2–5), with their labels
ColumnTransformer: each kind of column gets its own steps
numbers: distance, traffic, rain, rush hour, items
Fill blanks
SimpleImputer(strategy="median")

Learns: each column's median (traffic: 2)

Scale
StandardScaler()

Learns: each column's mean and standard deviation (distance: 3.09 ± 1.63 km)

categories: driver, payment
One-hot encode
OneHotEncoder(handle_unknown="ignore")

Learns: the values seen: 5 drivers, 3 payment types

13 feature columns
Model
LogisticRegression()

Learns: 13 weights and an intercept (distance's weight: 2.16)

Out: a fitted pipeline

Outlined boxes learn numbers from the rows passing through. Inside cross-validation, the whole pipeline is fitted again for each fold, on that fold’s training rows only.

The orders pipeline. Switch between fitting and predicting to see which steps learn numbers and which only reuse them.

Things to notice:

  • Numbers and categories need different steps, so they go down separate lanes and meet again as 13 columns.
  • When fitting, every box learns something. When predicting, every box only applies what it learned. No validation row or new order can change a median, a mean or a weight.
  • Cross-validation can fit the whole pipeline, again and again, on each fold's training rows. That's what makes the score honest.

In scikit-learn

scikit-learn has two tools for this, Pipeline and ColumnTransformer. A Pipeline chains steps; a ColumnTransformer sends different columns through different steps. Both are estimators, so they have fit and predict like any model.

First, the new columns, with pandas:

Features from the timestamp and the coordinates
def add_features(raw: pd.DataFrame) -> pd.DataFrame:
    """New columns a model can use, each computed from one order alone."""
    out = raw.copy()
    when = pd.to_datetime(out["timestamp"])
    out["hour"] = when.dt.hour  # 17-22
    out["weekday"] = when.dt.day_name()  # a category: "Monday", ...
    out["rush_hour"] = when.dt.hour.between(18, 19).astype(int)  # 18:00-19:59, the busy spell
    out["distance_km"] = np.hypot(out["east_km"], out["north_km"])  # straight-line km from the shop
    return out


orders = add_features(orders)
print(orders.loc[15, ["hour", "weekday", "rush_hour", "distance_km"]].to_dict())
{'hour': 19, 'weekday': 'Sunday', 'rush_hour': 1, 'distance_km': 4.00030111366632}

Then the pipeline, scored with cross_val_score:

ColumnTransformer + Pipeline + cross_val_score
NUMERIC = ["distance_km", "traffic", "rain", "rush_hour", "items"]
CATEGORIES = ["driver_name", "payment"]


def make_model(numeric: list[str], categories: list[str]) -> Pipeline:
    """Fill blanks and scale the numbers, one-hot encode the categories, then logistic regression."""
    prepare = ColumnTransformer([
        ("numbers", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), numeric),
        ("categories", OneHotEncoder(handle_unknown="ignore", sparse_output=False), categories),
    ])
    return Pipeline([("prepare", prepare), ("model", LogisticRegression())])


folds = KFold(n_splits=5)  # 5 blocks of 60 orders, in log order (the log is already in random order)
y = orders["late"]
honest = cross_val_score(make_model(NUMERIC, CATEGORIES), orders, y, cv=folds)
print(f"honest features:  {honest.mean():.1%}")
print(f"always 'on time': {1 - y.mean():.1%}")
honest features:  88.0%
always 'on time': 50.7%

What to notice:

  • make_pipeline(SimpleImputer(strategy="median"), StandardScaler()) handles the numbers: fill the traffic blanks, then scale.
  • OneHotEncoder(handle_unknown="ignore", sparse_output=False) handles the categories. handle_unknown="ignore" means a value it never saw in training (a new driver) gets all zeros instead of an error. sparse_output=False returns an ordinary array; the default is a sparse matrix, which saves memory when most entries are 0.
  • cross_val_score gets the whole pipeline and the raw table. For each of the 5 folds, it fits everything on the other 4 folds. No step ever sees the held-out fold during fitting.
  • KFold(n_splits=5) without shuffling keeps the folds in log order. The log is already in random order, and this way the figure's folds match exactly.
  • Always compare with a baseline: always guessing "on time" scores 50.7%.

To see what the model receives, ask the preparation step for pandas output:

The prepared table, with column names
prepare = make_model(NUMERIC, CATEGORIES).named_steps["prepare"]
prepare.set_output(transform="pandas")  # keep column names, so you can see what the model gets
table = prepare.fit_transform(orders)
print(table.shape)  # (300, 13): 5 numbers + 5 drivers + 3 payment types
print(table.iloc[15].round(2).to_string())  # order 1016, ready for the model
(300, 13)
numbers__distance_km            0.53
numbers__traffic                0.38
numbers__rain                  -0.68
numbers__rush_hour              1.31
numbers__items                  0.00
categories__driver_name_Asha    0.00
categories__driver_name_Ben     0.00
categories__driver_name_Chen    1.00
categories__driver_name_Dara    0.00
categories__driver_name_Eli     0.00
categories__payment_app         0.00
categories__payment_card        1.00
categories__payment_cash        0.00
  • set_output(transform="pandas") makes each step return a DataFrame with named columns. It needs dense output, which is why the encoder has sparse_output=False.
  • This is order 1016. Its blank traffic became the median, 2, which scales to 0.38. Its one-hot slots say Chen and card.

The leak, and how to spot it:

Adding the refund column
leaky = cross_val_score(make_model(NUMERIC + ["refund_issued"], CATEGORIES), orders, y, cv=folds)
print(f"+ refund_issued:  {leaky.mean():.1%}")  # refunds are issued after late deliveries
+ refund_issued:  93.7%
Each column alone
for column in ["distance_km", "traffic", "rush_hour", "refund_issued"]:
    alone = cross_val_score(make_model([column], []), orders, y, cv=folds).mean()
    print(f"{column:14} alone: {alone:.1%}")
print(pd.crosstab(orders["refund_issued"], orders["late"]))
distance_km    alone: 71.3%
traffic        alone: 77.7%
rush_hour      alone: 60.7%
refund_issued  alone: 83.0%
late             0    1
refund_issued
0              148   47
1                4  101

The table at the bottom is the worked example: 101 of the 105 refunds went to late orders.

Finally, a driver the model has never seen:

An unknown category
model = make_model(NUMERIC, CATEGORIES).fit(orders, y)
new_order = orders.iloc[[15]].assign(driver_name="Fay", traffic=2)  # a driver the model has never seen
print(model.predict_proba(new_order)[:, 1].round(2))  # Fay's one-hot slots are all 0; no error
[0.94]

Fay gets zeros in all five driver slots, so the model uses only her order's other features. Without handle_unknown="ignore", predict_proba would raise an error.

The workflow

Features, leaks and pipelines fit into a bigger routine. Here it is from question to launch.

  1. What exactly is predicted, and at what moment? For the shop: "late or not", when the order is placed.

  2. Before looking closely at the data. Split the way the model will be used: random rows, or past against future.

  3. Blanks, odd values, the share of each label, and when each column gets filled in.

  4. Dates to hours, places to distances, categories to one-hot columns, blanks filled, numbers scaled: all inside one pipeline.

  5. For example, always predict the most common answer. Here that’s 50.7%.

  6. Fit each pipeline on the training folds and score it on the held-out fold. Choose settings the same way.

  7. One final, honest number. If it’s much worse than cross-validation, find out why before shipping.

  8. The fitted pipeline, not only the model, so new orders get the same preparation. Then watch its inputs and accuracy over time.

0 of 8 steps done

Tick a step when it’s done. Open a step’s title to see what goes wrong if you skip it.

The workflow as a checklist. Tick each step; open one to see what goes wrong if you skip it.

Things to notice:

  • The test set is set aside in step 2, before any exploring. The train, validation and test split only works if the test rows stay unseen.
  • How you split should match how the model will be used. Predicting next month from this month calls for a time-based split.
  • After launch, the world changes: a new menu, a new branch, winter. That's distribution shift. The evaluation lesson covers both.
  • The real test of whether the model helps the shop is an experiment with real customers: an A/B test, the next lesson.

Putting it together

The late-delivery model from the raw log, start to finish:

  1. Question: late or not, predicted when the order is placed.
  2. Features: distance from the coordinates; hour, weekday and rush hour from the timestamp; one-hot driver and payment; traffic, with blanks filled by the training median.
  3. Leak check: "refund issued" and "minutes" are filled in after the delivery, so they go. The refund column alone scored 83% and lifted the model above what's possible: 93.7% against about 90%.
  4. Pipeline: fill and scale the numbers, one-hot the categories, logistic regression, all in one Pipeline.
  5. Cross-validation: 88.0%, against 50.7% for always guessing "on time".
  6. Test set and launch: one final check on held-back orders, then ship the fitted pipeline, not only the model.

Common misconceptions

"A higher validation score is always better." Not when it's higher than seems possible. A jump from one new column, or a score above what the data allows, is a reason to look for a leak.

"Leakage only means test rows in the training set." It's any information the model won't have at prediction time. That includes a column filled in later, and preparation fitted on all the rows.

"Scaling doesn't look at labels, so fitting it on all rows is fine." It still lets validation rows shape the features. The effect is small for scaling, but the same habit with column selection or target encoding gives scores far too high.

"Number the categories 0, 1, 2, … and the model will work it out." A linear model reads those numbers as amounts in order. One-hot encoding avoids inventing an order.

"Fill blanks with the column's mean from the whole dataset." Learn the fill-in value from the training rows only, inside the pipeline. And consider a "was missing" flag.

"The model is what you ship." Ship the whole fitted pipeline. New orders need the same fill-in values, scaling and category lists as the training rows.

Recap

  • Feature engineering turns raw fields into numbers a model can use: hours and rush-hour flags from timestamps, distances from coordinates.
  • One-hot encoding gives each category value its own 0/1 column, so no false order is implied.
  • Missing values are dropped, filled (imputation) or filled and flagged, with fill-in values learned from training rows.
  • Data leakage is information the model won't have when it's used. Spot it by a score that's too good, a column that does too much alone, and by asking when each column is filled in.
  • Every step that learns from data is fitted on the training rows only. A pipeline bundles those steps with the model, so cross-validation refits them inside each fold.
  • The workflow: question, test set aside, explore, features in a pipeline, baseline, cross-validate, test once, ship the pipeline and watch it.
  • Names in this lesson: pandas' to_datetime and .dt; scikit-learn's Pipeline, make_pipeline, ColumnTransformer, SimpleImputer, StandardScaler, OneHotEncoder (handle_unknown, sparse_output), set_output, KFold, cross_val_score, SelectKBest and TargetEncoder.