◆ AI All-in-One

Level 3 In-Depth AI · Classical Machine Learning

Feature Engineering

Creating better inputs from the raw data. A well-chosen new column (a ratio, a distance, the day of the week, a word count) can turn a problem a model can't solve into one it solves easily. Deep learning automates much of this for images and text, but on tables it is still where most wins come from.

Level
●●●●● Easy
Reading
14 min
To learn it well
1 hour to read, an afternoon to practise
↗ Plan a path here

Read first

Supervised LearningData Cleaning and Preparation

This leads to

—
The full path from zero — 7 concepts before this one
  1. What Is AI?
  2. Python for AI
  3. How Machines Learn
  4. Pandas and Working with Data
  5. Supervised, Unsupervised and Reinforcement Learning
  6. Data Cleaning and Preparation
  7. Supervised Learning
  8. Feature Engineering

Read them roughly in this order. See it on the concept map →

Why it matters

A model can only learn from the inputs you give it. If the information it needs is present in the data but in an awkward form, many models can't dig it out. Feature engineering is the craft of transforming raw data into features that expose that information directly: ratios, differences, counts, flags, dates broken into parts, text turned into word counts.

On tabular data (customer records, transactions, sensor logs, medical records) it is often the single biggest lever on performance. Winning solutions in tabular data-science competitions, and well-run industry teams, typically spend more effort on features than on choosing algorithms. A credit model that sees "debt divided by income" instead of debt and income separately, or a demand forecast that knows "is this a public holiday?", can be dramatically better than one fed only raw columns.

Feature engineering is also where human knowledge enters a model. A doctor knows that body-mass index (weight divided by height squared) matters more than weight alone. A logistics expert knows that rush hour matters. Writing that knowledge down as features is one of the most effective things a person can do for a model. And understanding why deep learning largely replaced hand-made features for images, audio and text, through representation learning, explains much of the last fifteen years of AI.

The intuition

Suppose you want to predict taxi fares, and your raw data gives the pickup and drop-off points as four coordinates: two latitudes and two longitudes. The fare depends mostly on the distance travelled, but distance is a complicated function of those four numbers (differences, squares, a square root). A linear model can't compute it, and even a flexible model needs lots of data to approximate it. Add one column, the distance between pickup and drop-off, and the fare becomes nearly a straight-line function of a single feature.

Here is a stark case. Points of one class form a disc, and points of the other a ring around it. No straight line can separate them, so Logistic Regression on the raw coordinates is no better than a coin toss. Add one new feature, the squared distance from the centre r2=x12+x22r^2 = x_1^2 + x_2^2, and the classes separate perfectly with a single threshold.

-1 0 1 -1 0 1 x₁ x₂ Raw features: no straight line works logistic regression: 44% accuracy -1 0 1 0.5 1 1.5 2 x₁ r² = x₁² + x₂² Add r²: now a flat line separates them logistic regression: 100% accuracy threshold r² = 0.56 The dashed circle on the left and the dashed line on the right are the same boundary.
Fig. 1 Left, a disc of blue points surrounded by a ring of red ones: logistic regression on the raw coordinates scores 44%. Right, the same points plotted against the new feature r², the squared distance from the centre: a flat line now separates them and the same model scores 100%.

Nothing about the model changed. Only the description of the data did.

Key idea A good feature puts the information the model needs into a form the model can use easily. The best features come from understanding the problem: what would a human expert look at? Then build those features from training data only, and check on validation data that they actually help.

How it works

Combinations of features

  • Ratios and differences. Price per square metre, debt-to-income, time since last purchase, speed (distance over time), BMI. Often the single most valuable family.
  • Interaction features: products of two features, x1×x2x_1 \times x_2, capturing effects that depend on both. A discount may boost sales on weekends but not on weekdays; discount × is_weekend lets a linear model learn that.
  • Polynomial features: powers and products, such as xx, x2x^2, x3x^3, x1x2x_1 x_2. They let linear models bend (Linear Regression), at the cost of many more columns and a greater risk of Overfitting and the Bias–Variance Tradeoff. Scikit-learn's PolynomialFeatures generates them.

Tree-based models such as Random Forests and Bagging and Gradient Boosting: XGBoost and LightGBM can approximate interactions themselves, but even they benefit from good ratios: a tree needs many splits to approximate "x divided by y".

Transformations of a single feature

  • Log transform. Incomes, prices, populations and counts are often long-tailed: most values are modest and a few are huge. Taking log⁡(1+x)\log(1 + x) pulls the tail in, so that a change from £10,000 to £20,000 counts as much as one from £100,000 to £200,000. This often helps linear models and neural networks.
  • Binning: cutting a number into ranges (age 0–17, 18–34, 35–64, 65+) and treating each range as a category. It lets a linear model capture a non-linear, step-like effect and is robust to outliers, but it throws away detail within each bin. Use it when the effect really is step-like or when you need an easily explained model.
  • Flags: is_zero, was_missing, is_round_number. Small, but sometimes revealing. Fraudsters often type round amounts.

