Section 4 · Lesson 1

Feature engineering and pipelines

Create features that expose signal, handle missing values and categories, and bundle every step into one leak-proof pipeline.

45 min 2 practice tasks
How do I encode categorical features using scikit-learn? by Data School on YouTube

Better models usually come from better features, not fancier algorithms. Feature engineering means turning raw columns into inputs that make the real pattern easy for a model to see. Domain knowledge is your main tool.

Ideas that work again and again

  • Ratios and rates. pages_viewed_30d mixes two things: how often someone visits and how deeply they browse. Dividing by sessions isolates depth: pages_per_session.
  • Flags for known behaviors. Marketers know that people who added to cart and came back recently are hot leads. A linear model can’t build that “and” by itself, but a 0/1 column can hand it over directly. Our recent_cart visitors convert at about 50%, compared with about 10% for everyone else.
  • Transforms for skewed counts. Sessions run from 1 to 45, with most people at 2–5. np.log1p(x) (log of 1 + x) compresses the long tail so a few heavy users don’t dominate.
  • Distances from a sweet spot. Conversion peaks for visitors around 35–45 and falls off on both sides. A linear model sees age as “older is better” or “older is worse”. The feature abs(age - 40) lets it express “closer to 40 is better”.
  • Dates. Day of week, days since signup and hour of day are often stronger than the raw timestamp.

Always check a new feature against the label (a group-by or a correlation), and keep only features you’ll actually have when the model runs.

Missing values and categories

Six percent of visitors never gave their age, and scikit-learn models refuse NaN. Two standard fixes:

  • SimpleImputer(strategy="median") fills gaps with the training median. Add add_indicator=True if the fact that a value is missing might itself be informative.
  • OneHotEncoder(handle_unknown="ignore") turns device, source and country into 0/1 columns. Unlike pd.get_dummies, it remembers the categories it saw during training. A brand-new category in production becomes all zeros instead of crashing the model.

ColumnTransformer + Pipeline

Different columns need different treatment. ColumnTransformer routes each group to its own steps, and a pipeline chains preprocessing to the model:

from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import OneHotEncoder, StandardScaler

preprocess = ColumnTransformer([
    ("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), num_cols),
    ("cat", OneHotEncoder(handle_unknown="ignore"), cat_cols),
])
model = make_pipeline(preprocess, LogisticRegression(max_iter=1000))
model.fit(X_train, y_train)
model.predict_proba(X_test)

Why this matters:

  • No leakage. The median, the scaling statistics and the category list are learned from X_train only. If you scale the whole dataset before splitting, test rows leak into training.
  • One object to ship. The fitted pipeline takes raw rows, with text categories and missing ages, and returns probabilities. Production code can’t forget a step.
  • It works with cross-validation and tuning, as you’ll see in the next lesson. Each fold refits the preprocessing on its own training part.

What it buys us

Logistic regression with… Test ROC-AUC
8 behavior features 0.800
+ age, device, source, country and 4 engineered features 0.827

The engineered pipeline has 26 input columns once the categories are one-hot encoded. Its gain over the behavior-only model, from 0.800 to 0.827, comes from encoding knowledge about how people buy, not from a more complex algorithm. In the ensembles lesson you’ll see a much more complex model on raw features fail to match it.

Practice

Write your answer, press Run to see results and Check answer to grade it. Shortcuts: Ctrl/⌘ + Enter run, Shift + Enter check.

1

Engineer new features

Add four columns to audience:

  • pages_per_session: pages_viewed_30d / sessions_30d
  • recent_cart: 1 if the visitor added something to their cart (cart_adds_30d > 0) and

visited in the last 3 days (days_since_last_visit <= 3), otherwise 0

  • log_sessions: np.log1p(sessions_30d)
  • age_gap: how far age is from 40, as an absolute value. Missing ages stay missing.

Then create:

  • recent_cart_rate: the conversion rate of visitors with recent_cart == 1, rounded to 4 decimals
  • other_rate: the conversion rate of everyone else, rounded to 4 decimals
Need a hint?
  1. Combine two conditions with & and wrap each in parentheses: (a > 0) & (b <= 3).
  2. audience.groupby("recent_cart")["converted"].mean() gives both rates at once.
Python 3
import numpy as np
import pandas as pd

audience = pd.read_csv("audience.csv")

# TODO: add pages_per_session, recent_cart, log_sessions and age_gap

recent_cart_rate = None
other_rate = None
print(recent_cart_rate, other_rate)
Files in the working directory
audience.csv (5,000 rows)
user_id, age, country, device, source, sessions_30d, pages_viewed_30d, minutes_on_site_30d, cart_adds_30d, days_since_last_visit, past_purchases, email_subscriber, ad_impressions_7d, converted
daily_stats.csv (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
campaigns.csv (40 rows)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
2

One pipeline for everything

The starter adds the engineered features, defines num_cols and cat_cols, splits the data and computes base_auc for the behavior-only logistic model. Build:

preprocess = ColumnTransformer([
    ("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), num_cols),
    ("cat", OneHotEncoder(handle_unknown="ignore"), cat_cols),
])
model = make_pipeline(preprocess, LogisticRegression(max_iter=1000))
  • model: the pipeline, fitted on X_train, y_train
  • pipeline_auc: its test ROC-AUC, rounded to 4 decimals
  • n_model_features: how many columns the logistic regression actually receives after

preprocessing (len(model[-1].coef_[0]))

Need a hint?
  1. ColumnTransformer takes a list of (name, transformer, columns) tuples and glues the outputs side by side.
  2. One-hot encoding turns each categorical column into one column per category, so the model gets more columns than you passed in.
Python 3
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import make_pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score

audience = pd.read_csv("audience.csv")
audience["pages_per_session"] = audience["pages_viewed_30d"] / audience["sessions_30d"]
audience["recent_cart"] = ((audience["cart_adds_30d"] > 0) & (audience["days_since_last_visit"] <= 3)).astype(int)
audience["log_sessions"] = np.log1p(audience["sessions_30d"])
audience["age_gap"] = (audience["age"] - 40).abs()

behavior = ["sessions_30d", "pages_viewed_30d", "minutes_on_site_30d", "cart_adds_30d",
            "days_since_last_visit", "past_purchases", "email_subscriber", "ad_impressions_7d"]
num_cols = behavior + ["age", "pages_per_session", "recent_cart", "log_sessions", "age_gap"]
cat_cols = ["device", "source", "country"]

X_train, X_test, y_train, y_test = train_test_split(
    audience[num_cols + cat_cols], audience["converted"], test_size=0.25, random_state=42,
    stratify=audience["converted"],
)
base = make_pipeline(StandardScaler(), LogisticRegression()).fit(X_train[behavior], y_train)
base_auc = roc_auc_score(y_test, base.predict_proba(X_test[behavior])[:, 1])
print("behavior-only AUC:", round(base_auc, 4))

preprocess = None
model = None
pipeline_auc = None
n_model_features = None
print(pipeline_auc, n_model_features)
Files in the working directory
audience.csv (5,000 rows)
user_id, age, country, device, source, sessions_30d, pages_viewed_30d, minutes_on_site_30d, cart_adds_30d, days_since_last_visit, past_purchases, email_subscriber, ad_impressions_7d, converted
daily_stats.csv (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
campaigns.csv (40 rows)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status