Feature Engineering
A model can only learn from the features you give it. Feature engineering means creating new, more informative features from the raw data, using your knowledge of the problem. Experienced practitioners often say better features beat a fancier algorithm — and the examples below show why.
Ratios and combinations
Suppose a flooring company predicts the cost of tiling a room from its length and width. Neither number alone tells the story; the floor area (length × width) does:
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import cross_val_score
rng = np.random.default_rng(0)
length_m = rng.uniform(2, 12, 200)
width_m = rng.uniform(2, 8, 200)
cost = 25 * length_m * width_m + 150 + rng.normal(0, 40, 200) # price per m² + call-out fee
raw = np.column_stack([length_m, width_m])
engineered = np.column_stack([length_m, width_m, length_m * width_m])
for name, X in [("raw features", raw), ("+ floor area", engineered)]:
r2 = cross_val_score(LinearRegression(), X, cost, cv=5).mean()
print(f"{name:13} CV R^2 = {r2:.3f}")raw features CV R^2 = 0.935
+ floor area CV R^2 = 0.994
A linear model can only add up weighted features; it can't multiply one by another by itself. Hand it the product, and it explains almost all of the variation.
Dates and times
A raw timestamp is almost useless to a model, but its parts are rich: hour of day, day of week, month, weekend or not.
import pandas as pd
orders = pd.DataFrame({"timestamp": pd.to_datetime([
"2024-03-01 08:15", "2024-03-02 19:40", "2024-03-03 12:05",
"2024-03-04 23:55", "2024-03-09 10:30",
])})
ts = orders["timestamp"]
orders["hour"] = ts.dt.hour
orders["weekday"] = ts.dt.dayofweek # Monday = 0
orders["is_weekend"] = (ts.dt.dayofweek >= 5).astype(int)
orders["month"] = ts.dt.month
print(orders) timestamp hour weekday is_weekend month
0 2024-03-01 08:15:00 8 4 0 3
1 2024-03-02 19:40:00 19 5 1 3
2 2024-03-03 12:05:00 12 6 1 3
3 2024-03-04 23:55:00 23 0 0 3
4 2024-03-09 10:30:00 10 5 1 3
Cyclical features
Hour 23 and hour 0 are neighbours, but as numbers they are 23 apart. Encoding a cycle with sine and cosine puts them close together:
import numpy as np
hours = np.array([0, 6, 12, 18, 23])
hour_sin = np.sin(2 * np.pi * hours / 24)
hour_cos = np.cos(2 * np.pi * hours / 24)
for h, s, c in zip(hours, hour_sin, hour_cos):
print(f"hour {h:2}: sin={s:6.3f} cos={c:6.3f}")
d = lambda a, b: np.hypot(hour_sin[a] - hour_sin[b], hour_cos[a] - hour_cos[b])
print(f"distance 23h-0h: {d(4, 0):.3f} distance 0h-12h: {d(0, 2):.3f}")hour 0: sin= 0.000 cos= 1.000
hour 6: sin= 1.000 cos= 0.000
hour 12: sin= 0.000 cos=-1.000
hour 18: sin=-1.000 cos=-0.000
hour 23: sin=-0.259 cos= 0.966
distance 23h-0h: 0.261 distance 0h-12h: 2.000
Transforming skewed values
Prices, incomes and counts are often heavily skewed. A log transform (np.log1p = log(1 + x), safe for zeros) compresses large values and can make relationships more linear:
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import cross_val_score
rng = np.random.default_rng(1)
followers = rng.lognormal(mean=7, sigma=1.5, size=300) # very skewed
likes = 12 * np.log1p(followers) + rng.normal(0, 4, 300)
for name, X in [("raw followers", followers), ("log1p(followers)", np.log1p(followers))]:
r2 = cross_val_score(LinearRegression(), X.reshape(-1, 1), likes, cv=5).mean()
print(f"{name:17} CV R^2 = {r2:.3f}")
print(f"followers range: {followers.min():.0f} .. {followers.max():.0f}")raw followers CV R^2 = 0.215
log1p(followers) CV R^2 = 0.950
followers range: 19 .. 114699
Binning
Sometimes a number works better as a category, for example ages grouped into life stages. pd.cut creates the bins; KBinsDiscretizer does the same inside scikit-learn:
import pandas as pd
ages = pd.Series([3, 15, 22, 37, 45, 61, 70, 88])
stage = pd.cut(ages, bins=[0, 12, 19, 64, 120], labels=["child", "teen", "adult", "senior"])
print(pd.DataFrame({"age": ages, "stage": stage})) age stage
0 3 child
1 15 teen
2 22 adult
3 37 adult
4 45 adult
5 61 adult
6 70 senior
7 88 senior
Aggregations per group
Facts about a customer's history are often the strongest features. pandas groupby + transform attaches group statistics to each row:
import pandas as pd
purchases = pd.DataFrame({
"customer": ["ana", "ana", "ben", "ana", "ben", "cy"],
"amount": [20, 35, 120, 15, 80, 42],
})
grouped = purchases.groupby("customer")["amount"]
purchases["customer_avg"] = grouped.transform("mean").round(1)
purchases["customer_orders"] = grouped.transform("count")
purchases["vs_own_avg"] = (purchases["amount"] / purchases["customer_avg"]).round(2)
print(purchases) customer amount customer_avg customer_orders vs_own_avg
0 ana 20 23.3 3 0.86
1 ana 35 23.3 3 1.50
2 ben 120 100.0 2 1.20
3 ana 15 23.3 3 0.64
4 ben 80 100.0 2 0.80
5 cy 42 42.0 1 1.00
A purchase three times larger than the customer's usual amount is a much stronger fraud signal than the raw amount.
Warning: Beware of leakage when engineering features. A feature computed from information that won't be available at prediction time (tomorrow's price, the final outcome, or statistics over the whole data set including test rows) makes the model look great in testing and fail in production.
Test yourself
Why encode the hour of day with sine and cosine?
- To make the numbers smaller
- So that 23:00 and 00:00 end up close together
- Because models can't read integers
- To remove missing values
What does np.log1p(x) compute?
- log(x) - 1
- log(1 + x)
- 1 / log(x)
- x to the power 1
Which engineered feature would cause data leakage when predicting whether a loan will default?
- Income divided by loan amount
- Applicant's age group
- Number of missed payments recorded after the loan was granted
- Month of application