Dates and times

A raw timestamp is almost useless to a model. Break it into parts that plausibly matter: hour of day, day of week, month, weekend or not, public holiday or not, days until payday, time since the account was opened.

Cyclical quantities need care. As a plain number, hour 23 and hour 0 look 23 apart although they are one hour apart. Cyclical encoding places each hour on a circle using two features:

hour_sin=sin⁡ ⁣(2π⋅hour24),hour_cos=cos⁡ ⁣(2π⋅hour24)\text{hour\_sin} = \sin\!\left(\frac{2\pi \cdot \text{hour}}{24}\right), \qquad \text{hour\_cos} = \cos\!\left(\frac{2\pi \cdot \text{hour}}{24}\right)

Work it through for 18:00: the angle is 2π×18/24=3π/22\pi \times 18/24 = 3\pi/2, so sin⁡=−1\sin = -1 and cos⁡=0\cos = 0. For 0:00 the point is (0,1)(0, 1), and for 23:00 it is (−0.259,0.966)(-0.259, 0.966), a distance of only about 0.26 away. The same trick works for day of the week (divide by 7) and month (divide by 12).

0 3 6 9 12 15 18 21 23 Hour as a plain number 23:00 and 00:00 are 23 apart distance |23 − 0| = 23 0 3 6 9 12 15 18 21 23 Hour as (sin, cos) of its angle 23:00 and 00:00 sit side by side sin → ↑ cos hour_sin = sin(2π · hour / 24) hour_cos = cos(2π · hour / 24) distance between 23:00 and 00:00 ≈ 0.26
Fig. 2 Hours as plain numbers put 23:00 and 00:00 at opposite ends of the scale. Encoded as the sine and cosine of an angle, the 24 hours sit around a circle and 23:00 is next to midnight.

Many datasets are really several tables: customers and their transactions, shops and their sales. Summarise the related rows into features: the customer's number of orders in the last 30 days, their average basket size, how much this transaction deviates from their usual amount. These "behavioural" features are the backbone of fraud detection and churn prediction. Compute them using only data from before each prediction time, or you leak the future (Training, Validation and Test Sets).

Text counts

The simplest way to turn text into features is the bag of words: one column per word in the vocabulary, holding how often that word appears in the document. Word order is thrown away. Refinements include counting pairs of words (bigrams) and TF-IDF (term frequency × inverse document frequency), which down-weights words such as "the" that appear everywhere and up-weights words that are frequent in this document but rare overall. With a linear model on top, TF-IDF features are still a strong, fast baseline for spam filtering and topic classification. Scikit-learn provides CountVectorizer and TfidfVectorizer. Modern systems mostly use learned Sentence Embeddings instead.

Target encoding for many categories

One-hot encoding (Data Cleaning and Preparation) breaks down when a category has thousands of values (shop IDs, postcodes). Target encoding replaces each category by the average label for that category in the training data: shop 17 becomes "38% of its orders were returned".

The danger is that rare categories get unreliable, overfitted averages, and that each training row's own label leaks into its encoding. Two fixes are standard. Smoothing blends each category's mean with the global mean, trusting categories with few rows less:

encoding=n⋅yˉcat+m⋅yˉalln+m\text{encoding} = \frac{n \cdot \bar{y}_{\text{cat}} + m \cdot \bar{y}_{\text{all}}}{n + m}

Here nn is the category's number of rows, yˉcat\bar{y}_{\text{cat}} its mean label, yˉall\bar{y}_{\text{all}} the global mean, and mm a smoothing strength. Worked example: a shop with 3 orders, 2 of them returned (yˉcat=0.67\bar{y}_{\text{cat}} = 0.67), a global return rate of 0.2, and m=10m = 10: (3×0.67+10×0.2)/(3+10)=(2+2)/13=0.31(3 \times 0.67 + 10 \times 0.2)/(3 + 10) = (2 + 2)/13 = 0.31. Three orders aren't enough to believe 67%, so the estimate is pulled most of the way back to 20%. Cross-fitting computes each training row's encoding from the other folds, so a row never sees its own label. Scikit-learn's TargetEncoder does both.

Domain knowledge beats cleverness

The most valuable features usually come from asking people who know the problem. In predicting hospital readmissions: number of admissions in the past year, number of different medications, whether the discharge happened on a Friday. In predicting equipment failure: hours since last maintenance, vibration relative to that machine's normal level. No automatic method would think of "discharged on a Friday". It takes someone who knows that weekend staffing is thinner.

