Skip to content

33. Feature engineering

A model learns only from the numbers that you give it. A date string, a plan name or a price with a long tail is not a good input yet. Feature engineering is the work of creating, transforming and choosing the input columns so that a model can learn the real pattern. On tabular data, it often improves a model more than a change of algorithm does.

This module uses three course datasets: data/customers.csv (which customers churn), data/houses.csv (what a house sells for) and data/sales.csv (daily demand). The data dictionary describes every column.

  • Use the scikit-learn transformer API: fit learns from the training data, transform applies what it learned.
  • Scale numeric features with StandardScaler, MinMaxScaler and RobustScaler, and know which models need scaling.
  • Encode categories with one-hot, ordinal (with an explicit order) and target encoding, and explain why naive target encoding leaks.
  • Build binned, polynomial, interaction, date and log-transformed features.
  • Select features with filter, wrapper and embedded methods.
  • Recognize data leakage, measure how much it inflates a score and fit every step on training data only.

You do not need to know the models in this module. Each example uses a simple model (k-nearest neighbors, logistic regression, linear regression or a tree) only to measure whether a feature helps. Modules 35 and 36 teach these models in depth.

A feature is one input column of a model, such as tenure_months. The target is the column that the model predicts, such as churned. Raw data rarely arrives in the best form for a model:

Raw column Problem for a model Engineered feature
monthly_charges (28–143) next to total_charges (30–8,323) the large column dominates distances scaled columns with a similar spread
plan = "basic", "standard", "premium" a model needs numbers one 0/1 column per plan, or the codes 0, 1, 2
signup_date = "2021-03-14" a string has no order or distance days since signup, signup month
price from 117,500 to 3,730,500 a long right tail; errors are in percent log(price)
sqft and neighborhood the value of one more square foot depends on the area log(sqft) × neighborhood
25 candidate columns noise columns add variance and cost the 10 columns that carry signal

The work has four parts. You transform columns (scale, log), encode non-numeric columns, create new columns (bins, interactions, dates) and select the useful ones. A rule holds for all four: anything that learns from data learns from the training rows only.

flowchart LR
    R["Raw table"] --> S["Split:<br/>train / test"]
    S --> T["Transform<br/>scale, log"]
    T --> E["Encode<br/>categories"]
    E --> C["Create<br/>bins, interactions, dates"]
    C --> F["Select<br/>features"]
    F --> M["Model"]

In scikit-learn, an estimator is any object that learns from data with a fit method. A transformer is an estimator that also changes data with a transform method. A scaler, an encoder and a feature selector are transformers. The API has three methods:

Method Does Use on
fit(X) learns parameters from X and stores them in attributes that end with _ the training set
transform(X) applies the stored parameters to X the training set and the test set
fit_transform(X) fit and transform in one call the training set only

You built the same idea in module 18 with the minilearn StandardScaler. Here is the scikit-learn version on five monthly charges. The first block also fixes the pandas display options for this page.

import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
pd.set_option("display.width", 100)
pd.set_option("display.max_columns", 12)
pd.set_option("display.precision", 3)
charges = pd.DataFrame({"monthly_charges": [29.5, 45.0, 60.8, 88.2, 120.0]})
scaler = StandardScaler()
scaler.fit(charges)
print(scaler.mean_, scaler.scale_.round(2))
print(scaler.transform(charges).ravel().round(2))
print(scaler.transform(pd.DataFrame({"monthly_charges": [143.24]})).round(2))
Output
[68.7] [32.16]
[-1.22 -0.74 -0.25 0.61 1.59]
[[2.32]]

fit stored the mean and the standard deviation (scale_) of the five values. transform uses them on any rows, including a new customer whose charge is above every training value. The learned attributes end with an underscore, the scikit-learn naming rule for anything that fit creates.

By default, a transformer returns a NumPy array and drops the column names. set_output(transform="pandas") makes it return a DataFrame with named columns, which is easier to read and to debug:

scaler = StandardScaler().set_output(transform="pandas")
print(scaler.fit_transform(charges).round(2).T)
Output
0 1 2 3 4
monthly_charges -1.22 -0.74 -0.25 0.61 1.59

Feature scaling puts numeric features on a similar range. It matters for three kinds of models:

  • Distance-based models compare rows by their distance, such as the Euclidean distance of module 32. k-nearest neighbors (KNN), k-means and support vector machines are in this group. A column measured in thousands then outweighs a column measured in units.
  • Gradient-based models (logistic regression, neural networks) are trained by iterative optimizers such as gradient descent or lbfgs (scikit-learn’s default solver for logistic regression). Features on very different scales make the loss surface long and narrow, so training needs more steps.
  • Regularized models add a penalty on the size of the coefficients to the loss. Regularization keeps a model simple and reduces overfitting. The penalty treats every coefficient the same, so the features must share one scale for the penalty to be fair. Ridge, Lasso and scikit-learn’s LogisticRegression (regularized by default) are in this group.

Decision trees, random forests and gradient boosting do not need scaling. A tree splits on thresholds such as tenure_months <= 6, and a threshold works the same on any monotone rescaling of the column.

scikit-learn has three common scalers. μ\mu is the mean, σ\sigma the standard deviation, Q1Q_1 and Q3Q_3 the first and third quartiles:

Scaler Formula Result Outliers Use when
StandardScaler z=x−μσz = \dfrac{x - \mu}{\sigma} mean 0, standard deviation 1 shift μ\mu and inflate σ\sigma the default for linear models, SVMs, PCA and neural networks
MinMaxScaler x′=x−min⁡max⁡−min⁡x' = \dfrac{x - \min}{\max - \min} the range 0 to 1 on training data one extreme value squeezes all others you need a bounded range (pixel values, some neural networks)
RobustScaler x′=x−medianQ3−Q1x' = \dfrac{x - \text{median}}{Q_3 - Q_1} median 0, interquartile range 1 barely affected the column has outliers or a heavy tail

StandardScaler divides by the population standard deviation (ddof=0). pandas .std() uses the sample standard deviation (ddof=1), so the two differ slightly on small data. No scaler clips by default: a test value outside the training range gets a value below 0 or above 1 from MinMaxScaler (pass clip=True to cap it).

Model family Needs scaling? Why
KNN, k-means, SVM, PCA yes distances and variances depend on units
Linear and logistic regression with a penalty (Ridge, Lasso, scikit-learn’s LogisticRegression) yes the penalty must treat all coefficients equally
Plain least squares (LinearRegression) no for predictions, yes for comparing coefficients predictions are the same; coefficients change with units
Neural networks yes gradient descent converges faster
Decision trees, random forests, gradient boosting no splits use thresholds, not distances

A categorical feature holds labels from a fixed set, such as region or plan. Most models need numbers, so you encode the labels. Two kinds of categories need different encodings:

  • A nominal feature has no order: region (East, North, South, West) or payment_method.
  • An ordinal feature has a natural order: contract (month-to-month < one-year < two-year) or plan (basic < standard < premium).

One-hot encoding makes one 0/1 column per category. Each row has a 1 in the column of its category and 0 elsewhere. Each new column is a dummy variable:

contract contract_month-to-month contract_one-year contract_two-year
month-to-month 1 0 0
two-year 0 0 1
one-year 0 1 0

One-hot encoding adds no false order, so it is the safe default for nominal features. OneHotEncoder has four settings that you use often:

  • sparse_output=False returns a dense array. The default is a sparse matrix, a format that stores only the non-zero values. It saves memory when a column has thousands of categories.
  • handle_unknown="ignore" encodes a category that fit never saw as all zeros, instead of raising an error. New categories appear in production all the time.
  • drop="first" drops one column per feature. The dropped columns are redundant: in the table above, the three columns always sum to 1. An unregularized linear model with an intercept then has no unique solution. This problem is the dummy variable trap. Regularized models and trees do not need drop.
  • min_frequency= and max_categories= merge rare categories into one “infrequent” column.

pd.get_dummies also one-hot encodes, but it does not remember the categories. If the test set lacks a category, or has a new one, its columns do not match the training columns. Use get_dummies for exploration and OneHotEncoder for models.

Ordinal encoding replaces each category with an integer code: month-to-month → 0, one-year → 1, two-year → 2. It keeps one column and keeps the order. OrdinalEncoder sorts the categories alphabetically unless you pass categories=. For plan, alphabetical order is basic, premium, standard, which is wrong. Always pass the order explicitly. A linear model also reads equal steps into the codes (one-year is “halfway” between month-to-month and two-year). Trees only use the order, so ordinal codes suit trees well.

Target encoding replaces each category with the mean of the target in that category. For churn, electronic_check becomes about 0.246, its churn rate. One column replaces many, so target encoding suits features with high cardinality, which means many distinct categories (postcodes, product ids, store ids). A rare category has an unreliable mean, so the encoding smooths it: it mixes the category mean yˉc\bar{y}_c (from ncn_c rows) with the global mean yˉ\bar{y}:

encoding(c)=nc yˉc+m yˉnc+m\text{encoding}(c) = \frac{n_c\,\bar{y}_c + m\,\bar{y}}{n_c + m}

The smoothing strength mm acts like mm extra rows at the global mean. A category with 2 rows moves strongly toward yˉ\bar{y}. A category with 1,000 rows keeps almost its own mean.

Naive target encoding leaks. The mean of a category includes the target of the row that you encode. With 5 customers per postcode, one churner moves the postcode mean by 0.2. The encoded column then contains part of the answer. The model learns to trust it on the training set and fails on new data. The fix is cross-fitting: split the training rows into kk folds and encode each fold with means computed from the other k−1k-1 folds. No row ever sees its own target. scikit-learn’s TargetEncoder does this inside fit_transform. Its transform method, used on the test set, uses means from all training rows. So fit(X, y).transform(X) differs from fit_transform(X, y) on purpose: use fit_transform on the training set.

Encoder Columns per feature Order Best for
OneHotEncoder one per category none nominal features with few categories, linear models
OrdinalEncoder(categories=[...]) one explicit ordinal features; any categories for tree models
TargetEncoder one (one per class for multiclass) learned from the target high-cardinality features

