Sub topic 1
What Feature Engineering Is and Why It Matters
Prerequisites
This chapter assumes you have the following background:
- Basic Python and pandas, including DataFrames and column selection.
- Core supervised learning ideas: features, labels, and the split into training and test sets.
- Familiarity with scikit-learn's
fitandpredictworkflow. - Basic statistics: mean, variance, and distributions.
No other chapter is needed first. This chapter sets up the vocabulary and the working model that the next fifteen chapters build on.
What a feature is
A feature is one input column that a model reads to make a prediction. The label (or target) is the column you want to predict. A model never sees "a customer" or "a transaction". It sees a row of numbers.
Raw data rarely arrives as a clean matrix of numbers. A real table usually has:
- Missing values.
- Text categories such as
"Berlin"or"premium". - Timestamps stored as strings.
- Numeric columns with very different ranges, such as
age(18 to 90) andincome(0 to 5,000,000). - Columns with heavy skew, where a few huge values dominate.
Feature engineering is the work of turning this raw data into columns that a model can use well. It covers cleaning, converting, scaling, combining, creating, and selecting columns. The result is a numeric matrix X that carries the signal in the data in a form the algorithm can exploit.
Why it matters
Feature engineering often changes model quality as much as the choice of algorithm does. There are three main reasons.
Models need numeric input
Most scikit-learn estimators raise an error on text values or NaN. Even when a model accepts the input, it may handle it badly. A linear model that receives a city name encoded as 1, 2, 3 treats city 3 as three times city 1. That is a representation error, and no tuning of the algorithm fixes it.
Models have built-in assumptions
Each algorithm assumes something about its input. The table shows common examples.
| Model family | Sensitive to feature scale | Handles non-linear relations by itself | Accepts missing values natively |
|---|---|---|---|
| Linear and logistic regression | Yes | No | No |
| k-nearest neighbors, SVM | Yes | Depends on kernel | No |
| Neural networks | Yes | Yes | No |
| Decision trees, random forests | No | Yes | Some implementations |
| Gradient boosting (for example `HistGradientBoosting`) | No | Yes | Yes |
A distance-based model such as k-nearest neighbors computes distances across all columns. If income spans millions and age spans tens, income decides almost every distance. Scaling fixes this. A tree does not care, because it splits one column at a time.
This table is also why "just use gradient boosting" does not remove the need for feature engineering. Trees still benefit from good date-time parts, ratios, and aggregates, and they still suffer from leakage and from high-cardinality categories.
Good features encode domain knowledge
A model can only learn patterns that are reachable from its inputs. If the real signal is "spend per visit", and you supply only total_spend and visits, a linear model cannot form the ratio. A tree needs many splits to approximate it. Adding spend_per_visit = total_spend / visits makes the relationship direct.
The same applies to time. A raw timestamp is one large number that grows forever. Features such as hour, day of week, and "is weekend" expose the repeating patterns that actually drive behavior.
A small worked example
The example below shows the idea on synthetic data. Revenue depends on the ratio of two columns. The same linear model is fitted on raw columns and on an engineered ratio.
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import r2_score
rng = np.random.default_rng(0)
n = 2000
visits = rng.integers(1, 50, size=n)
total_spend = visits * rng.uniform(5, 100, size=n)
df = pd.DataFrame({"visits": visits, "total_spend": total_spend})
# the target depends on spend per visit, with a little noise
df["target"] = 3.0 * (df["total_spend"] / df["visits"]) + rng.normal(0, 5, size=n)
X_raw = df[["visits", "total_spend"]]
X_eng = X_raw.assign(spend_per_visit=df["total_spend"] / df["visits"])
y = df["target"]
for name, X in [("raw", X_raw), ("engineered", X_eng)]:
X_tr, X_te, y_tr, y_te = train_test_split(X, y, random_state=0)
pred = LinearRegression().fit(X_tr, y_tr).predict(X_te)
print(name, round(r2_score(y_te, pred), 3))The raw version scores clearly lower than the engineered version, which should score close to 1.0. The algorithm, the data, and the split are identical. Only the features changed.
Notice that spend_per_visit uses no information from y and no statistics from the test rows. It is computed row by row. That property matters, and the next section explains why.
The central rule: learn from training data only
Some transformations are stateless. A row-wise ratio or a calendar part such as the hour needs nothing beyond the row itself. Others are stateful. They learn a number from the data and then apply it:
- A median used to fill missing values.
- A mean and standard deviation used for scaling.
- The set of categories seen by an encoder.
- Feature importances used to select columns.
A stateful transformation must be fitted on the training data only, then applied unchanged to validation, test, and production data. If you fit it on the full dataset, information about the held-out rows leaks into training. Your evaluation score then looks better than the real performance. This problem is called data leakage, and Chapter 3 covers it in depth. It shapes how every other technique in this tutorial is used.
Scikit-learn expresses the rule through the fit and transform split. fit learns the state from training data. transform applies it. The Pipeline and ColumnTransformer classes (Chapter 12) chain these steps so the rule is followed automatically, including inside cross-validation.
The shape of the workflow
Feature engineering is not a one-off cleanup step. It is a loop. You inspect the data, form a hypothesis, build a feature, measure the effect with cross-validation, and keep or discard it.
Two habits keep this loop honest:
- Always build a baseline first. Fit a simple model on minimally prepared data, and record its cross-validated score. Every later change is judged against it.
- Change one thing at a time. If you add five features and the score moves, you do not know which one helped.
Limits and trade-offs
Feature engineering is powerful, but it has costs.
- Maintenance. Every feature must be computed identically at training time and at serving time. Each added feature is another place where the two can diverge (Chapter 16).
- Overfitting to the validation set. If you try hundreds of ideas and keep whichever scores best, the score you report is biased upward. Keep a final test set that you touch once.
- Dimensionality. One-hot encoding a column with 10,000 categories creates 10,000 columns. Chapters 7, 11, and 15 cover alternatives.
- Diminishing returns. Past a point, more feature work gives less improvement than collecting better data or defining the label more carefully.
- Interpretability. Polynomial terms and PCA components are harder to explain than the original columns.
Where the rest of the tutorial goes
The remaining chapters follow the order you would use on a real table:
| Stage | Chapters |
|---|---|
| Understand the columns and the leakage rule | 2, 3 |
| Clean and rescale numeric data | 4, 5, 6 |
| Encode categories, dates, and text | 7, 8, 10 |
| Create new features | 9, 11 |
| Assemble and evaluate | 12, 13 |
| Reduce the feature set | 14, 15 |
| Deploy consistently | 16 |
Exercise
A teammate standardizes all columns of the full dataset with StandardScaler().fit_transform(X), then splits into train and test sets and reports a test score. Name the problem, and say what they should do instead.
Show answer
The scaler's mean and standard deviation were computed using the test rows, so information from the test set leaked into preprocessing and the test score is optimistic. They should split first, fit the scaler on the training rows only, and apply it to the test rows with transform. Placing the scaler and model in a Pipeline does this automatically, including inside cross-validation.
Exercise
You train a random forest and a k-nearest neighbors model on a table where income ranges up to 5,000,000 and age ranges from 18 to 90. Which model is likely to be affected by the difference in scale, and why?
Show answer
K-nearest neighbors. It measures distances across all columns, so income dominates the distance and age has almost no influence. A random forest splits on one column at a time using thresholds, so a column's scale does not change which splits are chosen.
Exercise
In the worked example, why is spendpervisit safe to compute on the full dataset before splitting, while a median imputer is not?
Show answer
spendpervisit is stateless. It uses only values in the same row and learns nothing from the data. A median imputer is stateful, because the median is computed from many rows. If it is computed on the full dataset, held-out rows influence the value used on training rows, which is leakage.