Feature selection

More features are not always better. Irrelevant ones add noise, slow training, and make overfitting easier. Feature selection keeps the useful ones: L1 Regularization: L1 and L2 (the lasso zeros out weights), importance scores from tree models, or simply dropping a feature and checking validation performance. As always, select inside the cross-validation loop, not on all the data (Training, Validation and Test Sets shows how badly that goes).

Why deep learning automates part of this

For decades, computer vision ran on hand-designed features: edge detectors, corner detectors, histograms of gradient directions (SIFT and HOG). Speech recognition ran on hand-designed spectral features. Text classification ran on bag-of-words counts. Each took years of expert work.

Deep learning replaced these with representation learning: the early layers of a neural network learn their own features from raw pixels, audio samples or tokens, trained end to end by Backpropagation for the task at hand. A convolutional network's first layer learns edge detectors much like the hand-made ones, and its deeper layers learn textures, parts and objects. A language model learns embeddings that capture meaning. When AlexNet won the ImageNet competition in 2012 with learned features, by a wide margin over hand-engineered systems, the field changed direction (A Short History of AI).

On tabular data, though, hand-crafted features plus gradient-boosted trees remain very hard to beat. Table columns are already meaningful, heterogeneous and few, so there is less raw structure for a network to discover, and domain knowledge is more valuable. Even in deep learning, feature engineering hasn't vanished. It has moved: into choosing inputs, designing data augmentation, writing prompts, and building the retrieval features of Retrieval-Augmented Generation systems.

In code

The ring-shaped data from the figure, without and with the engineered feature:

import numpy as np
from sklearn.datasets import make_circles
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score

# One class inside a ring of the other: no straight line can separate them
X, y = make_circles(n_samples=400, noise=0.1, factor=0.4, random_state=0)
print("raw x1, x2:        ", cross_val_score(LogisticRegression(), X, y, cv=5).mean().round(3))

r2 = (X ** 2).sum(axis=1, keepdims=True)         # new feature: squared distance from centre
X_new = np.hstack([X, r2])
print("x1, x2 + radius^2: ", cross_val_score(LogisticRegression(), X_new, y, cv=5).mean().round(3))
# raw x1, x2:         0.443
# x1, x2 + radius^2:  1.0

Date features with Pandas and Working with Data, including the cyclical encoding of the hour:

import numpy as np
import pandas as pd

orders = pd.DataFrame({"time": pd.to_datetime(
    ["2024-03-15 18:30", "2024-03-16 09:05", "2024-03-17 23:50", "2024-03-18 00:10"])})
t = orders["time"]
orders["day_of_week"] = t.dt.day_of_week               # Monday = 0 ... Sunday = 6
orders["is_weekend"] = (t.dt.day_of_week >= 5).astype(int)
orders["hour"] = t.dt.hour
orders["hour_sin"] = np.sin(2 * np.pi * t.dt.hour / 24).round(3) + 0.0   # 23:00 and 00:00
orders["hour_cos"] = np.cos(2 * np.pi * t.dt.hour / 24).round(3) + 0.0   # end up close together
print(orders.to_string(index=False))
#                time  day_of_week  is_weekend  hour  hour_sin  hour_cos
# 2024-03-15 18:30:00            4           0    18    -1.000     0.000
# 2024-03-16 09:05:00            5           1     9     0.707    -0.707
# 2024-03-17 23:50:00            6           1    23    -0.259     0.966
# 2024-03-18 00:10:00            0           0     0     0.000     1.000

(The + 0.0 turns a printed -0.000 into 0.000.) Finally, target encoding a category with 1,000 values, done naively and done properly:

import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import KFold, train_test_split
from sklearn.preprocessing import TargetEncoder
from sklearn.metrics import roc_auc_score

# 3,000 orders from 1,000 different shops; some shops have far more returns
rng = np.random.default_rng(0)
shop = rng.integers(0, 1000, 3000)
shop_effect = rng.normal(0, 1.5, 1000)
y = (rng.random(3000) < 1 / (1 + np.exp(-(shop_effect[shop] - 1)))).astype(int)
X = shop.reshape(-1, 1)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, random_state=0)

# Naive: replace each shop by its average label in the training set
means = {s: y_tr[X_tr[:, 0] == s].mean() for s in np.unique(X_tr)}
naive = lambda X: np.array([[means.get(s, y_tr.mean())] for s in X[:, 0]])
m = LogisticRegression().fit(naive(X_tr), y_tr)
print("naive target mean:  train AUC %.3f  test AUC %.3f"
      % (roc_auc_score(y_tr, m.predict_proba(naive(X_tr))[:, 1]),
         roc_auc_score(y_te, m.predict_proba(naive(X_te))[:, 1])))

