Learning path: Data and Features in Production · Step 3 of 8
Feature Engineering Patterns, Each One Tested: Date Parts, Differences, Windows and Target Encoding
Four feature patterns on Rain in Australia, each scored against one baseline on a time split: month, pressure change, a 7-day rain window and a location rain rate. Small honest gains, and two leaks that beat them all.
What you will learn
- Add date parts, differences and ratios as new columns and score each one on a time split
- Build a per-location window aggregate that stops at yesterday
- Target-encode a category by hand and with TargetEncoder, without reading the test answers
- Recognise a leak when a new column scores better than everything honest
Before you start
- Time Splits and Group Splits
- Encoding Categorical Data
- ROC Curve and AUC
Think about a doctor's chart. Your resting heart rate today is one reading, and on its own it says very little. The change since last month says a lot. Our four patterns work the same way:
- Date parts: when in the year is it?
- Differences and ratios: how much did something change?
- Window aggregates: what happened recently?
- Target encoding: what's usual for this place?
And here's the part people skip. A good doctor then asks: does this new number change the decision? For us, that check is the score. A pattern is only a good guess until the score moves. So every new column in this lesson gets scored against the same baseline.
One baseline, one time split
The test rig doesn't change for the rest of the lesson. It trains on the past and tests on what came after, with the cutoff 80% of the way through the dates (as in Time Splits and Group Splits).
import numpy as np
import pandas as pd
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import StratifiedKFold
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler, TargetEncoder
df = pd.read_csv("weatherAUS.csv", parse_dates=["Date"])
df = df.sort_values(["Location", "Date"]).reset_index(drop=True)
df["y"] = (df["RainTomorrow"] == "Yes").astype(int)
cut = df["Date"].quantile(0.8)
has = df["Date"] < cut # the training rows
print(df.shape, cut.date(), has.sum(), (~has).sum())
(142193, 25) 2015-11-10 113748 28445
nums = df.select_dtypes("number").columns
# RISK_MM is tomorrow's rain, so it stays out
BASE = list(nums.drop(["y", "RISK_MM"]))
def score(new=(), at=cut, model=None):
tr, te = df[df["Date"] < at], df[df["Date"] >= at]
cols = BASE + list(new)
m = model or HistGradientBoostingClassifier(
early_stopping=False, random_state=42)
m.fit(tr[cols], tr["y"])
p = m.predict_proba(te[cols])[:, 1]
return round(roc_auc_score(te["y"], p), 4)
base = score()
def show(name, s):
print(f"{name:14} {s:.4f} {s - base:+.4f}")
print(len(BASE), "columns")
show("baseline", base)
16 columns
baseline 0.8705 +0.0000
16 numeric weather columns, boosted trees (HistGradientBoostingClassifier), and an AUC of 0.8705. Early stopping is off, so nothing here is random. Every new column now has to beat 0.8705.
Pattern 1: take the month out of the date
df["Month"] = df["Date"].dt.month
wet = df[has].groupby("Month")["y"].mean()
print(wet.round(2).tolist())
show("Month", score(["Month"]))
[0.18, 0.22, 0.21, 0.23, 0.23, 0.26, 0.26, 0.25, 0.21, 0.19, 0.23, 0.22]
Month 0.8719 +0.0014
The rain rate (checked on training rows only) goes from 0.18 in January to 0.26 in June and July, so the season matters. The gain is small, +0.0014, but as you'll see, it holds up.
Pattern 2: make the change its own column
df["PressureChange"] = df["Pressure3pm"] - df["Pressure9am"]
df["PressureRatio"] = df["Pressure3pm"] / df["Pressure9am"]
cols = ["Pressure9am", "Pressure3pm", "PressureChange"]
print(df[cols].head(3).round(1).to_string())
show("change", score(["PressureChange"]))
show("ratio", score(["PressureRatio"]))
Pressure9am Pressure3pm PressureChange
0 1017.4 1017.7 0.3
1 1022.4 1022.6 0.2
2 1027.8 1026.5 -1.3
change 0.8730 +0.0025
ratio 0.8735 +0.0030
The model already had both pressure columns. So why does it gain anything? Because a tree cuts one column at a time. To follow a difference between two columns it needs many small cuts, like a staircase. Give it the change as one column, and one cut can do the job.
Now try the same column on a model that can already subtract, a plain logistic regression:
linear = make_pipeline(SimpleImputer(strategy="median"),
StandardScaler(),
LogisticRegression(max_iter=1000))
a = score(model=linear)
b = score(["PressureChange"], model=linear)
print(a, b, round(b - a, 4))
0.851 0.8513 0.0003
Almost nothing. The same column helps one model and not another, and that's why we test.
Pattern 3: rain over the last 7 days, stopping at yesterday
by_place = df.groupby("Location")["Rainfall"]
df["Rain7"] = by_place.transform(
lambda s: s.shift(1).rolling(7, min_periods=1).sum())
syd = df[df["Location"] == "Sydney"]
print(syd[["Date", "Rainfall", "Rain7"]].iloc[46:56].to_string())
Date Rainfall Rain7
108073 2008-03-18 0.0 0.0
108074 2008-03-19 0.0 0.0
108075 2008-03-20 0.0 0.0
108076 2008-03-21 1.0 0.0
108077 2008-03-22 2.2 1.0
108078 2008-03-23 0.4 3.2
108079 2008-03-24 17.0 3.6
108080 2008-03-25 0.4 20.6
108081 2008-03-26 19.0 21.0
108082 2008-03-27 0.0 40.0
Grouping by location means the sum restarts for every place, so Sydney never reads Albury's rain. shift(1) stops the window at yesterday (the same idea as in Time Series Basics). On 25 March, the seven days before add up to 0 + 0 + 0 + 1.0 + 2.2 + 0.4 + 17.0 = 20.6. Today's rain is never inside, because it's already its own column.
show("Rain7", score(["Rain7"]))
te = df[~has]
alone = roc_auc_score(te["y"], te["Rain7"].fillna(0))
print("Rain7 on its own", round(alone, 4))
Rain7 0.8710 +0.0005
Rain7 on its own 0.6031
To be honest, +0.0005 is almost nothing. On its own Rain7 scores 0.6031, well above a coin flip, but today's columns already carry that signal, so it adds nothing new.
What if the window peeks?
df["Peek7"] = by_place.transform(
lambda s: s.rolling(7, center=True, min_periods=1).sum())
show("Peek7", score(["Peek7"]))
Peek7 0.9080 +0.0375
center=True also covers the next three days, so tomorrow's rain sits inside the column. A huge jump, and it's fake. A big jump is a reason to check the column first.
Pattern 4: replace a place with its rain rate
Location is text, with 49 places. Target encoding replaces each place with its own rain rate, using the training rows only:
means = df[has].groupby("Location")["y"].mean()
df["LocRain"] = df["Location"].map(means)
print(means.sort_values().round(3).iloc[[0, -1]].to_dict())
show("by hand", score(["LocRain"]))
{'Uluru': 0.059, 'Portland': 0.368}
by hand 0.8769 +0.0064
Uluru becomes 0.059, Portland 0.368. The gain is +0.0064, the biggest of the four, because the baseline model didn't know where it was.
Cross-fitting with TargetEncoder
One worry: a training row's own answer is inside its own mean. scikit-learn's TargetEncoder handles that by cross-fitting: each training row gets a mean computed from the other folds.
runs = []
for seed in range(42, 62):
folds = StratifiedKFold(5, shuffle=True, random_state=seed)
enc = TargetEncoder(cv=folds)
x, y = df.loc[has, ["Location"]], df.loc[has, "y"]
df.loc[has, "LocCV"] = enc.fit_transform(x, y).ravel()
rest = df.loc[~has, ["Location"]]
df.loc[~has, "LocCV"] = enc.transform(rest).ravel()
runs.append(score(["LocCV"]))
print(len(runs), "seeds", min(runs), "to", max(runs))
20 seeds 0.8736 to 0.8757
All 20 seeds land below the plain mean. With this many rows per place, that protection cost us a little.
And against one-hot encoding (from Encoding Categorical Data)?
spots = pd.get_dummies(df["Location"], prefix="at", dtype=int)
df = df.join(spots)
show("one hot", score(list(spots.columns)))
one hot 0.8773 +0.0068
A bit higher, with 49 columns. Target encoding didn't beat one-hot here. What it gives you is one column instead of 49, and that matters when a column has thousands of categories.
The same mistake, small and then large
Now the leaky way: the mean is taken over every row, so the test answers go in too.
# WRONG: this mean also reads the test rows' answers
leak = df.groupby("Location")["y"].mean()
df["LocLeak"] = df["Location"].map(leak)
show("leaky", score(["LocLeak"]))
leaky 0.8769 +0.0064
The same as by hand, to four decimals. On Location this leak doesn't show, because each place has so many rows that the test answers barely change its rain rate. Make the category smaller, a location plus a calendar month:
key = df["Location"] + df["Date"].dt.strftime(" %Y-%m")
print(key.nunique(), "keys,", int(key.value_counts().median()),
"rows each")
df["KeyLeak"] = key.map(df.groupby(key)["y"].mean())
df["KeyClean"] = key.map(df[has].groupby(key[has])["y"].mean())
show("leaky key", score(["KeyLeak"]))
show("clean key", score(["KeyClean"]))
4768 keys, 30 rows each
leaky key 0.8814 +0.0109
clean key 0.8636 -0.0069
4,768 keys of about 30 rows each, so each mean now holds a row's own answer. The same mistake scores 0.8814. Done cleanly, on training rows only, it's 0.8636, below the baseline: almost all test keys are new, and the training rows still read their own answers. Cross-fitting this key with TargetEncoder (5 seeds) gives 0.8692 to 0.8706, back near the baseline. So this key was never useful, and yet the leaky version beats everything honest we built.
All together, then at other cutoffs
FOUR = ["Month", "PressureChange", "Rain7", "LocRain"]
show("all four", score(FOUR))
show("without Rain7", score(FOUR[:2] + FOUR[3:]))
all four 0.8797 +0.0092
without Rain7 0.8798 +0.0093
Dropping Rain7 cost nothing. One cutoff can get lucky, so the notebook repeats each gain at four cutoffs (recomputing the location means from the earlier rows each time):
| Cutoff | Month | PressureChange | Rain7 | LocRain |
|---|---|---|---|---|
| 2013-05-27 | +0.0011 | +0.0025 | +0.0007 | +0.0033 |
| 2014-03-19 | +0.0014 | +0.0030 | +0.0004 | +0.0042 |
| 2015-01-12 | +0.0016 | +0.0029 | -0.0006 | +0.0045 |
| 2015-11-10 | +0.0014 | +0.0025 | +0.0005 | +0.0064 |
Month, pressure change and location stay positive all four times, and location is the biggest each time. Rain7 changes sign, so here it's just noise. None of these is a big win, because the strong columns were already in the baseline.
Common mistakes
- Assuming a pattern works. The same column helped boosted trees and did nothing for logistic regression.
- A window without
shift(1), or withcenter=True. It reads the future and scores like magic. - Target means over all rows. The test answers leak in. The smaller the category, the bigger the leak.
- Judging at one cutoff.
Rain7was positive at three cutoffs and negative at the fourth.
Quick recap
| Pattern | Column | AUC gain | Verdict |
|---|---|---|---|
| Date part | Month | +0.0014 | Small, steady |
| Difference | PressureChange | +0.0025 | Small, steady |
| Window | Rain7 | +0.0005 | Noise here |
| Target encoding | LocRain | +0.0064 | Biggest honest gain |
| Leaks | Peek7, leaky key | +0.0375, +0.0109 | Not real |
Try it yourself
Add Humidity3pm minus Humidity9am as a new column. Does it earn its place at all four cutoffs?
The notebook and the dataset are in the StudyEasy AI Community, free to join.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Time Series Basics: Lags, Rolling Windows and Walk-Forward Backtesting
Next →Point-in-Time Correctness: Join Features as of Each Event with merge_asof
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Python Virtual Environments: One Project, One Toolbox
Why every Python project gets its own virtual environment: two projects that need different versions of requests, python -m venv .venv, activation, pip install and the PyCharm setting that activates it for you.
Git and GitHub Fundamentals: Commits, Branches, Push and Pull
The Git you use every day, on a tiny hello-ml project: commits as save points, the staging area, a branch merged with a fast-forward, then push, clone, pull and pull requests with a teammate.
Testing a FastAPI App with pytest: Three Small Tests
A tiny FastAPI app with a Hello World route and a name route that refuses numbers, three pytest tests that check it, and what happens when the validation is deleted by mistake.
Config and Logging Instead of Hard-Coded Values in ML Training
Take the hard-coded values out of a car price training script: one config.toml read with tomllib, logging with levels and a run id on every line, and secrets read from the environment. Same RMSE, 2195, before and after.