Binning (also called discretization) turns a numeric feature into intervals, or bins. Age 34 becomes the band “30–39”. A linear model gives one coefficient to a numeric feature, so it can only fit a straight line. With one-hot encoded bins, it fits a separate level per bin. This captures a step or a U-shape, such as house prices that are highest for new builds, fall with age and rise again for the oldest character houses.

Binning has a cost. It throws away the differences inside a bin, and the bin edges are arbitrary. Use it when the effect really changes in steps, or when people need bands (age groups in a report). Tree models find their own thresholds, so they gain little from binning.

Tool Edges come from Use when
pd.cut(x, bins=[...]) you, as fixed numbers the edges have a meaning (eras, age groups)
pd.qcut(x, q=4) the quantiles of x you want bins with equal counts
KBinsDiscretizer(n_bins, strategy=...) fit on the training data the bins are part of a model; strategy is "uniform", "quantile" or "kmeans"

pd.cut and pd.qcut compute edges from the data you pass them. If you call pd.qcut on the full table, the test rows help to choose the edges. In a model, fit KBinsDiscretizer on the training set, or compute the edges on the training set and pass them to pd.cut.

A linear model adds up one effect per feature. It cannot bend a line or let one feature change the effect of another, unless you give it the columns to do so:

  • A polynomial feature is a power of a feature, such as x2x^2. It lets the model fit a curve.
  • An interaction feature is a product of two features, such as x1x2x_1 x_2. It lets the effect of one feature depend on another.

With an interaction, the model is y^=b0+b1x1+b2x2+b3x1x2\hat{y} = b_0 + b_1 x_1 + b_2 x_2 + b_3 x_1 x_2. The effect of one more unit of x1x_1 is b1+b3x2b_1 + b_3 x_2: it changes with x2x_2. For houses, the price gain from one more square foot is larger in Lakeview than in Cedar Park. A product of sqft and a Lakeview dummy gives the model a separate slope for Lakeview.

PolynomialFeatures(degree=2) creates all powers and products up to degree 2. With interaction_only=True it creates only the products. include_bias=False drops the constant column of ones, because the model has its own intercept. The number of columns grows fast. For nn input features and degree dd, it creates (n+dd)−1\binom{n+d}{d} - 1 columns (without the bias): 65 for 10 features at degree 2 and 285 at degree 3. Scale the features after the expansion, and use a regularized model when the count gets large.

Tree models and gradient boosting find interactions by themselves: a split on neighborhood followed by a split on sqft is an interaction. Hand-made interactions help linear models most.

A date string such as "2024-11-29" means nothing to a model. You extract numbers from it:

  • Components: year, month, day of the month, day of the week, hour. In pandas: s.dt.year, s.dt.month, s.dt.day_of_week (Monday = 0). pandas 3 deprecates the older spelling dt.dayofweek.
  • Flags: is_weekend, is_holiday, is_month_end.
  • Elapsed time: days since signup or since the last order. Measure it from a fixed snapshot date, the date when the data was extracted (2024-12-31 for customers.csv). Never use “today”, because the feature then changes every time you rerun the code.
  • Cyclical encoding: month 12 and month 1 are neighbors, but the numbers 12 and 1 are far apart. Map a cyclical value onto a circle with a sine and a cosine. For a month mm from 1 to 12:
month_sin=sin⁡ ⁣(2π (m−1)12),month_cos=cos⁡ ⁣(2π (m−1)12)\text{month\_sin} = \sin\!\left(\frac{2\pi\,(m - 1)}{12}\right), \qquad \text{month\_cos} = \cos\!\left(\frac{2\pi\,(m - 1)}{12}\right)

Each month becomes a point on a circle, and December sits next to January. You need both columns: the sine alone gives the same value to two different months. The same idea works for the hour of the day (period 24), the day of the week (period 7) and wind direction (period 360°). Two sin/cos columns describe one smooth wave per period. A pattern with a sharp spike, such as a December sales peak, needs more waves or a one-hot encoded month.

Prices, incomes and counts are often right-skewed: most values are small and a long tail of large values stretches to the right. House prices in houses.csv run from 117,500 to 3,730,500 with a median of 376,000. A log transform replaces xx with log⁡(x)\log(x). It compresses the tail, so a few expensive houses no longer dominate the fit.

A log also changes what an error means. A linear model on log⁡(price)\log(\text{price}) makes errors in percent: an error of 0.1 in log price is about 10% of the price, for a cheap house and for an expensive one. House prices behave this way. A model on the raw price treats a 50,000 error the same for a 150,000 house and a 2,000,000 house.

  • Use np.log(x) for positive values and np.log1p(x), which computes log⁡(1+x)\log(1 + x), when the column contains zeros.
  • If you model the log of the target, transform the predictions back with np.exp (or np.expm1 after log1p) before you report them in dollars. Module 35 shows TransformedTargetRegressor, which does both steps for you.
  • A log is a monotone transform: it keeps the order of the values. So it does not change a tree’s splits on that feature.

Feature selection keeps a subset of the features. Fewer features mean less overfitting, faster training, cheaper data collection and a model that is easier to explain. There are three families:

Family How it works scikit-learn Strength Weakness
Filter scores each feature by a statistic, without a model VarianceThreshold, correlation, mutual_info_regression, SelectKBest fast, model-free judges one feature at a time; misses features that only help together
Wrapper fits a model on many subsets and keeps the best RFE, SequentialFeatureSelector measures real model performance slow; can overfit the selection
Embedded the model selects while it trains Lasso, tree feature_importances_, SelectFromModel one fit; uses the model’s view tied to one model type

The filter tools:

  • VarianceThreshold(threshold) drops features whose variance is below the threshold. A 0/1 flag with share pp of ones has variance p(1−p)p(1-p), so a flag that is 1 for 0.2% of rows has variance 0.002. Variance depends on units, so use it on flags or on scaled data.
  • Correlation with the target ranks features by their linear relation to the target. Correlation between features finds redundant pairs. Two features that are strongly correlated with each other are multicollinear: a linear model cannot tell their effects apart, and its coefficients become unstable.
  • Mutual information measures how much knowing a feature reduces the uncertainty about the target. It is 0 for independent variables and grows with dependence, linear or not. mutual_info_regression and mutual_info_classif estimate it from the data, with some noise.

The wrapper tools:

  • Recursive feature elimination (RFE) fits the model, drops the feature with the smallest coefficient or importance, and repeats until n_features_to_select remain.
  • Sequential feature selection (SequentialFeatureSelector) starts from no features. At each step it adds the feature that improves the cross-validated score most (direction="forward"), or it starts from all features and removes them (direction="backward"). It fits many models, so keep cv small (3 to 5).

The embedded tools:

  • Lasso is linear regression with an L1 penalty, the sum of the absolute coefficients. It minimizes 12n∥y−Xw∥22+α∥w∥1\frac{1}{2n}\lVert y - Xw \rVert_2^2 + \alpha \lVert w \rVert_1. The L1 penalty pushes weak coefficients to exactly 0, so the features that keep a non-zero coefficient are the selected ones. A larger α\alpha selects fewer features. Scale the features first.
  • Impurity-based feature importance (feature_importances_ of a tree model) sums how much each feature’s splits reduce the error. It is quick, but it favors continuous and high-cardinality features, and it spreads credit between correlated features. Module 43 teaches permutation importance, a more reliable measure.

Feature selection learns from the target, so it is part of training. Run it on the training set only.

Data leakage happens when information that the model will not have at prediction time gets into training or evaluation. The model then scores well in testing and badly in production. Leakage comes in two forms:

  • Target leakage: a feature contains the answer. It is computed from the target (price_per_sqft when you predict price), or it is recorded after the outcome (a “retention call logged” flag that the support team sets after a customer asks to cancel).
  • Train–test contamination: the test rows influence training. A scaler, encoder, binner or selector is fitted on all rows before the split. Duplicate rows land on both sides of the split. A time series is split at random, so the model trains on the future.

Leakage is easy to cause and hard to see, because everything looks better. Use these rules:

  1. Split first. Fit every learned step on the training rows only.
  2. For each feature, ask: “Would I know this value at the moment I make the prediction?”
  3. Distrust a score that is far better than the baseline or than published results. Find the feature that carries it.
  4. For time data, train on the past and test on the future.
  5. Choose between options (scalers, encodings, feature sets) with cross-validation or a validation split: a part of the training rows that you hold back to compare options. Use the test set once, at the end.

Cross-validation gives a more stable score than a single split. It splits the training data into kk parts called folds, trains on k−1k-1 folds, scores on the remaining fold, and repeats so that each fold is scored once. The kk scores are averaged. Cross-validation has a trap: if you transform the data once before it, every fold’s validation rows have already influenced the transform.

A pipeline solves this. A scikit-learn Pipeline chains transformers and a final model into one estimator. When cross-validation fits the pipeline on a training fold, it fits every step on that fold only. Module 34 teaches pipelines in depth; this module uses make_pipeline only where it prevents leakage.

flowchart TD
    D["All rows"] --> S["Split"]
    S --> TR["Training rows"]
    S --> TE["Test rows"]
    TR --> F["fit scaler, encoder,<br/>selector, model"]
    F --> P["Fitted steps"]
    TE --> A["transform + predict"]
    P --> A
    A --> SC["Honest test score"]

Example 1 — Scale churn features for a k-nearest neighbors model

Section titled “Example 1 — Scale churn features for a k-nearest neighbors model”

Goal: A retention team wants a churn score from seven numeric columns of data/customers.csv. KNN predicts from the most similar customers, so it compares customers by distance. Measure how much scaling changes its score, and check that a tree does not care.

from sklearn.model_selection import train_test_split
customers = pd.read_csv("data/customers.csv").dropna(subset=["total_charges"])
num_cols = [
"age", "tenure_months", "monthly_charges", "total_charges",
"support_tickets", "logins_last_30d", "has_autopay",
]
X = customers[num_cols]
y = customers["churned"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=42
)
print(X_train.shape, X_test.shape)
print(X_train.agg(["min", "max", "std"]).round(1).T)
Output
(3742, 7) (1248, 7)
min max std
age 18.0 80.0 12.9
tenure_months 1.0 72.0 19.9
monthly_charges 28.0 143.2 23.0
total_charges 30.0 8322.6 1364.0
support_tickets 0.0 8.0 1.2
logins_last_30d 0.0 60.0 8.0
has_autopay 0.0 1.0 0.5

