Traditional models · lesson 2 of 16
Parts in this lesson
AX['bedroom_share'] = X['AveBedrms'] / X['AveRooms']a ratio, built from two columns
Btrips['date'].dt.dayofweeka feature taken from a date
CTfidfVectorizer()word counts, weighted by how rare each word is
DSelectKBest(f_classif, k=4)keep only the most useful features

Feature engineering and extraction

Last updated

A model can only learn from what you give it. Hand a linear model the distance to the nearest city and it suddenly understands house prices; hand logistic regression one squared distance and it draws circles. This lesson builds features from what you know about the problem, from dates, from text and from images, and then removes the features that only add noise.

By the end of this lesson you can

  • Build features from domain knowledge: ratios, distances, dates and interactions
  • Extract features from text with counts and TF-IDF, and from images with simple statistics
  • Select features, and explain why noisy features hurt some models
  • Spot target leakage in a feature built from the label

Domain knowledge first

Feature engineering is making new columns out of the ones you have, so that the pattern a model needs is easy to see. It's where knowing the problem pays most. Before reaching for a cleverer model, ask: what would an expert look at?

Meet the data for the rest of this stage: 2,000 districts of California from the 1990 US census (Pace and Barry, 1997). For each district, the median income (in tens of thousands of dollars), the median age of its houses, the average rooms, bedrooms and people per household, its population, its latitude and longitude, and the label, the median house value (in units of $100,000). A linear model, on the columns as they come, cross-validated:

features.ipynb

An RMSE of 0.713, about $71,000. An estate agent would say what's missing straight away: location. Latitude and longitude are there, but a straight line in latitude can't say "close to San Francisco or Los Angeles is expensive"; the cities are in the middle of the range, not at one end.

One feature that changes everything

So build what the agent means. The distance from each district to San Francisco and to Los Angeles (with the haversine formula, which measures along the Earth's curve), the nearer of the two, and two more ideas: the share of rooms that are bedrooms (a ratio: a house with a big living room is a nicer house), and the log of the population (lesson 4.1):

features.ipynb

The same model, the same data, a better answer: 0.685. Nothing about the model changed. Typical ingredients of a hand-made feature:

  • Ratios: per person, per room, per square metre. Bedrooms out of rooms, price per kilo, debt over income.
  • Differences: the time between two events, the gap between this month and last.
  • Counts and aggregates: how many orders this customer made before, their average size.
  • Distances: to a city, to the coast, to the nearest hospital.

Dates and times

A date written as 2025-03-14 means nothing to a model. Taken apart, it says a lot. A year of made-up daily jeepney riders on one route, busier on weekdays:

features.ipynb

.dt.dayofweek (0 is Monday), .dt.month, .dt.hour, .dt.dayofyear turn one date into the cycles that drive behaviour. Here, the day of the week is nearly everything:

features.ipynb

About 1,200 riders on weekdays, 900 on Saturdays, 650 on Sundays. A holiday flag, payday, the start of the school year, and the hours since the last typhoon warning are the kind of features that come from knowing the place. Encode the day of the week one-hot (lesson 4.1); as a number, 0 to 6, a linear model would think Sunday is "most".

Interactions, polynomials and bins

Some effects only exist together. Rain matters more for a jeepney route with no shelter; a big house is worth more in a rich district. An interaction feature is the product of two features, so a linear model can learn "this, when that". PolynomialFeatures(degree=2) adds every product and every square at once (lesson 3.8 used it for curves).

The circles data shows how far one well-chosen feature goes. Logistic regression can only draw straight lines, and the inner ring sits inside the outer one:

features.ipynb

45% on x and y, worse than a coin. Add one feature, x2+y2, the squared distance from the centre, and the same model gets 99.7%. Its straight-line boundary in three features is a circle in two:

Feature liftlogistic regression on circles

On x and y alone, logistic regression can only draw a straight line, and scores 52%, no better than a coin. The model isn't the problem; the features are.

Lesson 4.7's kernel trick does this automatically, for many features at once. And binning, cutting a number into ranges with KBinsDiscretizer (ages 0–17, 18–64, 65+), lets a linear model give each range its own weight, so it can follow a curve with steps.

Extracting features from text

Feature extraction turns raw data that isn't a table at all, text, images, sound, into columns. For text, the oldest method still works well: count the words (lesson 4.3 builds a spam filter on it). Plain counts make common words like "the" the biggest numbers. TF-IDF, term frequency times inverse document frequency, scales each count down by how many documents use the word:

idf(w)=ln⁡1+n1+df(w)+1

where n is the number of documents and df(w) the number that contain w. That's the formula scikit-learn uses by default.

features.ipynb

"the" is in three of the four messages and gets the smallest weight, 1.22; "claim" is in one and gets 1.92. In "the jeep is late", "late" and "jeep" end up with the biggest values, and they're the words that say what the message is about. Each row is then scaled to length 1, so long and short messages compare fairly.

Word counts forget the order of words. Stages 10 and 11 learn features from text that keep it.

Extracting features from images

An 8 × 8 digit is 64 pixels. Could fewer, more meaningful numbers do? Sum the ink in each of the 8 rows and each of the 8 columns: 16 numbers that describe the digit's shape.

features.ipynb

16 hand-made features reach 85.5%; all 64 pixels reach 92.8%. A quarter of the numbers keep most of the accuracy. For decades, image recognition worked like this, with experts designing features (edges, corners, gradients) and a simple model on top. Since 2012, convolutional networks (Stage 8) learn the features themselves, from the pixels, and do far better. For tables, though, hand-made features are still where the biggest gains usually are.

Selecting features

More features aren't always better. Take the penguins' four measurements and add 40 columns of pure noise:

features.ipynb

k-NN falls from 99.1% to 80.4%. Every noise column adds to every distance, so neighbours in the noise drown out neighbours in the bill and flipper. Picking the 4 best columns again, with SelectKBest and an F-test inside the pipeline, brings it back to 99.1%.

Ways to select:

  • Filter: score each feature on its own against the label (SelectKBest). Fast, but blind to features that only help together.
  • From a model: keep the features a lasso gives non-zero weights (lesson 3.8), or that a forest's permutation importance ranks highly (lesson 4.5), with SelectFromModel.
  • Common sense: drop IDs, duplicates and columns you won't have at prediction time.

Distance-based models suffer most from noise features. Trees and lasso pick their own features, and suffer least. Always select inside the pipeline: choosing features on all the data first is leakage, again.

Wrong way: a feature built from the label

Here's a feature that looks clever: the house value per room.

features.ipynb

RMSE 0.32, more than twice as good! But value_per_room was computed from y, the answer. A new district has no house value yet: that's what the model is meant to predict. This is target leakage, and it's the most common reason a model that tested brilliantly is useless in use. Subtler versions hide in real data: "number of follow-up visits" when predicting illness, "account closed date" when predicting who will leave.

The test for every feature: would I know this at the moment I make the prediction? If not, it goes. And a score that's suddenly too good is a reason for suspicion, not celebration.

Check what you learned

A linear model predicts a café’s daily sales. Which feature is likely to help it most?
You add 30 random columns to a data set. Which model’s cross-validated score is likely to fall the most?
A churn model scores 99% in testing using “days since the account was closed”. What’s the problem?

Sources

Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.

All sources for Simple Machine Learning