Topic 1 of 6 · 4 min read
Feature engineering for tabular data
Goal: Build a scikit-learn pipeline that encodes categories, imputes missing values and scales numbers without leaking test data.
Put every preprocessing step inside one scikit-learn Pipeline, fitted on the training split only, so the model never sees information from the test data. Feature engineering is turning raw columns into numbers a model can use. On tabular data it often moves the score more than switching algorithms.
Check yourself · 1 of 3
Why should a scaler be fitted only on the training split?
Why it matters
Models take numbers, not strings or blanks. A column such as city must be encoded. A blank in income must be filled or flagged. For linear models, a column in dollars and one in years must be put on a comparable scale. An AI assistant will happily write this code, but it often does it in the wrong order: it scales the whole dataset first and splits afterwards. The test rows then influence the mean and variance used for scaling, and your score looks better than it will be in production. This is called data leakage.
How to do it
- Split first. Call
train_test_splitbefore any fitting step. - Treat column types separately. Numeric columns: impute missing values (median is a safe default), then scale if the model needs it. Category columns: impute with a constant such as
"missing", then one-hot encode withhandle_unknown="ignore"so new categories at prediction time do not crash. - Combine with
ColumnTransformer, then chain it with the model in aPipeline. - Fit the pipeline once on the training data. Every statistic (medians, means, category lists) is learned there and only applied to the test data.
- Add simple derived features that encode what you know: a ratio, a date part, a count per customer.
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
num = ["age", "income"]
cat = ["city", "plan"]
prep = ColumnTransformer([
("num", Pipeline([("imp", SimpleImputer(strategy="median")),
("sc", StandardScaler())]), num),
("cat", Pipeline([("imp", SimpleImputer(strategy="constant", fill_value="missing")),
("oh", OneHotEncoder(handle_unknown="ignore"))]), cat),
])
model = Pipeline([("prep", prep), ("clf", LogisticRegression(max_iter=1000))])
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
model.fit(X_train, y_train)
Before and after
Before: X = StandardScaler().fit_transform(X) on all rows, then train_test_split. After: the scaler lives inside the pipeline and fit sees only X_train. The same rule applies to cross-validation: pass the whole pipeline to cross_val_score so each fold refits the preprocessing.
What goes wrong
- Leakage through early fitting. Imputing, scaling or target-encoding before the split.
- One-hot encoding a column with thousands of values such as a user id, which creates a huge sparse matrix and memorises rows. Group rare values or drop the id.
- Scaling for trees. Tree models split on thresholds and do not need scaling; it is harmless but wasted effort. Linear models and k-means do need it.
Examples
The leak an assistant wrote
X_scaled = StandardScaler().fit_transform(X)
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y)
The scaler computed its mean and variance on every row, including the test rows. Move the scaler into a Pipeline and call fit on X_train only.
A user id as a category
A churn dataset has user_id with 80,000 distinct values among 80,000 rows. One-hot encoding it adds 80,000 columns and lets the model memorise each customer. Drop the id, or replace it with something general such as account age or orders per month.
Key points
- Split the data before fitting any preprocessing step, or test rows leak into the training statistics.
- A Pipeline plus ColumnTransformer keeps imputing, encoding and scaling together with the model, so cross-validation refits them per fold.
- One-hot encode low-cardinality categories with handle_unknown set to ignore, so unseen categories at prediction time do not fail.
- Scale numeric columns for linear models and k-means; tree models do not need it.
- Median imputation is a safe default for skewed numbers, and a missing-value flag can carry signal of its own.
Common mistakes
- Fitting an imputer or scaler on the full dataset before the train/test split.
- Using a plain integer code for an unordered category (city 1, 2, 3) in a linear model, which implies an order that does not exist.
- Dropping rows with missing values without checking whether the missingness itself predicts the label.
- Hand-writing preprocessing outside the pipeline, so production code differs from the code that was evaluated.
Check yourself · 2 of 3
A trained pipeline fails in production with 'Found unknown categories' for a new city. Which one-hot setting avoids this?
Check yourself · 3 of 3
Which column most needs scaling before a logistic regression or k-means model?
Practice items, not counted towards your mastery.
Start here
- scikit-learn: ensembles (gradient boosting, random forests) (opens in a new tab)DocsFree
Reference for random forests and histogram gradient boosting, with the parameters that matter.
- XGBoost documentation (opens in a new tab)DocsFree
Official docs for the most used boosted-tree library, including parameter tuning notes.
- Why do tree-based models still outperform deep learning on tabular data? (opens in a new tab)PaperFree
The benchmark paper behind the claim that trees lead on medium-sized tabular data.
More for this topic
- scikit-learn: pipelines and composite estimators (opens in a new tab)DocsFree
Documents Pipeline and ColumnTransformer, the tools for per-column preprocessing.
- scikit-learn: common pitfalls and recommended practices (opens in a new tab)ArticleFree
Shows data leakage from preprocessing before the split and how pipelines prevent it.