The 10 brand-new customers with a blank total_charges are dropped. stratify=y keeps the churn rate equal in both parts. The spreads differ a lot: total_charges has a standard deviation in the thousands, has_autopay below 1.

Step 2 — See which feature controls the distance

Section titled “Step 2 — See which feature controls the distance”
first, second = X_train.iloc[0], X_train.iloc[1]
squared_gap = (first - second) ** 2
print((100 * squared_gap / squared_gap.sum()).round(2)) # percent of the distance
Output
age 0.80
tenure_months 0.06
monthly_charges 0.01
total_charges 98.87
support_tickets 0.01
logins_last_30d 0.25
has_autopay 0.00
dtype: float64

The squared Euclidean distance between two customers is the sum of the squared gaps per feature. Here total_charges provides almost 99% of it. KNN therefore finds neighbors by total charges alone and ignores tenure, tickets and logins.

Step 3 — Score KNN on the raw features with cross-validation

Section titled “Step 3 — Score KNN on the raw features with cross-validation”
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
folds = StratifiedKFold(5, shuffle=True, random_state=42)
def cv_auc(model):
"""5-fold CV ROC-AUC on the training rows only; the test set stays unused."""
scores = cross_val_score(model, X_train, y_train, cv=folds, scoring="roc_auc")
return f"{scores.mean():.3f} (folds {scores.min():.3f} to {scores.max():.3f})"
print("KNN, raw features:", cv_auc(KNeighborsClassifier(n_neighbors=25)))
Output
KNN, raw features: 0.726 (folds 0.712 to 0.733)

ROC-AUC scores how well a model ranks positive cases (churners) above negative cases. 0.5 is a random ranking and 1.0 is a perfect one. It suits imbalanced targets such as churn (19% positives). Module 36 explains it in full.

The comparison runs on the training rows only, with cross-validation (see Data leakage): cross_val_score trains on 4 folds, scores the fifth and repeats. The test set is kept for one final score in Step 6. If you chose the scaler by its test score, the test set would take part in the choice.

Step 4 — Compare the three scalers inside pipelines

Section titled “Step 4 — Compare the three scalers inside pipelines”
from sklearn.preprocessing import MinMaxScaler, RobustScaler
for scaler in [StandardScaler(), MinMaxScaler(), RobustScaler()]:
model = make_pipeline(scaler, KNeighborsClassifier(n_neighbors=25))
print(f"{type(scaler).__name__:<15}", cv_auc(model))
Output
StandardScaler 0.768 (folds 0.741 to 0.808)
MinMaxScaler 0.773 (folds 0.755 to 0.801)
RobustScaler 0.775 (folds 0.750 to 0.810)

make_pipeline(scaler, model) chains the two steps into one estimator. In each fold, cross_val_score fits the scaler on the 4 training folds only, so the scored fold never influences the scaling. All three scalers beat the raw features clearly, because every feature now gets a fair say in the distance. The differences between the scalers are smaller than the swing between folds, so they perform about the same here.

Step 5 — Check that a tree ignores scaling

Section titled “Step 5 — Check that a tree ignores scaling”
from sklearn.tree import DecisionTreeClassifier
tree = DecisionTreeClassifier(max_depth=5, random_state=42)
print("tree, raw: ", cv_auc(tree))
print("tree, scaled:", cv_auc(make_pipeline(StandardScaler(), tree)))
Output
tree, raw: 0.755 (folds 0.733 to 0.778)
tree, scaled: 0.755 (folds 0.733 to 0.778)

The two scores are identical. A tree compares one feature with a threshold at a time, and rescaling moves the threshold with the data.

Step 6 — Score the chosen model once on the test set

Section titled “Step 6 — Score the chosen model once on the test set”
final = make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=25))
final.fit(X_train, y_train) # the scaler learns from all training rows
test_auc = roc_auc_score(y_test, final.predict_proba(X_test)[:, 1])
print(f"KNN + StandardScaler, test ROC-AUC: {test_auc:.3f}")
Output
KNN + StandardScaler, test ROC-AUC: 0.765

The scalers tie, so the choice is StandardScaler, the usual default. The pipeline is refitted on all training rows and scored once on the test set. predict_proba(...)[:, 1] is the predicted probability of churn. The test score is close to the cross-validated one, as it should be when nothing leaks.

Common mistakes:

  • Calling fit_transform on the test set. The test set then gets its own mean and spread, and the same customer gets different values in the two sets. Use transform on the test set.
  • Scaling a 0/1 flag and then reading the scaled value as a probability. Scaled values are only positions on a common scale.
  • Scaling for a tree model and expecting a gain. It costs time and changes nothing.

Example 2 — Encode plan, contract and payment method for a churn model

Section titled “Example 2 — Encode plan, contract and payment method for a churn model”

Goal: customers.csv has four text columns. Encode them for a logistic regression so that unknown categories cannot crash the model and the ordinal columns keep their order.

cat_cols = ["region", "plan", "contract", "payment_method"]
train_df, test_df = train_test_split(
customers, test_size=0.25, stratify=customers["churned"], random_state=42
)
print(train_df[cat_cols].nunique())
print(train_df.groupby("plan")["churned"].mean().round(3))
print(train_df.groupby("contract")["churned"].mean().round(3))
Output
region 4
plan 3
contract 3
payment_method 4
dtype: int64
plan
basic 0.178
premium 0.291
standard 0.159
Name: churned, dtype: float64
contract
month-to-month 0.299
one-year 0.087
two-year 0.035
Name: churned, dtype: float64

Every column has 3 or 4 categories. contract has a clear order, and churn falls as the contract gets longer. plan has an order too (basic < standard < premium), but churn does not follow it: premium churns most.

Step 2 — One-hot encode the nominal columns

Section titled “Step 2 — One-hot encode the nominal columns”
from sklearn.preprocessing import OneHotEncoder
onehot = OneHotEncoder(sparse_output=False, handle_unknown="ignore")
onehot.set_output(transform="pandas")
region_pay = onehot.fit_transform(train_df[["region", "payment_method"]])
print(region_pay.shape)
print(*onehot.get_feature_names_out(), sep="\n")
print(region_pay.iloc[:3, :4])
Output
(3742, 8)
region_East
region_North
region_South
region_West
payment_method_bank_transfer
payment_method_credit_card
payment_method_electronic_check
payment_method_paypal
region_East region_North region_South region_West
2466 0.0 1.0 0.0 0.0
3373 0.0 0.0 0.0 1.0
1546 1.0 0.0 0.0 0.0

Two columns became 8 dummy columns, named feature_category. Each row has exactly one 1 per original column. get_feature_names_out() gives the names in output order, which you need to read a coefficient later.

Step 3 — Handle a category the encoder has never seen

Section titled “Step 3 — Handle a category the encoder has never seen”
new_customer = pd.DataFrame({"region": ["Central"], "payment_method": ["paypal"]})
print(onehot.transform(new_customer).iloc[:, [0, 1, 2, 3, 7]])
Output
region_East region_North region_South region_West payment_method_paypal
0 0.0 0.0 0.0 0.0 1.0

Central was not in the training data, so all four region columns are 0. The paypal column is still 1. Without handle_unknown="ignore", the encoder refuses the row:

strict = OneHotEncoder(sparse_output=False).fit(train_df[["region"]])
strict.transform(pd.DataFrame({"region": ["Central"]}))
Output
ValueError: Found unknown categories ['Central'] in column 0 during transform

A model in production meets new categories: a new region, a new payment method, a typo. handle_unknown="ignore" turns them into “none of the known categories” instead of a crash.

Step 4 — Ordinal-encode the ordered columns with an explicit order

Section titled “Step 4 — Ordinal-encode the ordered columns with an explicit order”
from sklearn.preprocessing import OrdinalEncoder
alphabetical = OrdinalEncoder().fit(train_df[["plan"]])
print("default order:", list(alphabetical.categories_[0]))
ordinal = OrdinalEncoder(
categories=[["month-to-month", "one-year", "two-year"],
["basic", "standard", "premium"]]
).set_output(transform="pandas")
codes = ordinal.fit_transform(train_df[["contract", "plan"]])
side_by_side = pd.concat(
[train_df[["contract", "plan"]], codes.add_suffix("_code")], axis=1
)
print(side_by_side.head(4))
Output
default order: ['basic', 'premium', 'standard']
contract plan contract_code plan_code
2466 month-to-month basic 0.0 0.0
3373 one-year basic 1.0 0.0
1546 two-year standard 2.0 1.0
1866 two-year premium 2.0 2.0

The default order is alphabetical, so premium would get code 1 and standard code 2. The explicit categories= list fixes the order: one list per column, in the column order of the input.

Step 5 — Measure what the encoded categories add

Section titled “Step 5 — Measure what the encoded categories add”
from sklearn.linear_model import LogisticRegression
# A validation split of the training rows: compare options here, not on the test set.
fit_df, val_df = train_test_split(
train_df, test_size=0.25, stratify=train_df["churned"], random_state=42
)
base_cols = ["tenure_months", "monthly_charges", "support_tickets",
"logins_last_30d", "has_autopay", "age"]
num_scaler = StandardScaler().set_output(transform="pandas").fit(fit_df[base_cols])
onehot_all = OneHotEncoder(sparse_output=False, handle_unknown="ignore")
onehot_all.set_output(transform="pandas").fit(fit_df[cat_cols])
def churn_auc(fit_parts, val_parts):
model = LogisticRegression(max_iter=1000)
model.fit(pd.concat(fit_parts, axis=1), fit_df["churned"])
proba = model.predict_proba(pd.concat(val_parts, axis=1))[:, 1]
return roc_auc_score(val_df["churned"], proba)
num_fit = num_scaler.transform(fit_df[base_cols])
num_val = num_scaler.transform(val_df[base_cols])
cat_fit = onehot_all.transform(fit_df[cat_cols])
cat_val = onehot_all.transform(val_df[cat_cols])
print(f"numeric only: {churn_auc([num_fit], [num_val]):.3f}")
print(f"+ one-hot (4 cols): {churn_auc([num_fit, cat_fit], [num_val, cat_val]):.3f}")
Output
numeric only: 0.775
+ one-hot (4 cols): 0.795