# scikit-learn's TargetEncoder: smoothed, and cross-fitted on the training set
enc = TargetEncoder(cv=KFold(5, shuffle=True, random_state=0))
Z_tr = enc.fit_transform(X_tr, y_tr)             # each row encoded without its own label
m = LogisticRegression().fit(Z_tr, y_tr)
print("TargetEncoder:      train AUC %.3f  test AUC %.3f"
      % (roc_auc_score(y_tr, m.predict_proba(Z_tr)[:, 1]),
         roc_auc_score(y_te, m.predict_proba(enc.transform(X_te))[:, 1])))
# naive target mean:  train AUC 0.944  test AUC 0.684
# TargetEncoder:      train AUC 0.692  test AUC 0.685

Both reach the same test AUC here, but look at the training scores. With naive encoding, most shops have only two or three training orders, so each row's encoding largely is its own label, and the training AUC of 0.944 is a fantasy. Any model trained on top of that feature, alongside others, will trust it far too much. The cross-fitted encoder's training score, 0.692, honestly matches what happens on new data.

Common pitfalls

  • Leaking the target or the future. Aggregates computed over the whole dataset, target encodings that include each row's own label, or "days until churn" style features all leak. Build every feature as it would have been known at prediction time.
  • Fitting feature steps on all the data. Binning edges, target encodings, vocabulary lists and selected-feature lists must be learned from the training folds only. Put them in a pipeline.
  • Feature explosion. Polynomial features of degree 3 on 100 columns create over 170,000 features. Add only combinations you have reason to believe in, and regularise.
  • Training–serving skew. A feature computed one way in a notebook and another way in the production system silently degrades the model. Share one implementation.
  • Not checking that a feature helps. Every feature should earn its place on validation data. Intuition is a source of ideas, not proof.

Watch out The most "predictive" feature in a dataset is very often a leak: an ID that encodes the outcome, a timestamp recorded after the event, a field filled in only for positive cases. If one new feature makes the score jump dramatically, suspect leakage before celebrating.

Where it leads

A bit of history

For most of machine learning's history, feature engineering was the job. Statisticians have long transformed variables (logs, polynomials, indicator variables) before fitting regressions. In computer vision, David Lowe's SIFT features (1999, refined in 2004) and Navneet Dalal and Bill Triggs' HOG features (2005) were landmark hand-designed representations. In speech, mel-frequency cepstral coefficients (MFCCs) were the standard input for decades. Text classification used bag-of-words and TF-IDF, the latter going back to Karen Spärck Jones's 1972 work on term specificity. The 2012 success of AlexNet showed that features learned from raw pixels beat decades of hand design, and Yoshua Bengio, Aaron Courville and Pascal Vincent's 2013 review "Representation Learning" named the shift. On tabular data, though, Kaggle competition write-ups through the 2010s and 2020s show feature engineering with gradient-boosted trees still winning more often than not.

Try it

  1. Compute the cyclical encoding of 6:00 and 12:00 by hand. How far apart are 6:00 and 18:00 in the encoded space?
  2. In the circles code, replace the r2r^2 feature with x1⋅x2x_1 \cdot x_2. Does it help? Why or why not?
  3. Smoothed target encoding: a postcode has 50 rows with a mean label of 0.4, the global mean is 0.1, and m=10m = 10. What is its encoding? What if it had only 1 row with label 1?

Hint for 1: 6:00 is a quarter of the way round the circle, so its point is (1, 0). 18:00 is at (−1, 0), so they are 2 apart: the full width of the circle, as far apart as two hours can be.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. One class of points forms a disc and the other a ring around it. Logistic regression on the raw coordinates scores about 44%. Which single new feature fixes this?

  2. Your model uses hour of day as a plain number, so 23:00 and 00:00 look 23 apart. What fixes this?

  3. A shop has only 3 orders, 2 of them returned, and the global return rate is 0.2. With smoothed target encoding (m = 10), the shop's encoding comes out near 0.31. Why is it not 0.67?

  4. You add one new feature and validation accuracy jumps dramatically. What should you check first?

  5. Why did deep learning largely replace hand-made features for images and text, but not for tables?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Course

Kaggle Learn

Kaggle · Beginner · Free

Bite-sized interactive courses (Python, Pandas, intro ML, feature engineering) that run in the browser.

Docs

scikit-learn: Preprocessing data

scikit-learn · Intermediate · Free

The guide to scalers, encoders, discretisers and other transformers, with advice on which to use when and how they behave with outliers.

Book

Hands-On Machine Learning (code notebooks)

Aurélien Géron · Beginner · notebooks free, book paid

A very practical bestselling book that covers scikit-learn through deep learning. All of its notebooks are free on GitHub.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/ml/feature-engineering.md