A model only sees the columns you give it. Hand a simple model the hour of the day as one number and it can’t see a lunch rush; hand it the same information in a better shape and it can. A model can only learn the patterns its inputs make easy to see. That’s why reshaping the inputs, called feature engineering, often does more than swapping in a fancier model. Here you’ll give a model better and worse versions of the same columns and watch its accuracy follow.
Features are the model’s view of the world#
A feature is one column a model learns from. Raw data rarely arrives in the best shape: a timestamp, a city name, a price and a floor area. Feature engineering turns those into columns a model can use: the hour and day of the week, one yes/no column per city, the price per square metre. None of it adds new information. It rearranges what you have so the pattern is easier to reach.
The same hour, three ways#
A food-delivery app wants to predict how many orders arrive each hour, to plan riders. Orders peak at lunch and dinner, carry on past midnight, and weekends look different. The model here is the simplest there is, linear regression: it multiplies each column by a weight and adds them up.
Predict first
The model gets the hour as a single number, 0 to 23. What can it draw for orders through the day?
With the hour as one number the model scores an R² of 0.24 (the share of the variation it explains, where 1 is perfect) and is off by 12 orders an hour on average. Give it the hour as 24 categories, one yes/no column per hour (one-hot encoding), and each hour gets its own weight: R² 0.79, off by 5.6. Add a weekend column and a copy of the hour columns that only switch on at weekends (an interaction), and the model can draw a separate weekend shape: R² 0.93, off by 3.3. Same model, same data, nearly four times the accuracy. The data hasn’t changed; what changed is what the model is allowed to draw.
The circle is the middle road. Hour 23 and hour 0 are an hour apart, but as numbers they’re 23 apart. Placing the hour on a circle with a sine and a cosine (sin(2π·hour/24), cos(2π·hour/24)) puts midnight next to 23:00 and uses four columns instead of 24. It scores 0.42 here, because smooth waves can’t make peaks this sharp. It shines when the pattern really is smooth, or when there are too many categories to give each its own column, like day of the year.
Categories and counts#
One-hot encoding works for any category with a handful of values: city, payment method, device. With thousands of values, like postcodes or product IDs, it makes too many sparse columns. Common alternatives: how often each value appears, the average outcome for that value (target encoding, which must be worked out from training rows only, or it leaks the answer), or a learned embedding.
Some of the best features are summaries of other rows: a customer’s number of orders in the last 30 days, their average basket, the time since their last visit. Each is one groupby in pandas, worked out only from data you’d have at the moment of prediction.
When the units decide#
Some models compare rows by distance. k-nearest neighbours labels a customer by looking at the most similar customers it has seen and taking a vote. “Most similar” means the smallest distance across all the columns, and that’s where units sneak in.
Predict first
Customers are described by monthly spend (£10 to £200) and support calls last month (0 to 10), in those raw units. When the model measures distance, which column decides who counts as a neighbour?
In raw units the picked customer, who spends £75 a month, made no support calls and stayed, gets neighbours who spend about the same but called support 3 or 4 times on average, and most of them left. So the model says they’ll leave. Overall it gets 71% right. Scale each column to the same spread (subtract the mean, divide by the standard deviation, worked out on the training rows) and both columns count: the neighbours now match on calls too, and accuracy rises to 90%.
Then add useless columns, numbers with nothing to do with leaving. Scaling makes them count as much as the real ones: with 2, accuracy drops to 81%; with 10, to 79%; with 50, to 60%, and the yellow neighbours are scattered all over the chart. Watch the second tile. With 50 extra columns the nearest customer is, on average, 62% as far away as the farthest one: in many dimensions, everything is roughly equally far from everything else, so “nearest” stops meaning much. This is the curse of dimensionality. More columns aren’t free: every column that doesn’t help makes the useful ones harder to see.
Habits that keep features honest#
- Fit on training rows only. Scalers, encoders and group averages all learn from data. Put them in a scikit-learn
Pipeline(orColumnTransformer) so they’re fitted on training rows and only applied to test rows. - Ask what you’d know at prediction time. A feature from the future, like “refund issued”, makes a model look brilliant and fail in use.
- Start from how the thing works. The best features come from knowing the problem: rushes happen at mealtimes, price depends on size, people who call support are unhappy.
- Check every feature earns its place. Compare validation scores with and without it, and drop what doesn’t help.
In code#
The second figure’s experiment with scikit-learn, on freshly drawn customers:
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
rng = np.random.default_rng(0)
spend = rng.uniform(10, 200, 300) # £ a month
calls = rng.poisson(rng.uniform(0.5, 5.5, 300)) # support calls last month
churn = rng.random(300) < 1 / (1 + np.exp(-2 * (-0.035 * (spend - 105) + (calls - 3))))
X = np.column_stack([spend, calls])
X_train, X_test, y_train, y_test = train_test_split(X, churn, test_size=100, random_state=0)
raw = KNeighborsClassifier(n_neighbors=7).fit(X_train, y_train)
scaled = make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=7)).fit(X_train, y_train)
print(f"raw units: {raw.score(X_test, y_test):.2f}")
print(f"scaled: {scaled.score(X_test, y_test):.2f}")
# 50 useless columns, scaled like the rest
noise = rng.normal(size=(300, 50))
X_noisy = np.column_stack([X, noise])
Xn_train, Xn_test = train_test_split(X_noisy, test_size=100, random_state=0)
noisy = make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=7)).fit(Xn_train, y_train)
print(f"+50 junk: {noisy.score(Xn_test, y_test):.2f}")
# raw units: 0.76
# scaled: 0.91
# +50 junk: 0.66And the hour on a circle, ready for any model: np.sin(2 * np.pi * hour / 24) and np.cos(2 * np.pi * hour / 24).
What to remember
- Feature engineering reshapes what you already have (categories, cycles, interactions, group summaries) so a model can reach the pattern.
- The same simple model went from R² 0.24 to 0.93 just by encoding the hour as categories with a separate weekend pattern.
- Distance-based models need scaled columns, and every useless column dilutes the useful ones: choose features, don’t just pile them up.