fit_df and val_df form a validation split of the training rows, so the test set stays untouched for a final score. The four encoded columns raise the validation ROC-AUC clearly: the data dictionary shows large churn differences by contract and payment method. The numeric columns are scaled because LogisticRegression is regularized by default.

Common mistakes:

  • Encoding a nominal column with integer codes for a linear model. The model then believes that West (code 3) is “three times” North (code 1).
  • Trusting the default order of OrdinalEncoder. It is alphabetical. Pass categories=.
  • Using pd.get_dummies separately on the training and the test set. A category missing from one set shifts or removes columns, and the model reads the wrong values.

Example 3 — Target-encode a high-cardinality column without leaking

Section titled “Example 3 — Target-encode a high-cardinality column without leaking”

Goal: A marketing analyst suggests the customer’s postcode as a churn feature. One-hot encoding would add about 1,000 columns, so target encoding looks attractive. customers.csv has no postcode, so this example adds one at random. You know the truth in advance: the postcode carries no information about churn. Any gain is an illusion.

rng = np.random.default_rng(42)
customers["postcode"] = [f"Z{n:04d}" for n in rng.integers(0, 1000, len(customers))]
train_df, test_df = train_test_split(
customers, test_size=0.25, stratify=customers["churned"], random_state=42
)
per_code = train_df.groupby("postcode").size()
print("postcodes:", customers["postcode"].nunique())
print("training rows per postcode:", int(per_code.median()), "median,",
per_code.max(), "max")
Output
postcodes: 988
training rows per postcode: 4 median, 11 max

About 1,000 postcodes share 3,742 training rows, so a typical postcode has only 4 customers. That is high cardinality with tiny groups, the situation where target encoding is most tempting and most dangerous.

Step 2 — Encode naively with the training means

Section titled “Step 2 — Encode naively with the training means”
y_tr, y_te = train_df["churned"], test_df["churned"]
code_means = train_df.groupby("postcode")["churned"].mean()
naive_tr = train_df["postcode"].map(code_means)
naive_te = test_df["postcode"].map(code_means).fillna(y_tr.mean())
print(f"corr with churn, train: {np.corrcoef(naive_tr, y_tr)[0, 1]:.3f}")
print(f"corr with churn, test: {np.corrcoef(naive_te, y_te)[0, 1]:.3f}")
Output
corr with churn, train: 0.527
corr with churn, test: -0.055

The means come from the training rows only, so this is not train–test contamination. It still leaks. On the training rows, each encoding contains the row’s own target: a postcode with one churner out of 4 customers gets 0.25. The correlation with churn is strong on the training set and near zero on the test set.

Step 3 — Fit a model with the naive encoding

Section titled “Step 3 — Fit a model with the naive encoding”
te_cols = ["tenure_months", "monthly_charges", "support_tickets",
"logins_last_30d", "has_autopay"]
def train_test_auc(X_tr, X_te):
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
model.fit(X_tr, y_tr)
return (roc_auc_score(y_tr, model.predict_proba(X_tr)[:, 1]),
roc_auc_score(y_te, model.predict_proba(X_te)[:, 1]))
base = train_test_auc(train_df[te_cols], test_df[te_cols])
naive = train_test_auc(train_df[te_cols].assign(postcode_te=naive_tr),
test_df[te_cols].assign(postcode_te=naive_te))
print(f"without postcode: train {base[0]:.3f} test {base[1]:.3f}")
print(f"naive encoding: train {naive[0]:.3f} test {naive[1]:.3f}")
Output
without postcode: train 0.788 test 0.785
naive encoding: train 0.901 test 0.665

make_pipeline(StandardScaler(), LogisticRegression(...)) chains a scaler and a model into one estimator. Its fit fits the scaler on the training rows, then the model on the scaled rows. With the naive encoding, the training score jumps and the test score falls far below the model without the postcode. The model learned to trust a column that is pure noise on new data.

Step 4 — Use TargetEncoder with cross-fitting

Section titled “Step 4 — Use TargetEncoder with cross-fitting”
from sklearn.model_selection import StratifiedKFold
from sklearn.preprocessing import TargetEncoder
encoder = TargetEncoder(cv=StratifiedKFold(5, shuffle=True, random_state=42))
cross_fit_tr = encoder.fit_transform(train_df[["postcode"]], y_tr)[:, 0]
cross_fit_te = encoder.transform(test_df[["postcode"]])[:, 0]
safe = train_test_auc(train_df[te_cols].assign(postcode_te=cross_fit_tr),
test_df[te_cols].assign(postcode_te=cross_fit_te))
print(f"corr with churn, train: {np.corrcoef(cross_fit_tr, y_tr)[0, 1]:.3f}")
print(f"TargetEncoder: train {safe[0]:.3f} test {safe[1]:.3f}")
Output
corr with churn, train: 0.026
TargetEncoder: train 0.789 test 0.783

fit_transform encodes each training fold with means from the other four folds, then smooths them. The encoded column now shows its true value on the training set too: no relation to churn. The model ignores it, and the scores match the model without the postcode. Pass the fold splitter through cv=, with random_state=42 for reproducible folds. scikit-learn 1.9 deprecates the older shuffle= and random_state= arguments of TargetEncoder.

Step 5 — Look at the smoothing on a real category

Section titled “Step 5 — Look at the smoothing on a real category”
pay_encoder = TargetEncoder(cv=StratifiedKFold(5, shuffle=True, random_state=42))
pay_encoder.fit(train_df[["payment_method"]], y_tr)
summary = train_df.groupby("payment_method")["churned"].agg(["size", "mean"])
summary["encoding"] = pay_encoder.encodings_[0]
print(summary.round(4))
print("global churn rate:", round(pay_encoder.target_mean_, 4))
Output
size mean encoding
payment_method
bank_transfer 916 0.182 0.182
credit_card 1014 0.157 0.157
electronic_check 1154 0.246 0.246
paypal 658 0.170 0.170
global churn rate: 0.1929

payment_method has about 650 to 1,200 rows per category, so smoothing barely moves the means toward the global rate. Electronic checks really do churn more. encodings_ holds the values that transform uses, in the order of categories_ (alphabetical).

Common mistakes:

  • Encoding with groupby(...).mean() on the training set and calling it safe. It still leaks the row’s own target. Use cross-fitting.
  • Calling encoder.fit(X_train, y).transform(X_train) instead of fit_transform. Only fit_transform cross-fits.
  • Computing the category means on all rows, including the test set. That adds train–test contamination on top of target leakage.

Example 4 — Log-transform house prices and bin house age

Section titled “Example 4 — Log-transform house prices and bin house age”

Goal: A real-estate team predicts sale prices from data/houses.csv with a linear model. The price seems to have a long right tail, and the effect of age may be U-shaped. Check both on the training rows, then fix them with a log transform and age bins.

houses = pd.read_csv("data/houses.csv")
print(houses["price"].describe().astype(int))
print(f"skew of price: {houses['price'].skew():.2f}")
print(f"skew of log(price): {np.log(houses['price']).skew():.2f}")
Output
count 3000
mean 476465
std 318750
min 117500
25% 278500
50% 376000
75% 560375
max 3730500
Name: price, dtype: int64
skew of price: 2.67
skew of log(price): 0.70

The mean is far above the median, and the skewness is 2.67: a long right tail. After the log, the skewness drops to 0.70, much closer to a symmetric shape.

Step 2 — Fit a linear model on the price and on the log price

Section titled “Step 2 — Fit a linear model on the price and on the log price”
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, r2_score
houses["sale_year"] = pd.to_datetime(houses["sold_date"]).dt.year
houses["age"] = houses["sale_year"] - houses["year_built"]
h_train, h_test = train_test_split(houses, test_size=0.25, random_state=42)
# Compare options on a validation split of the training rows; keep h_test for the end.
h_fit, h_val = train_test_split(h_train, test_size=0.25, random_state=42)
h_cols = ["sqft", "bedrooms", "bathrooms", "garage_spaces", "has_pool",
"condition", "distance_to_center_km", "sale_year", "age"]
nb_encoder = OneHotEncoder(sparse_output=False).set_output(transform="pandas")
nb_fit = nb_encoder.fit_transform(h_fit[["neighborhood"]])
nb_val = nb_encoder.transform(h_val[["neighborhood"]])
base_fit = pd.concat([h_fit[h_cols], nb_fit], axis=1)
base_val = pd.concat([h_val[h_cols], nb_val], axis=1)
on_price = LinearRegression().fit(base_fit, h_fit["price"])
on_log = LinearRegression().fit(base_fit, np.log(h_fit["price"]))
pred_price = on_price.predict(base_val)
pred_from_log = np.exp(on_log.predict(base_val)) # back to dollars
for name, pred in [("price", pred_price), ("log(price)", pred_from_log)]:
print(f"target {name:<10} R2 {r2_score(h_val['price'], pred):.3f} "
f"MAE {mean_absolute_error(h_val['price'], pred):,.0f}")
print("negative price predictions:", (pred_price < 0).sum())
Output
target price R2 0.812 MAE 94,920
target log(price) R2 0.911 MAE 62,112
negative price predictions: 1

age is the age at sale, a better feature than the raw year_built. Both models use the same features. The log target cuts the mean absolute error by about a third, and it never predicts a negative price. The raw-price model even predicts a negative price for one house, because a straight line in dollars cannot fit growth in percent. The 8 neighborhood dummies always sum to 1, which is the dummy variable trap. LinearRegression still returns one valid least-squares solution, so the predictions are correct. Only the individual dummy coefficients are not unique; use drop="first" when you want to read them.

age_bands = pd.cut(h_fit["age"], bins=[0, 5, 20, 40, 60, 80, 120], right=False)
print(h_fit.groupby(age_bands, observed=True)["price"].agg(["size", "median"]))
Output
size median
age
[0, 5) 119 494500.0
[5, 20) 429 439500.0
[20, 40) 604 362500.0
[40, 60) 295 351000.0
[60, 80) 139 332500.0
[80, 120) 101 353000.0

pd.cut with fixed edges makes six bands, and right=False makes each band include its left edge: [0, 5) means 0 to 4 years. The median price falls with age and then rises again for the oldest houses. One straight line in age cannot fit this U-shape.

