Skip to content

Lesson 6 of 9 · 27m

Feature Engineering: Signals, Shortcuts, and Leakage

Design features that encode real causal or operational signal while recognizing target leakage, frozen context, and unavailable-at-inference traps.

Feature engineering is where machine learning becomes domain work. Algorithms interpolate; features decide what there is to interpolate. The practitioner's question is not "what columns can I create?" It is "what information exists at decision time, what behavior does it encode, and what shortcuts will the model exploit if I let it?"

Start from the decision moment

Write down the exact inference moment. For churn prediction, is it nightly batch scoring, signup completion, or immediately before a retention email? A feature is valid only if its value exists then:

decision time: 2026-11-30 00:00 UTC
valid: events before 2026-11-30 00:00
invalid: subscription cancellation event on 2026-11-30 09:15
suspicious: support ticket resolved_at

If you cannot state the decision moment, you cannot audit leakage.

Good features compress behavior

Counts, recency, frequency, ratios, and trends often beat raw event dumps:

df['events_7d'] = df['events_1d'] + df['events_2to7d']
df['days_since_last_login'] = (decision_ts - df['last_login_at']).dt.total_seconds() / 86400
df['events_per_active_day'] = df['events_7d'] / df['active_days_7d'].clip(lower=1)

The exact transformations should reflect the product. A user with one huge day is not the same as a user with consistent usage. Ratios need denominator guards; division by zero is not a feature.

Leakage wears respectable clothes

Classic leakage examples look boring:

target: converted
leaky feature: conversion_email_opened
leaky feature: invoice_paid
leaky feature: account_closed_reason
leaky feature: final_status

The model is not smart; it is reading the answer key. Worse, leakage can enter through aggregate tables. A "user summary" generated after the full month may include post-decision events even if individual column names look innocent.

Crosses and interactions are controlled complexity

Feature crosses can expose nonlinear structure to linear models:

df['plan_x_weekend'] = (
    (df['plan_code'] == 'team') & df['signup_is_weekend']
).astype('int8')

Do not enumerate every interaction because you can. Feature count multiplies memory, sparsity, debugging surface, and overfitting risk. Create interactions when you have a product hypothesis or evidence of a segment-specific effect.

Text and categories need humility

Hashing, one-hot encoding, target encoding, embeddings, and TF-IDF each have different leakage and cardinality behavior. Target encoding is especially dangerous outside pipelines because it uses the label. If you use it, it must be fit within cross-validation folds.

from sklearn.feature_extraction.text import TfidfVectorizer

text_features = TfidfVectorizer(
    lowercase=True,
    ngram_range=(1, 2),
    min_df=5,
    max_features=50000,
)

Text preprocessing looks easy until unicode, HTML entities, emails, and multilingual content arrive. Validate tokenizer behavior on real examples, not clean demo strings.

Keep feature definitions reusable

If training computes events_7d in pandas and production computes it in SQL, they are now two implementations of the same concept. Put definitions in shared SQL, a feature store, or versioned transformation code. Otherwise offline metrics measure a feature production does not actually receive.

Field notes

  • High feature importance for a suspicious feature is a leakage alarm, not a victory.
  • IDs rarely generalize as raw numeric features; they encode identity, not magnitude.
  • Time-based aggregates need explicit windows and timezone rules.
  • Categorical frequency shifts after launch; monitor cardinality and unseen values.
  • A feature can be legal, accurate, and still unethical or unacceptable for the product decision. Model governance is not optional.

Was this lesson helpful?

Sign in to rate