Step 4 — Bin age with KBinsDiscretizer and refit

Section titled “Step 4 — Bin age with KBinsDiscretizer and refit”
from sklearn.preprocessing import KBinsDiscretizer
binner = KBinsDiscretizer(n_bins=6, encode="onehot-dense", strategy="quantile")
binner.set_output(transform="pandas")
age_bins_fit = binner.fit_transform(h_fit[["age"]]) # edges from the fitting rows
age_bins_val = binner.transform(h_val[["age"]])
print("edges:", binner.bin_edges_[0])
y_fit_log, y_val_log = np.log(h_fit["price"]), np.log(h_val["price"])
for name, extra_fit, extra_val in [
("age as a number", [], []),
("+ age bins", [age_bins_fit], [age_bins_val]),
]:
Xa = pd.concat([base_fit, *extra_fit], axis=1)
Xb = pd.concat([base_val, *extra_val], axis=1)
model = LinearRegression().fit(Xa, y_fit_log)
val_r2 = r2_score(y_val_log, model.predict(Xb))
print(f"{name:<16} validation R2 on log(price) {val_r2:.4f}")
Output
edges: [ 1. 11. 20. 29. 38. 56. 118.]
age as a number validation R2 on log(price) 0.9020
+ age bins validation R2 on log(price) 0.9062

strategy="quantile" puts about the same number of training houses in each bin. encode="onehot-dense" returns one 0/1 column per bin. The model keeps age as a number and adds one level per bin, so it can now follow the U-shape. The validation R² on the log price rises a little.

Common mistakes:

  • Reporting the R² or the error on the log scale as if it were in dollars. Transform the predictions back with np.exp before you compare them with prices.
  • Using np.log on a column that contains 0. It returns -inf. Use np.log1p.
  • Computing bin edges with pd.qcut on the full table before the split. The test rows then shape the edges.

Example 5 — Add interaction and polynomial features for house prices

Section titled “Example 5 — Add interaction and polynomial features for house prices”

Goal: An agent claims that extra space is worth more in expensive neighborhoods. Check the claim on the training rows, give the linear model a separate slope per neighborhood with interaction features, add polynomial terms, and score the chosen features once on the test set.

Step 1 — Measure the slope of log price on log sqft per neighborhood

Section titled “Step 1 — Measure the slope of log price on log sqft per neighborhood”
slopes = {
name: np.polyfit(np.log(group["sqft"]), np.log(group["price"]), deg=1)[0]
for name, group in h_fit.groupby("neighborhood")
}
print(pd.Series(slopes).sort_values().round(2))
Output
Cedar Park 0.45
Downtown 0.50
Westfield 0.54
Old Town 0.56
Maple Grove 0.84
Riverside 1.00
Oak Hill 1.18
Lakeview 1.34
dtype: float64

np.polyfit(..., deg=1) fits a straight line and returns the slope first. On a log–log scale, the slope is an elasticity: the percent change in price for a 1% change in size. In Cedar Park, 1% more space adds about 0.45% to the price. In Lakeview, it adds more than 1%. The claim holds: the areas with the highest median prices in the data dictionary (Lakeview, Oak Hill) have the steepest slopes. One shared sqft coefficient averages these very different slopes.

Step 2 — Build log sqft × neighborhood columns by hand

Section titled “Step 2 — Build log sqft × neighborhood columns by hand”
def size_by_area(nb_dummies, sqft):
"""One column per neighborhood: log(sqft) inside it, 0 elsewhere."""
product = nb_dummies.mul(np.log(sqft), axis=0)
return product.rename(columns=lambda c: c.replace("neighborhood_", "size_x_"))
inter_fit = size_by_area(nb_fit, h_fit["sqft"])
inter_val = size_by_area(nb_val, h_val["sqft"])
print(inter_fit.head(3).round(2).T) # one column per house
Output
2385 1164 616
size_x_Cedar Park 0.00 0.00 0.00
size_x_Downtown 0.00 0.00 0.00
size_x_Lakeview 0.00 0.00 0.00
size_x_Maple Grove 0.00 0.00 0.00
size_x_Oak Hill 7.44 7.72 0.00
size_x_Old Town 0.00 0.00 0.00
size_x_Riverside 0.00 0.00 0.00
size_x_Westfield 0.00 0.00 7.61

The table is transposed: each column is one house. Each house has one non-zero interaction value, the log size of the house in its own neighborhood. mul(..., axis=0) multiplies each dummy column by the log size of the same row.

def log_r2(fit_parts, val_parts):
model = LinearRegression().fit(pd.concat(fit_parts, axis=1), y_fit_log)
return r2_score(y_val_log, model.predict(pd.concat(val_parts, axis=1)))
print(f"baseline: {log_r2([base_fit], [base_val]):.4f}")
print(f"+ size x area: "
f"{log_r2([base_fit, inter_fit], [base_val, inter_val]):.4f}")
Output
baseline: 0.9020
+ size x area: 0.9209

The interaction columns give each neighborhood its own size slope, and the validation R² on the log price rises by about 2 points.

Step 4 — Add polynomial terms with PolynomialFeatures

Section titled “Step 4 — Add polynomial terms with PolynomialFeatures”
from sklearn.preprocessing import PolynomialFeatures
poly = PolynomialFeatures(degree=2, include_bias=False).set_output(transform="pandas")
two_cols = pd.DataFrame({"log_sqft": np.log(h_fit["sqft"]), "age": h_fit["age"]})
poly_fit = poly.fit_transform(two_cols)
poly_val = poly.transform(
pd.DataFrame({"log_sqft": np.log(h_val["sqft"]), "age": h_val["age"]})
)
print(list(poly.get_feature_names_out()))
all_fit = [base_fit, inter_fit, poly_fit.add_prefix("poly_")]
all_val = [base_val, inter_val, poly_val.add_prefix("poly_")]
print(f"+ size x area + poly: {log_r2(all_fit, all_val):.4f}")
Output
['log_sqft', 'age', 'log_sqft^2', 'log_sqft age', 'age^2']
+ size x area + poly: 0.9281

Degree 2 on two columns creates the two originals, their squares and their product. age^2 lets the model bend the age effect into a U-shape, like the age bins of Example 4. The poly_ prefix keeps the names unique, because age is also a baseline column. scikit-learn refuses a DataFrame with duplicate column names. The copy of age is redundant: a plain linear model copes with it, and a regularized model would share the weight between the two copies.

eight = h_fit[["sqft", "bedrooms", "bathrooms", "garage_spaces", "has_pool",
"condition", "distance_to_center_km", "age"]]
for degree in [2, 3, 4]:
expanded = PolynomialFeatures(degree=degree, include_bias=False).fit(eight)
print(f"degree {degree}: {expanded.n_output_features_} columns")
Output
degree 2: 44 columns
degree 3: 164 columns
degree 4: 494 columns

8 columns become 44 at degree 2 and 494 at degree 4. With under 2,000 rows to fit on, a model with hundreds of columns overfits. Prefer a few interactions that you can justify, like size × area, over a blind expansion.

Step 6 — Refit the chosen features and score the test set once

Section titled “Step 6 — Refit the chosen features and score the test set once”
def chosen_features(fit_df, apply_df):
"""Baseline + size x area + polynomial terms, learned on fit_df only."""
encoder = OneHotEncoder(sparse_output=False, handle_unknown="ignore")
encoder.set_output(transform="pandas").fit(fit_df[["neighborhood"]])
nb_part = encoder.transform(apply_df[["neighborhood"]])
two = pd.DataFrame({"log_sqft": np.log(apply_df["sqft"]), "age": apply_df["age"]})
poly_part = PolynomialFeatures(degree=2, include_bias=False).fit_transform(two)
poly_part = pd.DataFrame(poly_part, index=apply_df.index).add_prefix("poly_")
return pd.concat([apply_df[h_cols], nb_part,
size_by_area(nb_part, apply_df["sqft"]), poly_part], axis=1)
X_final = chosen_features(h_train, h_train)
final = LinearRegression().fit(X_final, np.log(h_train["price"]))
test_pred = np.exp(final.predict(chosen_features(h_train, h_test))) # dollars
print(f"test R2 {r2_score(h_test['price'], test_pred):.3f} "
f"MAE {mean_absolute_error(h_test['price'], test_pred):,.0f}")
Output
test R2 0.933 MAE 55,331

The validation split chose the feature set. Now the model is refitted on all 2,250 training houses and scored once on the 750 test houses, in dollars. For comparison, the raw-price baseline of Example 4 had a mean absolute error of about 95,000 on the validation rows. The log target, the interactions and the polynomial terms bring the typical error down to about 55,000.

Common mistakes:

  • Multiplying raw sqft by a dummy and forgetting the dummy’s own column. Keep the main effects (the dummies) next to the interactions, so each neighborhood has its own intercept and its own slope.
  • Expanding to degree 3 or more on many features. Check n_output_features_ first.
  • Expanding unscaled features and then fitting a regularized model. Scale after the expansion.

Example 6 — Build calendar features for daily sales

Section titled “Example 6 — Build calendar features for daily sales”

Goal: A planner forecasts the units sold per day from data/sales.csv. Build day-of-week, weekend, month and trend features from the order date, compare month encodings, and add an elapsed-time feature to the churn data.

Step 1 — Aggregate the order lines to daily units

Section titled “Step 1 — Aggregate the order lines to daily units”
sales = pd.read_csv("data/sales.csv", parse_dates=["order_date"])
daily = sales.groupby("order_date", as_index=False)["quantity"].sum()
daily = daily.rename(columns={"quantity": "units"})
print(daily.dtypes)
print(len(daily), "days;", daily["units"].min(), "to", daily["units"].max(), "units")
Output
order_date datetime64[us]
units int64
dtype: object
731 days; 5 to 242 units

parse_dates= reads the column as datetime64, so the .dt accessor works. The table has one row per day of 2023 and 2024.

Step 2 — Extract calendar components and a trend

Section titled “Step 2 — Extract calendar components and a trend”
daily["day_of_week"] = daily["order_date"].dt.day_of_week # Monday = 0
daily["is_weekend"] = (daily["day_of_week"] >= 5).astype(int)
daily["month"] = daily["order_date"].dt.month
daily["days_since_start"] = (daily["order_date"] - daily["order_date"].min()).dt.days
print(daily.head(3))
print(daily.groupby("day_of_week")["units"].mean().round(1).to_dict())
Output
order_date units day_of_week is_weekend month days_since_start
0 2023-01-01 31 6 1 1 0
1 2023-01-02 19 0 0 1 1
2 2023-01-03 26 1 0 1 2
{0: 34.9, 1: 33.4, 2: 35.0, 3: 35.7, 4: 45.3, 5: 52.9, 6: 45.7}

Subtracting two dates gives a timedelta, and .dt.days turns it into a whole number of days. days_since_start lets a linear model learn the growth trend. Saturday (5) is the peak day and Tuesday (1) the low day.

angle = 2 * np.pi * (daily["month"] - 1) / 12
daily["month_sin"] = np.sin(angle)
daily["month_cos"] = np.cos(angle)
points = daily.drop_duplicates("month").set_index("month")[["month_sin", "month_cos"]]
def gap(a, b):
return np.linalg.norm(points.loc[a] - points.loc[b])
print(f"Dec-Jan: raw gap {12 - 1}, circle gap {gap(12, 1):.3f}")
print(f"Jan-Feb: raw gap {2 - 1}, circle gap {gap(1, 2):.3f}")
print(f"Jan-Jul: raw gap {7 - 1}, circle gap {gap(1, 7):.3f}")
Output
Dec-Jan: raw gap 11, circle gap 0.518
Jan-Feb: raw gap 1, circle gap 0.518
Jan-Jul: raw gap 6, circle gap 2.000

On the circle, December and January are as close as January and February. July, half a year away, is at the largest distance (2, the diameter of the unit circle). The raw month numbers put December farthest from January.

Step 4 — Compare month encodings on a later validation period

Section titled “Step 4 — Compare month encodings on a later validation period”
date = daily["order_date"]
is_fit = date < "2024-01-01" # 2023: fit the candidates
is_val = (date >= "2024-01-01") & (date < "2024-07-01") # H1 2024: compare them
is_test = date >= "2024-07-01" # H2 2024: score the chosen one once
log_units = np.log(daily["units"])
dow = pd.get_dummies(daily["day_of_week"], prefix="dow", drop_first=True, dtype=float)
month_dummies = pd.get_dummies(daily["month"], prefix="m", drop_first=True, dtype=float)
trend = daily[["days_since_start"]]
options = {
"trend + day of week": [trend, dow],
"+ month as a number": [trend, dow, daily[["month"]]],
"+ month sin/cos": [trend, dow, daily[["month_sin", "month_cos"]]],
"+ month one-hot": [trend, dow, month_dummies],
}
def period_mae(parts, train_mask, score_mask):
X_days = pd.concat(parts, axis=1)
model = LinearRegression().fit(X_days[train_mask], log_units[train_mask])
pred = np.exp(model.predict(X_days[score_mask]))
return mean_absolute_error(daily.loc[score_mask, "units"], pred)
val_mae = {name: period_mae(parts, is_fit, is_val) for name, parts in options.items()}
for name, mae in val_mae.items():
print(f"{name:<21} validation MAE {mae:5.2f} units/day")
best = min(val_mae, key=val_mae.get)
test_mae = period_mae(options[best], is_fit | is_val, is_test)
print(f"chosen: {best!r}, test MAE {test_mae:.2f} units/day")
Output
trend + day of week validation MAE 21.09 units/day
+ month as a number validation MAE 22.92 units/day
+ month sin/cos validation MAE 33.48 units/day
+ month one-hot validation MAE 23.28 units/day
chosen: 'trend + day of week', test MAE 17.10 units/day

The split is by date, in three periods: fit on 2023, compare on the first half of 2024, then refit the winner on all 18 months and score the last 6 months once. A random split would let the model see days on both sides of each scored day. get_dummies runs once on the whole table. It learns only the list of categories, and every weekday and month occurs in the 2023 fitting period, so this shortcut is safe here.

The result is a useful surprise: every month encoding makes the validation forecast worse, and the simplest model wins. With only one year to fit on, each calendar month occurs in only one year, so a month column cannot be told apart from the growth trend. The sin/cos pair is worst: its two parameters fit one smooth wave to 2023, and that wave does not carry over. Seasonal features need at least two full cycles of history. Sin/cos encoding shines for smooth cycles with plenty of history, such as the hour of the day in a year of hourly data. Module 40 validates forecasts over several rolling periods.

Step 5 — Compute days since signup from a snapshot date

Section titled “Step 5 — Compute days since signup from a snapshot date”
snapshot = pd.Timestamp("2024-12-31") # the extraction date of customers.csv
signup = pd.to_datetime(customers["signup_date"])
customers["days_since_signup"] = (snapshot - signup).dt.days
customers["signup_month"] = signup.dt.month
print(customers[["signup_date", "days_since_signup", "tenure_months"]].head(3))
print(f"corr with tenure_months: "
f"{customers['days_since_signup'].corr(customers['tenure_months']):.4f}")
Output
signup_date days_since_signup tenure_months
0 2018-12-01 2222 72
1 2018-12-01 2222 72
2 2018-12-01 2222 72
corr with tenure_months: 0.9999

The snapshot date is fixed, so the feature gives the same values on every run. The correlation with tenure_months is almost 1: the dataset already contains this information. A new feature must add something that the model does not already have. Feature selection in the next example finds such redundant pairs.

Common mistakes:

  • Feeding a date as a string or as a raw timestamp in nanoseconds. Extract components and elapsed times.
  • Computing “days since” from pd.Timestamp.today(). The feature changes every day and the model’s inputs drift.
  • Using only month_sin without month_cos. Months 2 and 6 (February and June) then get the same value.

Example 7 — Select features for a house price model

Section titled “Example 7 — Select features for a house price model”

Goal: A house price model has 23 candidate features: the house columns, two engineered flags, the neighborhood dummies and three columns of pure random noise. Compare filter, wrapper and embedded selection, and check which methods drop the noise.

import textwrap
cand = houses.copy()
cand["is_new_build"] = (cand["age"] <= 2).astype(int)
cand["huge_house"] = (cand["sqft"] >= 5000).astype(int)
for i in (1, 2, 3):
cand[f"noise_{i}"] = rng.normal(size=len(cand)) # no relation to price
nb = pd.get_dummies(cand["neighborhood"], prefix="nb", drop_first=True, dtype=int)
dropped = ["house_id", "neighborhood", "sold_date", "price", "year_built"]
X_cand = pd.concat([cand.drop(columns=dropped), nb], axis=1)
Xc_train, Xc_test, yc_train, yc_test = train_test_split(
X_cand, np.log(cand["price"]), test_size=0.25, random_state=42
)
medians = Xc_train.median() # impute lot_sqft and school_rating with training medians
Xc_train, Xc_test = Xc_train.fillna(medians), Xc_test.fillna(medians)
import textwrap
print(Xc_train.shape)
print(textwrap.fill(", ".join(Xc_train.columns), width=88))
Output
(2250, 23)
sqft, bedrooms, bathrooms, lot_sqft, garage_spaces, has_pool, condition,
distance_to_center_km, school_rating, sale_year, age, is_new_build, huge_house, noise_1,
noise_2, noise_3, nb_Downtown, nb_Lakeview, nb_Maple Grove, nb_Oak Hill, nb_Old Town,
nb_Riverside, nb_Westfield

rng continues the generator from Example 3, so the noise is reproducible. The noise columns are a test: a good selector should drop them. The medians come from the training rows only.

Two columns are left out on purpose, because they make the linear coefficients non-unique. year_built is exactly sale_year - age, and the 8 neighborhood dummies sum to 1 next to the intercept (the dummy variable trap). With exact duplicates, least squares can split the weight between twins in any way, so a ranking by coefficient size (RFE, Lasso) would be arbitrary. drop_first=True drops Cedar Park, which becomes the reference area. get_dummies is acceptable here because it learns only the category list, and all 8 areas occur in the training rows.

Step 2 — Filter: drop near-constant features

Section titled “Step 2 — Filter: drop near-constant features”
from sklearn.feature_selection import VarianceThreshold
flags = Xc_train[["huge_house", "is_new_build", "has_pool"]]
print("huge houses in training:", flags["huge_house"].sum())
print(flags.var().round(4).to_dict())
low_var = VarianceThreshold(threshold=0.01).fit(flags)
print("kept:", list(flags.columns[low_var.get_support()]))
Output
huge houses in training: 6
{'huge_house': 0.0027, 'is_new_build': 0.0388, 'has_pool': 0.0971}
kept: ['is_new_build', 'has_pool']

Only 6 training houses have 5,000 sqft or more, so huge_house is almost always 0. Its variance is about 0.003, below the threshold. get_support() returns a Boolean mask of the kept columns. The threshold is applied to flags only, because the variance of sqft (in the hundreds of thousands) says nothing about its usefulness.

Step 3 — Filter: rank by correlation and mutual information

Section titled “Step 3 — Filter: rank by correlation and mutual information”
from sklearn.feature_selection import mutual_info_regression
corr = Xc_train.corrwith(yc_train)
is_binary = Xc_train.nunique().eq(2).to_numpy() # flags and dummies are discrete
mi = pd.Series(mutual_info_regression(Xc_train, yc_train, random_state=42,
discrete_features=is_binary),
index=Xc_train.columns)
ranks = pd.DataFrame({"corr": corr, "mutual_info": mi})
print(ranks.sort_values("mutual_info", ascending=False).round(3).head(8))
print(ranks.loc[["sale_year", "noise_1", "noise_2", "noise_3"]].round(3))
pairs = Xc_train.corr().abs().where(np.triu(np.ones((23, 23), dtype=bool), k=1))
print(pairs.stack().sort_values(ascending=False).head(3).round(3))
Output
corr mutual_info
sqft 0.721 0.391
distance_to_center_km -0.239 0.343
school_rating 0.651 0.300
bathrooms 0.638 0.249
bedrooms 0.626 0.239
nb_Oak Hill 0.444 0.105
nb_Westfield -0.349 0.103
lot_sqft -0.137 0.089
corr mutual_info
sale_year 0.062 0.000
noise_1 -0.010 0.000
noise_2 -0.001 0.014
noise_3 -0.003 0.000
bedrooms bathrooms 0.896
sqft bedrooms 0.855
bathrooms 0.850
dtype: float64

Size, distance and school rating lead both rankings. discrete_features=is_binary tells the estimator which columns are 0/1; treating flags and dummies as continuous gives poor estimates. The filters have two blind spots. First, sale_year scores near zero, yet the sequential selector in Step 4 keeps it: its effect is small next to the spread between houses and only shows once size and area are accounted for. Second, the estimates are noisy: noise_2 gets a mutual information of 0.014, above sale_year, so a fixed cut-off can keep noise and drop signal. The pair check finds bedrooms, bathrooms and sqft, which largely measure the same thing: size.

Step 4 — Wrapper: RFE and sequential selection

Section titled “Step 4 — Wrapper: RFE and sequential selection”
from sklearn.feature_selection import RFE, SequentialFeatureSelector
std = StandardScaler().set_output(transform="pandas").fit(Xc_train)
Zc_train, Zc_test = std.transform(Xc_train), std.transform(Xc_test)
rfe = RFE(LinearRegression(), n_features_to_select=10).fit(Zc_train, yc_train)
rfe_cols = list(Zc_train.columns[rfe.support_])
print(textwrap.fill("RFE: " + ", ".join(rfe_cols), width=88))
sfs = SequentialFeatureSelector(
LinearRegression(), n_features_to_select=10, direction="forward", cv=3
).fit(Zc_train, yc_train)
sfs_cols = list(Zc_train.columns[sfs.get_support()])
print(textwrap.fill("SFS: " + ", ".join(sfs_cols), width=88))
Output
RFE: sqft, condition, school_rating, age, nb_Downtown, nb_Lakeview, nb_Maple Grove,
nb_Oak Hill, nb_Old Town, nb_Riverside
SFS: sqft, garage_spaces, condition, distance_to_center_km, school_rating, sale_year,
is_new_build, nb_Lakeview, nb_Oak Hill, nb_Westfield

RFE ranks by the size of the coefficients, so the features are standardized first. The sequential selector adds, step by step, the feature that most improves the 3-fold cross-validated R². Neither picks a noise column, and both drop bedrooms and bathrooms, which mostly repeat sqft. SFS keeps sale_year, which the filters ranked near zero. RFE spends 6 of its 10 slots on neighborhood dummies: it ranks by coefficient size, not by the gain in a cross-validated score.

Step 5 — Embedded: Lasso coefficients and tree importances

Section titled “Step 5 — Embedded: Lasso coefficients and tree importances”
from sklearn.ensemble import RandomForestRegressor
from sklearn.linear_model import Lasso
lasso = Lasso(alpha=0.01).fit(Zc_train, yc_train)
coefs = pd.Series(lasso.coef_, index=Zc_train.columns)
lasso_cols = list(coefs.index[coefs != 0])
zeroed = ", ".join(coefs.index[coefs == 0])
print(textwrap.fill(f"Lasso keeps {len(lasso_cols)}; zero for: {zeroed}", width=88))
forest = RandomForestRegressor(n_estimators=100, random_state=42, n_jobs=-1)
forest.fit(Xc_train, yc_train)
importance = pd.Series(forest.feature_importances_, index=Xc_train.columns)
print(importance.sort_values(ascending=False).round(3).head(3))
rank = importance.rank(ascending=False).astype(int)
watch = ["noise_1", "noise_2", "noise_3", "bathrooms", "bedrooms"]
print("rank of 23:", rank[watch].to_dict())
Output
Lasso keeps 14; zero for: bedrooms, lot_sqft, huge_house, noise_1, noise_2, noise_3,
nb_Downtown, nb_Maple Grove, nb_Old Town
sqft 0.475
school_rating 0.179
distance_to_center_km 0.164
dtype: float64
rank of 23: {'noise_1': 11, 'noise_2': 8, 'noise_3': 10, 'bathrooms': 12, 'bedrooms': 15}

The L1 penalty sets 9 coefficients to exactly zero: all three noise columns, huge_house, bedrooms, lot_sqft and three neighborhood dummies. The forest’s impurity importances tell a weaker story: the noise columns rank above real features such as bathrooms. Random continuous values give a tree many split points to overfit, and impurity importance rewards that.

Step 6 — Compare the selection methods with cross-validation

Section titled “Step 6 — Compare the selection methods with cross-validation”
from sklearn.feature_selection import SelectFromModel
from sklearn.model_selection import KFold
kfold = KFold(5, shuffle=True, random_state=42)
methods = {
"all 23": [],
"RFE 10": [RFE(LinearRegression(), n_features_to_select=10)],
"SFS 10": [SequentialFeatureSelector(LinearRegression(),
n_features_to_select=10, cv=3)],
"Lasso": [SelectFromModel(Lasso(alpha=0.01))],
}
cv_means = {}
for name, selector in methods.items():
pipe = make_pipeline(StandardScaler(), *selector, LinearRegression())
scores = cross_val_score(pipe, Xc_train, yc_train, cv=kfold, scoring="r2")
cv_means[name] = scores.mean()
print(f"{name:<7} CV R2 {scores.mean():.4f} (folds {scores.min():.3f} to "
f"{scores.max():.3f})")
Output
all 23 CV R2 0.8988 (folds 0.885 to 0.915)
RFE 10 CV R2 0.8838 (folds 0.865 to 0.899)
SFS 10 CV R2 0.8844 (folds 0.870 to 0.901)
Lasso CV R2 0.8916 (folds 0.878 to 0.907)

Steps 4 and 5 ran each selector on all training rows to see what it picks. To compare the methods fairly, the selection itself must happen inside cross-validation: each pipeline scales, selects and fits on 4 folds, then scores the fifth. SelectFromModel(Lasso(...)) keeps the features with a non-zero Lasso coefficient and passes them to a plain linear regression.

All 23 features give the best CV R². RFE and SFS lose about 1.5 points with 10 features; Lasso loses under 1 point with 14. With 1,800 rows per training fold and 23 features, the full linear model does not overfit much, so selection buys simplicity, not accuracy. On wide data (many features, few rows), selection matters much more, as exercise M33-X03 shows. Suppose the team wants the smallest model within 1 point of the best CV score: that is the Lasso pipeline.

Step 7 — Score the chosen pipeline once on the test set

Section titled “Step 7 — Score the chosen pipeline once on the test set”
chosen = make_pipeline(StandardScaler(), SelectFromModel(Lasso(alpha=0.01)),
LinearRegression())
chosen.fit(Xc_train, yc_train)
kept = chosen[1].get_support().sum()
test_r2 = r2_score(yc_test, chosen.predict(Xc_test))
print(f"Lasso selection: {kept} features, test R2 on log(price) {test_r2:.4f}")
Output
Lasso selection: 14 features, test R2 on log(price) 0.8988

The chosen pipeline is refitted on all 2,250 training rows and scored once on the test set. The test R² is close to the CV estimate, so the choice did not depend on luck in one split.

Common mistakes:

  • Running a selector on all rows, then evaluating on a test set that took part in the selection. Example 8 shows how much this inflates the score.
  • Reading a high tree importance as proof that a feature matters. Check it against a noise column or with permutation importance (module 43).
  • Using VarianceThreshold on unscaled continuous columns. Variance depends on units.

Example 8 — Catch data leakage before it fools you

Section titled “Example 8 — Catch data leakage before it fools you”

Goal: Measure three kinds of leakage: a feature selector fitted before cross-validation, a scaler fitted before the split, and a post-outcome column. Each one makes a model look better than it is.

Step 1 — Select features on all rows, then cross-validate

Section titled “Step 1 — Select features on all rows, then cross-validate”
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.model_selection import cross_val_score
noise_rng = np.random.default_rng(42)
X_noise = noise_rng.normal(size=(300, 2000)) # 300 rows, 2,000 random features
y_coin = noise_rng.permutation(np.repeat([0, 1], 150)) # labels: coin flips
folds = StratifiedKFold(5, shuffle=True, random_state=42)
X_top = SelectKBest(f_classif, k=20).fit_transform(X_noise, y_coin) # sees all rows
leaky = cross_val_score(LogisticRegression(), X_top, y_coin, cv=folds)
print(f"selected before CV: accuracy {leaky.mean():.3f}")
Output
selected before CV: accuracy 0.747

The labels are random, so no model can beat 50% accuracy on new data. Yet cross-validation reports far more. SelectKBest picked the 20 features (of 2,000) that best match the labels of all 300 rows, including every validation fold. By chance, some random features line up with the labels, and the selector found them.

Step 2 — Put the selector inside a pipeline

Section titled “Step 2 — Put the selector inside a pipeline”
pipe = make_pipeline(SelectKBest(f_classif, k=20), LogisticRegression())
honest = cross_val_score(pipe, X_noise, y_coin, cv=folds)
print(f"selected inside CV: accuracy {honest.mean():.3f}")
print("fold scores:", honest.round(2))
Output
selected inside CV: accuracy 0.467
fold scores: [0.52 0.37 0.45 0.52 0.48]

cross_val_score now refits the whole pipeline on each training fold. The selector never sees the validation fold, and the score falls to about chance. With only 60 rows per fold, the fold scores swing around 0.5.

Step 3 — Fit the scaler on all rows before the split

Section titled “Step 3 — Fit the scaler on all rows before the split”
X_all_scaled = StandardScaler().fit_transform(X) # X from Example 1: all customers
Xa_tr, Xa_te, ya_tr, ya_te = train_test_split(
X_all_scaled, y, test_size=0.25, stratify=y, random_state=42
)
knn = KNeighborsClassifier(n_neighbors=25).fit(Xa_tr, ya_tr)
leaky_auc = roc_auc_score(ya_te, knn.predict_proba(Xa_te)[:, 1])
safe_scaler = StandardScaler().fit(X_train)
knn = KNeighborsClassifier(n_neighbors=25).fit(safe_scaler.transform(X_train), y_train)
safe_auc = roc_auc_score(y_test, knn.predict_proba(safe_scaler.transform(X_test))[:, 1])
print(f"scaler fitted on all rows: {leaky_auc:.4f}")
print(f"scaler fitted on train only: {safe_auc:.4f}")
Output
scaler fitted on all rows: 0.7653
scaler fitted on train only: 0.7647

The difference is tiny here. The 3,742 training rows give almost the same mean and standard deviation as all 4,990 rows. A scaler learns only two numbers per column and never sees the target, so it leaks little. The habit still matters: the same mistake with a selector (Step 1) or a target encoder (Example 3) inflates the score a lot, and with small data even a scaler leaks.

churn = pd.read_csv("data/customers.csv")
leak_rng = np.random.default_rng(42)
# Simulated: the retention team logs a call AFTER a customer asks to cancel.
p_call = np.where(churn["churned"] == 1, 0.85, 0.04)
churn["retention_call"] = (leak_rng.random(len(churn)) < p_call).astype(int)
print(pd.crosstab(churn["retention_call"], churn["churned"]))
Output
churned 0 1
retention_call
0 3886 138
1 151 825

customers.csv has no such column, so this step simulates one. The retention team calls 85% of the customers who ask to cancel, and a few others. The call happens after the cancellation request, so the flag does not exist yet when the model must predict.

Step 5 — See the score jump and find the leak

Section titled “Step 5 — See the score jump and find the leak”
c_train, c_test = train_test_split(
churn, test_size=0.25, stratify=churn["churned"], random_state=42
)
for cols in [te_cols, te_cols + ["retention_call"]]:
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
model.fit(c_train[cols], c_train["churned"])
auc = roc_auc_score(c_test["churned"], model.predict_proba(c_test[cols])[:, 1])
print(f"{len(cols)} features: ROC-AUC {auc:.3f}")
one_feature = roc_auc_score(c_test["churned"], c_test["retention_call"])
print(f"retention_call alone: ROC-AUC {one_feature:.3f}")
print(pd.Series(model[-1].coef_[0], index=cols).round(2))
Output
5 features: ROC-AUC 0.783
6 features: ROC-AUC 0.942
retention_call alone: ROC-AUC 0.899
tenure_months -0.88
monthly_charges 0.53
support_tickets 0.52
logins_last_30d -0.30
has_autopay -0.31
retention_call 2.01
dtype: float64

The score jumps from 0.78 to 0.94. The data dictionary reports about 0.81 for a full churn model, so 0.94 is too good to be true. Two checks expose the leak: one column alone reaches an ROC-AUC of 0.90, and its coefficient is far larger than any other. model[-1] is the last step of the pipeline, the logistic regression. The fix is to drop the column. Then ask the business when each field gets its value.

Common mistakes:

  • Doing any learned preprocessing (selection, encoding, imputation, scaling) before cross_val_score. Put it in a pipeline.
  • Celebrating a big jump in score without asking why. Check single-feature scores and the largest coefficients or importances.
  • Keeping columns whose meaning you do not know. Ask when and how each column is filled.
Mistake Symptom Fix
fit_transform on the test set the same input gets different values in train and test; scores drop or swing fit on train, transform on test
Fitting a scaler, selector or encoder before the split or before CV test or CV score better than in production split first; wrap the steps in a pipeline
Naive target encoding with small categories train score far above test score TargetEncoder with fit_transform (cross-fitting)
OrdinalEncoder() without categories= alphabetical codes such as basic 0, premium 1, standard 2 pass categories=[[...]] in the true order
OneHotEncoder without handle_unknown="ignore" ValueError: Found unknown categories in production set handle_unknown="ignore"
pd.get_dummies on train and test separately column count or order differs; wrong predictions OneHotEncoder fitted on train
Integer codes for a nominal feature in a linear model the model assumes a false order and equal steps one-hot encode nominal features
Unscaled features in KNN, SVM, PCA or a penalized model one large-unit column dominates scale; RobustScaler for heavy tails
np.log on zeros -inf values, then errors in the fit np.log1p
Errors reported on the log scale numbers that look tiny and mean nothing to users back-transform with np.exp
Only month_sin, no month_cos two different months get the same value always add both
“Days since” from today’s date features change on every run measure from a fixed snapshot date
PolynomialFeatures(degree=3) on many columns hundreds of columns, overfitting, slow fits few justified interactions; check n_output_features_
A feature recorded after the outcome a score far above the baseline; one dominant feature ask “would I know this at prediction time?”; drop it
Comparing scalers, encodings or feature sets on the test set the test score is optimistic after many comparisons compare with CV or a validation split; score the test set once
Series.dt.dayofweek in pandas 3 Pandas4Warning deprecation warning Series.dt.day_of_week
  • Web analytics and A/B tools: session features such as hour of day (encoded with sin/cos), day of week and days since the first visit feed bot detection and personalization rules.
  • Search and recommendation systems: a ranking service one-hot encodes the device type, hashes or target-encodes high-cardinality ids, and scales click counts before a linear ranker scores the results.
  • Monitoring and automation: an alerting script compares today’s value with a log-transformed or robust-scaled baseline, so one huge spike does not hide every smaller one.
  • Software engineering: the same “fit on the past, apply to the future” rule protects any system that learns thresholds from data, such as a rate limiter that learns normal traffic levels.
  • Feature engineering transforms, encodes, creates and selects columns so that a model can learn the pattern. It often matters more than the choice of algorithm.
  • Transformers learn with fit and apply with transform. Fit on the training set only. set_output(transform="pandas") keeps the column names.
  • Scale for distance-based, gradient-based and penalized models. StandardScaler is the default, MinMaxScaler gives a bounded range, RobustScaler resists outliers. Trees do not need scaling.
  • One-hot encode nominal features with handle_unknown="ignore". Ordinal-encode ordered features with an explicit categories= order. Target-encode high-cardinality features with TargetEncoder, whose cross-fitting prevents the leak of naive mean encoding.
  • Bins, polynomial terms and interactions let a linear model fit steps, curves and effects that depend on another feature. Watch the column count.
  • Dates become components, flags, elapsed times from a fixed snapshot date and sin/cos pairs for cycles.
  • A log transform tames right-skewed values and turns errors into percentages. Back-transform predictions before you report them.
  • Filter methods are fast but judge one feature at a time. Wrapper methods measure real performance but cost many fits. Embedded methods (Lasso, tree importances) select during training. Impurity importances can rank noise above real features.
  • Data leakage inflates scores. Split first, fit every learned step inside the training data (use a pipeline with cross-validation) and drop any feature you would not have at prediction time.
  • Choose between options with cross-validation or a validation split of the training rows. Score the chosen model on the test set once.

Q1. Why does KNN need scaled features while a decision tree does not?

Answer

KNN compares rows by distance, so a feature with large units (such as total_charges in the thousands) dominates the distance and the other features barely count. A tree compares one feature at a time with a threshold. Rescaling moves the threshold with the data, so the splits and the predictions stay the same.

Q2. A column has a few extreme values. Which scaler do you choose, and why?

Answer

RobustScaler. It subtracts the median and divides by the interquartile range. Both ignore the extreme values. StandardScaler uses the mean and the standard deviation, which the outliers pull. MinMaxScaler maps the extreme value to 1 and squeezes all normal values into a narrow range.

Q3. What does OrdinalEncoder() do with plan (basic, standard, premium) when you pass no categories=, and why is that a problem?

Answer

It sorts the categories alphabetically: basic → 0, premium → 1, standard → 2. The codes no longer follow the real order of the plans, so a model that uses the order learns nonsense. Pass categories=[["basic", "standard", "premium"]].

Q4. Why does naive target encoding leak even when you compute the category means on the training set only?

Answer

Each training row’s encoding includes its own target value. In small categories, the row’s target moves the mean a lot, so the encoded column contains part of the answer on the training set but not on new data. The model learns to trust it and fails on the test set. Cross-fitting (TargetEncoder.fit_transform) encodes each fold with means from the other folds, so no row sees its own target.

Q5. How many columns does PolynomialFeatures(degree=2, include_bias=False) create from 3 features? Name them for the features a, b, c.

Answer

9: a, b, c, a^2, a b, a c, b^2, b c, c^2. The formula (3+22)−1=10−1=9\binom{3+2}{2} - 1 = 10 - 1 = 9 gives the same count.

Q6. Why do you need both month_sin and month_cos?

Answer

The sine alone gives the same value to two different months (for example February and June, which are symmetric around April on the sine curve). The pair of sine and cosine gives each month a unique point on a circle, so December sits next to January and no two months collide.

Q7. You model log(price). A colleague reports a mean absolute error of 0.09. What should you report instead?

Answer

The error in dollars. Transform the predictions back with np.exp and compute the MAE against the real prices. An error of 0.09 on the log scale means about 9% of the price, which is meaningful only when you say so. Users expect dollars.

Q8. Name one strength and one weakness each of filter, wrapper and embedded feature selection.

Answer

Filter: fast and model-free, but it judges each feature alone and can miss features that only help together (like sale_year in Example 7). Wrapper: measures real model performance, but it needs many fits and can overfit the selection. Embedded: selects during one training run (Lasso zeros, tree importances), but it is tied to one model type, and impurity importances can rank noise above real features.

Q9. A churn model reaches an ROC-AUC of 0.99 on the test set. Published models on similar data reach 0.82. What do you check first?

Answer

Target leakage. Score each feature alone and look at the largest coefficients or importances. A feature that predicts churn almost perfectly by itself is suspect. Ask when its value is recorded. A flag set after the customer cancels (a retention call, a final invoice, an exit survey) is not available at prediction time and must go.

Q10. Why does SelectKBest before cross_val_score inflate the score, and how does a pipeline fix it?

Answer

The selector picks features using the labels of all rows, including the rows that each fold later uses for validation. The chosen features therefore fit the validation labels by construction. In a pipeline, cross_val_score refits the selector on each training fold, so the validation fold stays unseen, and the score becomes honest.

Your progress

0 / 4 done

  • Exercises: 28 exercises on scaling, encoding, binning, interactions, dates, selection and leakage, with hints and full solutions.
  • Mini-project: engineer a leakage-safe feature set for house prices and measure every gain.
  • Cheat sheet: every transformer, encoder and selector of this module on one page.
  • Next module: 34. The scikit-learn workflow teaches the estimator API, Pipeline, ColumnTransformer, custom transformers and cross-validation in depth.