Skip to content

33. Feature engineering — Exercises

These exercises practice every idea of the feature engineering lesson. They use the course datasets: churn customers, house sales, daily sales and web traffic. The data dictionary describes every column.

How to work:

  1. Read the task and the expected output.
  2. Copy the setup block below into the top of a script (for example exercise.py). Then copy the starter code under it and replace each to-do comment with your code.
  3. Run the script with python exercise.py from your project folder, the folder that holds data/. Compare your output with the expected output.
  4. Stuck? Open one hint at a time. Open the solution only after a real attempt.

Each solution ends with assert checks. Add the same checks to your own code: they prove that the numbers are right, not only that they look right.

Every exercise starts with this block. It imports pandas and NumPy, fixes the display and loads four datasets.

import numpy as np
import pandas as pd
pd.set_option("display.width", 100)
pd.set_option("display.max_columns", 12)
pd.set_option("display.precision", 3)
customers = pd.read_csv("data/customers.csv")
houses = pd.read_csv("data/houses.csv")
sales = pd.read_csv("data/sales.csv", parse_dates=["order_date"])
traffic = pd.read_csv("data/web_traffic.csv", parse_dates=["date"])

M33-W01 · Standardize monthly charges by hand

Section titled “M33-W01 · Standardize monthly charges by hand”
Warm-up

Take monthly_charges of the first 5 customers. Compute their z-scores by hand with NumPy, using the mean and the population standard deviation. Then fit a StandardScaler on the same values and check that both give the same result. Print the z-scores rounded to 3 decimals.

Expected output
values: [ 84.69 55.33 108.02 85.25 40.81]
by hand: [ 0.414 -0.817 1.392 0.437 -1.426]
by scaler: [ 0.414 -0.817 1.392 0.437 -1.426]
pandas std (ddof=1): 26.669 numpy std (ddof=0): 23.854
Starter
from sklearn.preprocessing import StandardScaler
charges = customers[["monthly_charges"]].head(5)
values = charges["monthly_charges"].to_numpy()
# TODO: z-scores by hand with values.mean() and values.std()
# TODO: z-scores with StandardScaler().fit_transform(charges)
# TODO: print both and compare them with np.allclose
Hint 1

z=(x−μ)/σz = (x - \mu) / \sigma. NumPy’s values.std() uses ddof=0 (the population standard deviation), like StandardScaler.

Hint 2

fit_transform returns a 2-D array of shape (5, 1). Use .ravel() to make it 1-D before you compare.

Solution
from sklearn.preprocessing import StandardScaler
charges = customers[["monthly_charges"]].head(5)
values = charges["monthly_charges"].to_numpy()
by_hand = (values - values.mean()) / values.std()
by_scaler = StandardScaler().fit_transform(charges).ravel()
print("values: ", values)
print("by hand: ", by_hand.round(3))
print("by scaler:", by_scaler.round(3))
print("pandas std (ddof=1):", round(charges["monthly_charges"].std(), 3),
"numpy std (ddof=0):", round(values.std(), 3))
assert np.allclose(by_hand, by_scaler)
assert abs(by_scaler.mean()) < 1e-12
Output
values: [ 84.69 55.33 108.02 85.25 40.81]
by hand: [ 0.414 -0.817 1.392 0.437 -1.426]
by scaler: [ 0.414 -0.817 1.392 0.437 -1.426]
pandas std (ddof=1): 26.669 numpy std (ddof=0): 23.854

How it works:

  1. values.mean() and values.std() are the two parameters that StandardScaler learns (mean_ and scale_).
  2. Subtracting the mean centers the values at 0. Dividing by the standard deviation gives them a spread of 1.
  3. pandas .std() divides by n−1n - 1 and NumPy’s .std() by nn. With 5 values the difference is visible. A hand-made scaler that uses pandas .std() does not match StandardScaler.

Alternative: scipy.stats.zscore(values) gives the same numbers (it also uses ddof=0).

M33-W02 · Predict the output: MinMaxScaler outside the training range

Section titled “M33-W02 · Predict the output: MinMaxScaler outside the training range”
Warm-up

Predict the output: a MinMaxScaler is fitted on four tenure values. Then it transforms three new values, two of them outside the training range. Write down what each print shows. Then run the code.

Acceptance criteria:

  • Write your prediction for both prints before you run the code.
  • Run the code. Your prediction matches the Output in the solution.
  • Explain why one value is above 1 and one is below 0.
Starter
from sklearn.preprocessing import MinMaxScaler
tenure = pd.DataFrame({"tenure_months": [0, 12, 24, 72]})
scaler = MinMaxScaler().fit(tenure)
print(scaler.data_min_, scaler.data_max_)
new = pd.DataFrame({"tenure_months": [36, 90, -6]})
print(scaler.transform(new).ravel().round(3))
Hint 1

fit learns only the minimum and the maximum: 0 and 72.

Hint 2

The formula is (x−0)/(72−0)(x - 0) / (72 - 0). It does not clip.

Solution
from sklearn.preprocessing import MinMaxScaler
tenure = pd.DataFrame({"tenure_months": [0, 12, 24, 72]})
scaler = MinMaxScaler().fit(tenure)
print(scaler.data_min_, scaler.data_max_)
new = pd.DataFrame({"tenure_months": [36, 90, -6]})
scaled = scaler.transform(new).ravel().round(3)
print(scaled)
assert scaled[1] > 1 and scaled[2] < 0
Output
[0.] [72.]
[ 0.5 1.25 -0.083]

How it works:

  1. fit stores data_min_ = 0 and data_max_ = 72. The other training values do not matter.
  2. 36 is halfway between 0 and 72, so it becomes 0.5.
  3. 90 is above the training maximum, so it becomes 90 / 72 = 1.25. −6 is below the minimum and becomes −0.083. MinMaxScaler guarantees the range 0 to 1 only on the training data.

Alternative: MinMaxScaler(clip=True) caps the output at 0 and 1. Use it when a downstream step really needs the bounds; otherwise the clipping hides that a value was out of range.

Warm-up

One-hot encode the plan column of customers with OneHotEncoder. Return a pandas DataFrame, print its column names and the sum of each column. The sums must equal value_counts() of plan.

Expected output
['plan_basic', 'plan_premium', 'plan_standard']
plan_basic 2028
plan_premium 990
plan_standard 1982
dtype: int64
Starter
from sklearn.preprocessing import OneHotEncoder
encoder = OneHotEncoder(sparse_output=False)
# TODO: make the encoder return pandas
# TODO: fit_transform the plan column (as a one-column DataFrame)
# TODO: print the column names and the column sums
Hint 1

encoder.set_output(transform="pandas") makes transform return a DataFrame.

Hint 2

Pass customers[["plan"]] (double brackets): scikit-learn expects a 2-D input.

Solution
from sklearn.preprocessing import OneHotEncoder
encoder = OneHotEncoder(sparse_output=False).set_output(transform="pandas")
plan_dummies = encoder.fit_transform(customers[["plan"]])
print(list(plan_dummies.columns))
print(plan_dummies.sum().astype(int))
counts = customers["plan"].value_counts()
assert plan_dummies["plan_premium"].sum() == counts["premium"]
assert (plan_dummies.sum(axis=1) == 1).all()
Output
['plan_basic', 'plan_premium', 'plan_standard']
plan_basic 2028
plan_premium 990
plan_standard 1982
dtype: int64

How it works:

  1. sparse_output=False returns a dense array; set_output(transform="pandas") wraps it in a DataFrame with the names from get_feature_names_out().
  2. The categories are sorted, so the columns come in the order basic, premium, standard.
  3. Each row has exactly one 1, so the column sums are the category counts and every row sums to 1.

Alternative: pd.get_dummies(customers["plan"], prefix="plan", dtype=int) gives the same columns for exploration. It does not remember the categories for a later test set.

M33-W04 · Fix the bug: an ordinal encoding in the wrong order

Section titled “M33-W04 · Fix the bug: an ordinal encoding in the wrong order”
Warm-up

Fix the bug: the code below encodes the plan levels basic < standard < premium, but standard gets a higher code than premium. Fix it so the codes are basic 0, standard 1, premium 2.

Expected output
['basic', 'standard', 'premium']
{'basic': 0.0, 'standard': 1.0, 'premium': 2.0}
Starter
from sklearn.preprocessing import OrdinalEncoder
plans = pd.DataFrame({"plan": ["basic", "standard", "premium"]})
encoder = OrdinalEncoder() # TODO: fix the order
codes = encoder.fit_transform(plans).ravel()
print(list(encoder.categories_[0]))
print(dict(zip(plans["plan"], codes)))
Hint 1

Print encoder.categories_ in the buggy version. Which order did OrdinalEncoder choose?

Hint 2

Pass categories= as a list with one inner list per input column.

Solution
from sklearn.preprocessing import OrdinalEncoder
plans = pd.DataFrame({"plan": ["basic", "standard", "premium"]})
encoder = OrdinalEncoder(categories=[["basic", "standard", "premium"]])
codes = encoder.fit_transform(plans).ravel()
print(list(encoder.categories_[0]))
print(dict(zip(plans["plan"], codes.tolist())))
assert codes.tolist() == [0.0, 1.0, 2.0]
Output
['basic', 'standard', 'premium']
{'basic': 0.0, 'standard': 1.0, 'premium': 2.0}

How it works:

  1. Without categories=, OrdinalEncoder sorts the categories alphabetically: basic, premium, standard. Standard then gets code 2.
  2. The explicit list fixes the order. The code of each category is its position in the list.
  3. categories= takes one list per column, so two ordinal columns need [[...], [...]].

Alternative: a pandas ordered categorical: pd.Categorical(plans["plan"], categories=["basic", "standard", "premium"], ordered=True).codes gives the integer codes 0, 1, 2.

Warm-up

Cut age into the bands 18–29, 30–44, 45–59 and 60+ with pd.cut. Use fixed edges, include the left edge of each band and give the bands those labels. Print the number of customers and the churn rate per band.

Expected output
size mean
age
18-29 842 0.279
30-44 1994 0.170
45-59 1703 0.152
60+ 461 0.282
Starter
edges = [18, 30, 45, 60, 81]
labels = ["18-29", "30-44", "45-59", "60+"]
# TODO: age_band = pd.cut(...)
# TODO: group churned by age_band; print the size and the mean
Hint 1

right=False makes each band include its left edge, so 30 goes to “30-44”.

Hint 2

customers.groupby(age_band, observed=True)["churned"].agg(["size", "mean"]).

Solution
edges = [18, 30, 45, 60, 81]
labels = ["18-29", "30-44", "45-59", "60+"]
age_band = pd.cut(customers["age"], bins=edges, labels=labels, right=False)
summary = customers.groupby(age_band, observed=True)["churned"].agg(["size", "mean"])
print(summary)
assert summary["size"].sum() == len(customers)
assert summary["mean"].idxmin() in ("30-44", "45-59")
Output
size mean
age
18-29 842 0.279
30-44 1994 0.170
45-59 1703 0.152
60+ 461 0.282

How it works:

  1. pd.cut assigns each age to the interval it falls in. The last edge is 81, so 80 lands in “60+”.
  2. observed=True keeps only the bands that occur. It is the pandas 3 default; writing it makes the intent clear.
  3. Churn is highest for the youngest and the oldest customers, a U-shape. A linear model with age as one number cannot fit it; the four bands, one-hot encoded, can.

Alternative: pd.qcut(customers["age"], q=4) makes four bands with about equal counts. The edges then come from the data, so compute them on the training rows when the bands feed a model.

Warm-up

From traffic, build day_of_week (Monday = 0) and an is_weekend flag (Saturday or Sunday). Print the mean visits on weekdays and on weekends, rounded to whole visits.

Expected output
is_weekend
0 4577.0
1 3810.0
Name: visits, dtype: float64
weekend days: 314 of 1096
Starter
# TODO: traffic["day_of_week"] = ...
# TODO: traffic["is_weekend"] = ...
# TODO: mean visits per is_weekend value
Hint 1

traffic["date"].dt.day_of_week gives 0 for Monday and 6 for Sunday. pandas 3 deprecates the older dt.dayofweek.

Hint 2

(traffic["day_of_week"] >= 5).astype(int) is 1 on Saturday and Sunday.

Solution
traffic["day_of_week"] = traffic["date"].dt.day_of_week
traffic["is_weekend"] = (traffic["day_of_week"] >= 5).astype(int)
mean_visits = traffic.groupby("is_weekend")["visits"].mean().round()
print(mean_visits)
print("weekend days:", traffic["is_weekend"].sum(), "of", len(traffic))
assert mean_visits[0] > mean_visits[1]
Output
is_weekend
0 4577.0
1 3810.0
Name: visits, dtype: float64
weekend days: 314 of 1096

How it works:

  1. The .dt accessor works because the setup reads date with parse_dates=.
  2. day_of_week >= 5 selects Saturday (5) and Sunday (6). .astype(int) turns the Boolean column into 0/1.
  3. The site gets fewer visits at weekends. mean() skips the 5 blank visits values (tracking outages).

Alternative: traffic["date"].dt.day_name().isin(["Saturday", "Sunday"]) builds the same flag from day names, which reads well in reports.

Warm-up

support_tickets is right-skewed and contains zeros. Transform it with np.log1p. Print the skewness before and after, and check that np.expm1 recovers the original values exactly.

Expected output
zeros: 1537
skew before: 1.045
skew after: 0.028
min and max after: 0.0 2.303
Starter
tickets = customers["support_tickets"]
# TODO: logged = np.log1p(tickets)
# TODO: print the skew of tickets and of logged, rounded to 3 decimals
# TODO: check np.expm1(logged) against tickets
Hint 1

np.log(0) is -inf, so a plain log fails on the zeros. np.log1p(x) computes log⁡(1+x)\log(1 + x), which is 0 for x=0x = 0.

Hint 2

Series.skew() measures the skewness. Use np.allclose to compare floats.

Solution
tickets = customers["support_tickets"]
logged = np.log1p(tickets)
print("zeros:", (tickets == 0).sum())
print(f"skew before: {tickets.skew():.3f}")
print(f"skew after: {logged.skew():.3f}")
print("min and max after:", logged.min(), round(logged.max(), 3))
assert np.allclose(np.expm1(logged), tickets)
assert abs(logged.skew()) < abs(tickets.skew())
Output
zeros: 1537
skew before: 1.045
skew after: 0.028
min and max after: 0.0 2.303

How it works:

  1. 1,537 customers have no ticket, so np.log would give -inf for them. log1p maps 0 to 0.
  2. The transform compresses the tail: 9 tickets become 2.303 instead of standing far out.
  3. np.expm1 is the exact inverse of np.log1p, so you can always go back to the original units.

Alternative: FunctionTransformer(np.log1p, inverse_func=np.expm1) from sklearn.preprocessing wraps the same transform as a transformer, so it can sit in a pipeline.

Warm-up

Build four 0/1 flags from customers: has_autopay, is_premium (plan is premium), many_tickets (6 or more tickets) and age_78_plus (age 78 or more). Use VarianceThreshold(threshold=0.01) to find the flags that are almost constant. Print the variance of each flag and the names of the kept flags.

Expected output
has_autopay 0.249
is_premium 0.159
many_tickets 0.004
age_78_plus 0.004
dtype: float64
kept: ['has_autopay', 'is_premium']
Starter
from sklearn.feature_selection import VarianceThreshold
flags = pd.DataFrame({
"has_autopay": customers["has_autopay"],
# TODO: is_premium, many_tickets, age_78_plus as 0/1 integers
})
# TODO: fit VarianceThreshold(threshold=0.01) and print the kept names
Hint 1

A flag with a share pp of ones has variance p(1−p)p(1 - p). Below 0.01 means that the rare value occurs in about 1% of rows or fewer.

Hint 2

selector.get_support() returns a Boolean mask; flags.columns[mask] gives the kept names.

Solution
from sklearn.feature_selection import VarianceThreshold
flags = pd.DataFrame({
"has_autopay": customers["has_autopay"],
"is_premium": (customers["plan"] == "premium").astype(int),
"many_tickets": (customers["support_tickets"] >= 6).astype(int),
"age_78_plus": (customers["age"] >= 78).astype(int),
})
selector = VarianceThreshold(threshold=0.01).fit(flags)
print(pd.Series(selector.variances_, index=flags.columns).round(4))
kept = list(flags.columns[selector.get_support()])
print("kept:", kept)
assert kept == ["has_autopay", "is_premium"]
Output
has_autopay 0.249
is_premium 0.159
many_tickets 0.004
age_78_plus 0.004
dtype: float64
kept: ['has_autopay', 'is_premium']

How it works:

  1. variances_ holds the population variance of each column, p(1−p)p(1-p) for a flag.
  2. many_tickets is 1 for only 19 customers (0.38%) and age_78_plus for 21 (0.42%), so their variances fall below 0.01.
  3. A near-constant flag can still matter (19 customers with 6+ tickets may all churn), but a model has almost no rows to learn its effect from. Review dropped flags before you delete them for good.

Alternative: compute flags.mean() and keep the flags whose share of ones lies between 1% and 99%. That is the same rule written in shares.

M33-W09 · Predict the output: hours on a circle

Section titled “M33-W09 · Predict the output: hours on a circle”
Warm-up

Predict the output: the code maps the hours 0, 6, 12 and 23 onto a circle with sine and cosine (period 24). Then it prints the distance between hour 23 and hour 0, and between hour 0 and hour 12. Write down your prediction (rounded values), then run the code.

Acceptance criteria:

  • Write down the sin and cos of hours 0, 6 and 12 before you run the code.
  • Say which pair is closer: 23 and 0, or 0 and 12.
  • Run the code. Your prediction matches the Output in the solution.
Starter
hours = pd.Series([0, 6, 12, 23], index=[0, 6, 12, 23])
angle = 2 * np.pi * hours / 24
circle = pd.DataFrame({"sin": np.sin(angle), "cos": np.cos(angle)}).round(3)
print(circle)
print(round(np.linalg.norm(circle.loc[23] - circle.loc[0]), 3))
print(round(np.linalg.norm(circle.loc[0] - circle.loc[12]), 3))
Hint 1

Hour 0 sits at angle 0: sin 0, cos 1. Hour 6 is a quarter turn, hour 12 a half turn.

Hint 2

Opposite points on a unit circle are 2 apart. Neighboring hours are 2sin⁡(π/24)≈0.262 \sin(\pi / 24) \approx 0.26 apart.

Solution
hours = pd.Series([0, 6, 12, 23], index=[0, 6, 12, 23])
angle = 2 * np.pi * hours / 24
circle = pd.DataFrame({"sin": np.sin(angle), "cos": np.cos(angle)}).round(3)
print(circle)
late_to_midnight = round(np.linalg.norm(circle.loc[23] - circle.loc[0]), 3)
midnight_to_noon = round(np.linalg.norm(circle.loc[0] - circle.loc[12]), 3)
print(late_to_midnight)
print(midnight_to_noon)
assert late_to_midnight < midnight_to_noon
Output
sin cos
0 0.000 1.000
6 1.000 0.000
12 0.000 -1.000
23 -0.259 0.966
0.261
2.0

How it works:

  1. Hour 0 is at (sin 0, cos 1), hour 6 at (1, 0) and hour 12 at (0, −1). round(3) turns the tiny float error of sin⁡(π)\sin(\pi) into 0.
  2. Hour 23 is one step before midnight: a small negative sine and a cosine near 1. Its distance to hour 0 is 0.261.
  3. Hours 0 and 12 sit on opposite sides of the circle, distance 2. With raw hours, 23 and 0 would be 23 apart, the largest gap of the day.

Alternative: for tree models, a raw hour column often works well enough, because a tree can split it twice (hour < 6 and hour >= 22) to group the night hours.

M33-C01 · Choose a scaler for lot sizes and justify it

Section titled “M33-C01 · Choose a scaler for lot sizes and justify it”
Core

Choose a method and justify it: lot_sqft in houses has a long right tail. Scale it with StandardScaler and with RobustScaler (drop the blank values first). For each, print the scaled value of the median lot and of the largest lot, and the share of houses whose scaled value lies between −1 and 1. Then decide which scaler suits a KNN model better.

Expected output
skew 1.13, median 7,530, max 39,180
StandardScaler median lot -0.16 largest lot 6.30 share in [-1, 1] 0.701
RobustScaler median lot 0.00 largest lot 4.89 share in [-1, 1] 0.880
Starter
from sklearn.preprocessing import RobustScaler, StandardScaler
lots = houses[["lot_sqft"]].dropna()
# TODO: for each scaler: fit_transform, then print the scaled median lot,
# the scaled largest lot and the share between -1 and 1
Hint 1

The median lot is lots["lot_sqft"].median(). Transform a one-row DataFrame with that value, or use np.median on the scaled column.

Hint 2

((scaled >= -1) & (scaled <= 1)).mean() gives the share inside the band.

Solution
from sklearn.preprocessing import RobustScaler, StandardScaler
lots = houses[["lot_sqft"]].dropna()
print(f"skew {lots['lot_sqft'].skew():.2f}, median {lots['lot_sqft'].median():,.0f}, "
f"max {lots['lot_sqft'].max():,.0f}")
results = {}
for scaler in [StandardScaler(), RobustScaler()]:
scaled = scaler.fit_transform(lots).ravel()
share = ((scaled >= -1) & (scaled <= 1)).mean()
results[type(scaler).__name__] = share
print(f"{type(scaler).__name__:<15} median lot {np.median(scaled):6.2f} "
f"largest lot {scaled.max():6.2f} share in [-1, 1] {share:.3f}")
assert abs(np.median(RobustScaler().fit_transform(lots))) < 1e-12
Output
skew 1.13, median 7,530, max 39,180
StandardScaler median lot -0.16 largest lot 6.30 share in [-1, 1] 0.701
RobustScaler median lot 0.00 largest lot 4.89 share in [-1, 1] 0.880

How it works:

  1. StandardScaler subtracts the mean, which the large lots pull above the median, so the median lot gets a negative value. The largest lot ends up many standard deviations out.
  2. RobustScaler subtracts the median (the median lot becomes exactly 0) and divides by the interquartile range, which ignores the tail.
  3. Choice: RobustScaler for KNN. Typical lots keep a meaningful spread instead of being squeezed together by the extreme ones. If the model also allows it, a log transform before scaling tames the tail even more.

Alternative: np.log(lots) first, then StandardScaler. After the log, the distribution is close to symmetric, and the standard scaler works well.

M33-C02 · Fix the bug: the test set scaled with its own statistics

Section titled “M33-C02 · Fix the bug: the test set scaled with its own statistics”
Core

Fix the bug: the code below scales the training and the test set separately. Fix it so the test set uses the training statistics. Print the mean of the scaled test columns (it is no longer exactly 0) and the ROC-AUC of the KNN model.

Expected output
[-0.047 0.01 -0.011 -0.002]
0.764
Starter
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.preprocessing import StandardScaler
cols = ["tenure_months", "monthly_charges", "support_tickets", "logins_last_30d"]
X_train, X_test, y_train, y_test = train_test_split(
customers[cols], customers["churned"], test_size=0.25,
stratify=customers["churned"], random_state=42,
)
train_scaled = StandardScaler().fit_transform(X_train)
test_scaled = StandardScaler().fit_transform(X_test) # TODO: fix this line
knn = KNeighborsClassifier(n_neighbors=25).fit(train_scaled, y_train)
print(test_scaled.mean(axis=0).round(3))
print(round(roc_auc_score(y_test, knn.predict_proba(test_scaled)[:, 1]), 3))
Hint 1

You need one scaler object. Keep a name for it.

Hint 2

scaler = StandardScaler().fit(X_train), then scaler.transform(...) for both sets.

Solution
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.preprocessing import StandardScaler
cols = ["tenure_months", "monthly_charges", "support_tickets", "logins_last_30d"]
X_train, X_test, y_train, y_test = train_test_split(
customers[cols], customers["churned"], test_size=0.25,
stratify=customers["churned"], random_state=42,
)
scaler = StandardScaler().fit(X_train)
train_scaled = scaler.transform(X_train)
test_scaled = scaler.transform(X_test)
knn = KNeighborsClassifier(n_neighbors=25).fit(train_scaled, y_train)
test_means = test_scaled.mean(axis=0).round(3)
auc = roc_auc_score(y_test, knn.predict_proba(test_scaled)[:, 1])
print(test_means)
print(round(auc, 3))
assert not np.allclose(test_means, 0)
Output
[-0.047 0.01 -0.011 -0.002]
0.764

How it works:

  1. The bug: a second fit_transform learns a new mean and standard deviation from the test rows. The same raw value then maps to different scaled values in the two sets, and the test set “uses” its own future statistics.
  2. The fix fits one scaler on the training rows and reuses it. The test means are close to 0 but not exactly 0, which is what you expect from new data.
  3. Here the score barely changes (the buggy version gives 0.762), because both halves come from the same distribution. In production, a single new customer cannot even be scaled by its own statistics: the standard deviation of one row is 0.

Alternative: make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=25)) stores the scaler inside the model, so predict always uses the training statistics.

M33-C03 · Refactor: from get_dummies to OneHotEncoder

Section titled “M33-C03 · Refactor: from get_dummies to OneHotEncoder”
Core

Refactor: the code below one-hot encodes category with pd.get_dummies, separately for the 2023 sales (training) and the first 5 order lines of 2024 (a small batch to score). The batch gets fewer columns than the training set. Rewrite it with an OneHotEncoder fitted on the training lines. Print the number of columns for both versions and the encoded batch.

Expected output
get_dummies columns: 6 vs 4
OneHotEncoder columns: 6
Beauty Books Clothing Electronics Home Sports
Clothing 0 0 1 0 0 0
Electronics 0 0 0 1 0 0
Beauty 1 0 0 0 0 0
Home 0 0 0 0 1 0
Beauty 1 0 0 0 0 0
Starter
train_lines = sales[sales["order_date"].dt.year == 2023]
batch = sales[sales["order_date"].dt.year == 2024].head(5)
train_d = pd.get_dummies(train_lines["category"], dtype=int)
batch_d = pd.get_dummies(batch["category"], dtype=int)
print(train_d.shape[1], batch_d.shape[1])
# TODO: fit an OneHotEncoder on train_lines[["category"]]
# TODO: transform the batch; print its shape and the encoded rows
Hint 1

The encoder stores the categories in categories_ during fit. transform always returns those columns, in that order.

Hint 2

Use sparse_output=False, handle_unknown="ignore" and set_output(transform="pandas").

Solution
from sklearn.preprocessing import OneHotEncoder
train_lines = sales[sales["order_date"].dt.year == 2023]
batch = sales[sales["order_date"].dt.year == 2024].head(5)
train_d = pd.get_dummies(train_lines["category"], dtype=int)
batch_d = pd.get_dummies(batch["category"], dtype=int)
print("get_dummies columns:", train_d.shape[1], "vs", batch_d.shape[1])
encoder = OneHotEncoder(sparse_output=False, handle_unknown="ignore")
encoder.set_output(transform="pandas").fit(train_lines[["category"]])
batch_enc = encoder.transform(batch[["category"]]).astype(int)
print("OneHotEncoder columns:", batch_enc.shape[1])
assert list(batch_enc.columns) == list(encoder.get_feature_names_out())
short = batch_enc.rename(columns=lambda c: c.removeprefix("category_"))
print(short.set_axis(batch["category"].tolist()))
assert batch_enc.shape[1] == train_d.shape[1]
Output
get_dummies columns: 6 vs 4
OneHotEncoder columns: 6
Beauty Books Clothing Electronics Home Sports
Clothing 0 0 1 0 0 0
Electronics 0 0 0 1 0 0
Beauty 1 0 0 0 0 0
Home 0 0 0 0 1 0
Beauty 1 0 0 0 0 0

How it works:

  1. get_dummies creates one column per category that it sees. The batch of 5 lines does not contain all 6 categories, so its frame is narrower, and a model would read its columns in the wrong places.
  2. OneHotEncoder learns the 6 categories from the training lines once. Every later transform returns the same 6 columns.
  3. handle_unknown="ignore" also protects against a seventh category (for example a new “Toys” line) that appears after training.

Alternative: pd.get_dummies(...).reindex(columns=train_d.columns, fill_value=0) aligns the batch with the training columns. It works, but you must keep train_d.columns yourself; the encoder keeps it for you.

M33-C04 · Smoothed target encoding by hand

Section titled “M33-C04 · Smoothed target encoding by hand”
Core

Write a function smoothed_means(categories, target, m) that returns the smoothed target mean of each category: (ncyˉc+myˉ)/(nc+m)(n_c \bar{y}_c + m \bar{y}) / (n_c + m). Apply it to the payment_method of a random sample of 60 customers (random_state=42) with m=0 (no smoothing) and m=20. Print both encodings and the counts.

Expected output
count m=0 m=20
payment_method
bank_transfer 10 0.000 0.078
credit_card 19 0.105 0.111
electronic_check 19 0.263 0.188
paypal 12 0.000 0.073
global mean: 0.117
Starter
def smoothed_means(categories, target, m):
# TODO: count and mean per category, the global mean, then the formula
...
sample = customers.sample(60, random_state=42)
# TODO: build a table with the counts, m=0 and m=20 encodings; print it
Hint 1

target.groupby(categories).agg(["size", "mean"]) gives ncn_c and yˉc\bar{y}_c in one call.

Hint 2

The formula works on whole columns: (stats["size"] * stats["mean"] + m * global_mean) / (stats["size"] + m).

Solution
def smoothed_means(categories, target, m):
"""Mix each category's target mean with the global mean, weighted by m."""
stats = target.groupby(categories).agg(["size", "mean"])
global_mean = target.mean()
return (stats["size"] * stats["mean"] + m * global_mean) / (stats["size"] + m)
sample = customers.sample(60, random_state=42)
table = pd.DataFrame({
"count": sample.groupby("payment_method").size(),
"m=0": smoothed_means(sample["payment_method"], sample["churned"], 0),
"m=20": smoothed_means(sample["payment_method"], sample["churned"], 20),
})
print(table.round(3))
print("global mean:", round(sample["churned"].mean(), 3))
assert np.allclose(table["m=0"], sample.groupby("payment_method")["churned"].mean())
assert (abs(table["m=20"] - sample["churned"].mean())
<= abs(table["m=0"] - sample["churned"].mean())).all()
Output
count m=0 m=20
payment_method
bank_transfer 10 0.000 0.078
credit_card 19 0.105 0.111
electronic_check 19 0.263 0.188
paypal 12 0.000 0.073
global mean: 0.117

How it works:

  1. With m=0, the formula returns the raw category means. In a sample of 60, a category has only 10 to 19 customers, so these means jump around: two methods show no churner at all.
  2. With m=20, each category gets 20 imaginary customers at the global churn rate. Small categories move most toward the global mean.
  3. The second assert checks the defining property of smoothing: no encoding moves away from the global mean.

Alternative: TargetEncoder(smooth=20.0) applies the same formula (with target_type="binary"); its default smooth="auto" chooses the strength from the variance within and between categories.

M33-C05 · Quantile bins for monthly charges, learned on the training set

Section titled “M33-C05 · Quantile bins for monthly charges, learned on the training set”
Core

Split customers into training and test rows (25% test, stratified, random_state=42). Compute quintile edges (5 bins) of monthly_charges on the training rows with pd.qcut(..., retbins=True). Apply the same edges to the test rows with pd.cut. Print the edges and the churn rate per bin on the training and test rows. Interpret the pattern.

Expected output
edges: [ 28.05 37.84 53.37 62.49 86.12 143.24]
train test
monthly_charges
Q1 0.159 0.135
Q2 0.184 0.161
Q3 0.162 0.177
Q4 0.161 0.175
Q5 0.296 0.320
Starter
from sklearn.model_selection import train_test_split
train, test = train_test_split(
customers, test_size=0.25, stratify=customers["churned"], random_state=42
)
# TODO: train_bins, edges = pd.qcut(train["monthly_charges"], q=5, retbins=True)
# TODO: widen the outer edges so test values outside the training range fit
# TODO: test_bins = pd.cut(test["monthly_charges"], bins=edges)
# TODO: churn rate per bin for both sets
Hint 1

retbins=True makes pd.qcut return the edges too. Set edges[0] = -np.inf and edges[-1] = np.inf so that no test value falls outside.

Hint 2

Use the same labels= list for both cuts, for example ["Q1", "Q2", "Q3", "Q4", "Q5"].

Solution
from sklearn.model_selection import train_test_split
train, test = train_test_split(
customers, test_size=0.25, stratify=customers["churned"], random_state=42
)
labels = ["Q1", "Q2", "Q3", "Q4", "Q5"]
train_bins, edges = pd.qcut(train["monthly_charges"], q=5, labels=labels, retbins=True)
print("edges:", edges.round(2))
edges[0], edges[-1] = -np.inf, np.inf
test_bins = pd.cut(test["monthly_charges"], bins=edges, labels=labels)
rates = pd.DataFrame({
"train": train.groupby(train_bins, observed=True)["churned"].mean(),
"test": test.groupby(test_bins, observed=True)["churned"].mean(),
})
print(rates.round(3))
assert test_bins.notna().all()
assert rates["train"].idxmax() == "Q5"
Output
edges: [ 28.05 37.84 53.37 62.49 86.12 143.24]
train test
monthly_charges
Q1 0.159 0.135
Q2 0.184 0.161
Q3 0.162 0.177
Q4 0.161 0.175
Q5 0.296 0.320

How it works:

  1. pd.qcut on the training rows finds the 20%, 40%, 60% and 80% quantiles, so each training bin holds about 750 customers.
  2. Replacing the outer edges with ±∞\pm\infty makes the bins cover every possible value. A test customer with a charge above the training maximum still gets bin Q5.
  3. Interpretation: churn is flat across the first four bins and jumps in the top bin, for charges above about 86 (the Q4/Q5 edge on the training rows). The test rows show the same pattern, so it is not noise of one sample. A linear term in monthly_charges spreads this jump over the whole range; a flag for the top bin captures it.

Alternative: KBinsDiscretizer(n_bins=5, strategy="quantile", encode="ordinal") fitted on the training rows learns the same kind of edges, and its transform handles values outside the training range automatically.

M33-C06 · Uniform versus quantile bins for a skewed column

Section titled “M33-C06 · Uniform versus quantile bins for a skewed column”
Core

Fit two KBinsDiscretizer objects with 5 bins on lot_sqft (blank values dropped): one with strategy="uniform", one with strategy="quantile". Use encode="ordinal". Print the edges and the number of houses per bin for each. Which strategy suits this column, and why?

Expected output
uniform edges [ 880. 8540. 16200. 23860. 31520. 39180.]
counts [1700 1021 158 30 1]
quantile edges [ 880. 3940. 6430. 8730. 11960. 39180.]
counts [580 582 583 582 583]
Starter
from sklearn.preprocessing import KBinsDiscretizer
lots = houses[["lot_sqft"]].dropna()
for strategy in ["uniform", "quantile"]:
# TODO: fit, print the edges (bin_edges_[0]) and the counts per bin
...
Hint 1

binner.fit_transform(lots).ravel() gives one bin code (0 to 4) per house. np.bincount counts them.

Hint 2

Round the edges with .round(0) to keep the output short.

Solution
from sklearn.preprocessing import KBinsDiscretizer
lots = houses[["lot_sqft"]].dropna()
counts = {}
for strategy in ["uniform", "quantile"]:
binner = KBinsDiscretizer(n_bins=5, encode="ordinal", strategy=strategy)
codes = binner.fit_transform(lots).ravel().astype(int)
counts[strategy] = np.bincount(codes, minlength=5)
print(f"{strategy:<8} edges {binner.bin_edges_[0].round(0)}")
print(f"{'':<8} counts {counts[strategy]}")
assert counts["uniform"][:2].sum() > 0.9 * len(lots)
assert counts["quantile"].min() > 0.15 * len(lots)
Output
uniform edges [ 880. 8540. 16200. 23860. 31520. 39180.]
counts [1700 1021 158 30 1]
quantile edges [ 880. 3940. 6430. 8730. 11960. 39180.]
counts [580 582 583 582 583]

How it works:

  1. "uniform" splits the range from the smallest to the largest lot into 5 equal widths. The long tail stretches the range, so the first two bins hold more than 90% of the houses and the top bin holds a single lot.
  2. "quantile" puts the edges at the 20%, 40%, 60% and 80% quantiles, so each bin holds about 582 houses.
  3. Choice: quantile bins for a skewed column. Uniform bins waste four bins on a few large lots and give the model no detail where most houses are.

Alternative: strategy="kmeans" places the edges between clusters of values. On a skewed column, a log transform followed by uniform bins gives a similar spread to quantile bins with rounder edges.

M33-C07 · Predict the output: PolynomialFeatures options

Section titled “M33-C07 · Predict the output: PolynomialFeatures options”
Core

Predict the output: the code expands three columns a, b, c twice, once with interaction_only=True and once with degree=3. Write down the feature names of the first expansion and the column count of the second. Then run the code.

Acceptance criteria:

  • Write down all names of the first expansion, in order, before you run the code.
  • Compute the count of the second expansion with (n+dd)−1\binom{n+d}{d} - 1.
  • Run the code. Your prediction matches the Output in the solution.
Starter
from sklearn.preprocessing import PolynomialFeatures
abc = pd.DataFrame({"a": [1.0, 2.0], "b": [3.0, 4.0], "c": [5.0, 6.0]})
pairs = PolynomialFeatures(degree=2, interaction_only=True, include_bias=False)
print(list(pairs.fit(abc).get_feature_names_out()))
print(pairs.transform(abc))
cubic = PolynomialFeatures(degree=3, include_bias=False).fit(abc)
print(cubic.n_output_features_)
Hint 1

interaction_only=True keeps products of different features and drops the squares.

Hint 2

For n=3n = 3 and d=3d = 3: (63)−1=20−1\binom{6}{3} - 1 = 20 - 1.

Solution
from math import comb
from sklearn.preprocessing import PolynomialFeatures
abc = pd.DataFrame({"a": [1.0, 2.0], "b": [3.0, 4.0], "c": [5.0, 6.0]})
pairs = PolynomialFeatures(degree=2, interaction_only=True, include_bias=False)
names = list(pairs.fit(abc).get_feature_names_out())
print(names)
print(pairs.transform(abc))
cubic = PolynomialFeatures(degree=3, include_bias=False).fit(abc)
print(cubic.n_output_features_)
assert names == ["a", "b", "c", "a b", "a c", "b c"]
assert cubic.n_output_features_ == comb(3 + 3, 3) - 1
Output
['a', 'b', 'c', 'a b', 'a c', 'b c']
[[ 1. 3. 5. 3. 5. 15.]
[ 2. 4. 6. 8. 12. 24.]]
19

How it works:

  1. With interaction_only=True, degree 2 gives the three originals and the three pairwise products, no squares. For the first row: 1⋅3=31 \cdot 3 = 3, 1⋅5=51 \cdot 5 = 5, 3⋅5=153 \cdot 5 = 15.
  2. With include_bias=False, there is no constant column of ones.
  3. Degree 3 without the restriction creates every monomial up to degree 3: 3 of degree 1, 6 of degree 2 and 10 of degree 3, so 19 columns.

Alternative: for a single chosen interaction, multiply the columns yourself: abc["a"] * abc["b"]. It keeps the feature count under your control.

M33-C08 · An interaction for churn: contract × support tickets

Section titled “M33-C08 · An interaction for churn: contract × support tickets”
Core

The data dictionary reports that churn rises with the number of support tickets. Check whether that holds for every contract type: print the churn rate by contract and ticket count (0 to 4 tickets) on the training rows. Then add a feature mtm_x_tickets (a month-to-month flag times support_tickets). Compare the 5-fold cross-validated ROC-AUC of a scaled logistic regression with and without it, on the training rows only.

Expected output
support_tickets 0 1 2 3 4
contract
month-to-month 0.21 0.23 0.32 0.48 0.71
one-year 0.07 0.11 0.09 0.08 0.12
two-year 0.02 0.04 0.06 0.03 0.00
base CV ROC-AUC 0.8065
+ mtm_x_tickets CV ROC-AUC 0.8081
gain per fold: [ 0.0012 -0.0024 0.0059 0.0061 -0.0025]
Starter
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
df = customers.copy()
df["mtm"] = (df["contract"] == "month-to-month").astype(int)
# TODO: df["mtm_x_tickets"] = ...
train, test = train_test_split(
df, test_size=0.25, stratify=df["churned"], random_state=42
)
# TODO: churn rate table on train: rows contract, columns support_tickets 0-4
base = ["tenure_months", "monthly_charges", "support_tickets",
"logins_last_30d", "has_autopay", "mtm"]
# TODO: CV ROC-AUC on train with base and with base + interaction
Hint 1

train.groupby(["contract", "support_tickets"])["churned"].mean().unstack() builds the table; select columns 0 to 4 with .loc[:, 0:4].

Hint 2

cross_val_score(make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)), train[cols], train["churned"], cv=folds, scoring="roc_auc") refits the scaler in every fold.

Solution
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
df = customers.copy()
df["mtm"] = (df["contract"] == "month-to-month").astype(int)
df["mtm_x_tickets"] = df["mtm"] * df["support_tickets"]
train, test = train_test_split(
df, test_size=0.25, stratify=df["churned"], random_state=42
)
rates = train.groupby(["contract", "support_tickets"])["churned"].mean().unstack()
print(rates.loc[:, 0:4].round(2))
base = ["tenure_months", "monthly_charges", "support_tickets",
"logins_last_30d", "has_autopay", "mtm"]
folds = StratifiedKFold(5, shuffle=True, random_state=42)
aucs = {}
for name, cols in [("base", base), ("+ mtm_x_tickets", base + ["mtm_x_tickets"])]:
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
scores = cross_val_score(model, train[cols], train["churned"], cv=folds,
scoring="roc_auc")
aucs[name] = scores
print(f"{name:<16} CV ROC-AUC {scores.mean():.4f}")
gains = aucs["+ mtm_x_tickets"] - aucs["base"]
print("gain per fold:", gains.round(4))
assert gains.mean() > 0
Output
support_tickets 0 1 2 3 4
contract
month-to-month 0.21 0.23 0.32 0.48 0.71
one-year 0.07 0.11 0.09 0.08 0.12
two-year 0.02 0.04 0.06 0.03 0.00
base CV ROC-AUC 0.8065
+ mtm_x_tickets CV ROC-AUC 0.8081
gain per fold: [ 0.0012 -0.0024 0.0059 0.0061 -0.0025]

How it works:

  1. The table shows the interaction directly: for month-to-month customers, churn climbs steeply with each ticket. For one- and two-year contracts it stays flat. The overall “churn rises with tickets” of the data dictionary is mostly a month-to-month effect.
  2. Without the product, the model has one support_tickets coefficient for everybody, a compromise between a steep slope and a flat one. With mtm_x_tickets, the slope for month-to-month customers is the sum of two coefficients, and for the others it is one.
  3. The comparison runs on the training rows with cross-validation, so the test rows stay unused for a final score. Printing the gain per fold shows whether the improvement is consistent or the luck of one split. Here the mean gain is small and it helps in only 3 of 5 folds: the other features already capture much of the pattern. Keep the interaction only if a larger evaluation confirms it, or because it makes the model match the business story.

Alternative: PolynomialFeatures(degree=2, interaction_only=True) on [mtm, support_tickets] builds the same product, plus the originals.

M33-C09 · Recency features from order history

Section titled “M33-C09 · Recency features from order history”
Core

Build two features per customer from sales: days_since_last_order (from the snapshot date 2024-12-31) and order_count (distinct orders). Join them to customers. Customers without orders get order_count 0 and a blank recency. Print the number of customers without orders, and describe() of the recency rounded to 1 decimal.

Expected output
customers without orders: 1746
count 3254.0
mean 138.4
std 157.2
min 0.0
25% 25.0
50% 69.0
75% 200.0
max 724.0
Name: days_since_last_order, dtype: float64
Starter
snapshot = pd.Timestamp("2024-12-31")
# TODO: per customer_id: last order_date and number of unique order_id
# TODO: days_since_last_order = (snapshot - last_order).dt.days
# TODO: join to customers; fill order_count with 0
Hint 1

sales.groupby("customer_id").agg(last_order=("order_date", "max"), order_count=("order_id", "nunique")).

Hint 2

customers.join(history, on="customer_id") keeps every customer and leaves NaN where no order exists.

Solution
snapshot = pd.Timestamp("2024-12-31")
history = sales.groupby("customer_id").agg(
last_order=("order_date", "max"), order_count=("order_id", "nunique")
)
history["days_since_last_order"] = (snapshot - history["last_order"]).dt.days
features = customers.join(history[["days_since_last_order", "order_count"]],
on="customer_id")
features["order_count"] = features["order_count"].fillna(0).astype(int)
print("customers without orders:", (features["order_count"] == 0).sum())
print(features["days_since_last_order"].describe().round(1))
assert features["days_since_last_order"].min() >= 0
assert len(features) == len(customers)
Output
customers without orders: 1746
count 3254.0
mean 138.4
std 157.2
min 0.0
25% 25.0
50% 69.0
75% 200.0
max 724.0
Name: days_since_last_order, dtype: float64

How it works:

  1. Named aggregation computes the last order date and the number of distinct orders in one pass. nunique counts orders, not lines, because one order can have up to 3 lines.
  2. The fixed snapshot date makes the recency reproducible. Days since the last order is one of the strongest churn signals in real subscription data.
  3. A blank recency is information too (“never ordered”). Keep it as NaN for a gradient boosting model, or add a has_ordered flag and fill the blank for a linear model.

Alternative: in SQL (module 30), the same features are MAX(order_date) and COUNT(DISTINCT order_id) with GROUP BY customer_id, then a LEFT JOIN to the customer table.

M33-C10 · Refactor: row-by-row features to vectorized code

Section titled “M33-C10 · Refactor: row-by-row features to vectorized code”
Core

Refactor: the loop below builds three house features row by row with iterrows(). Rewrite it as vectorized pandas code and check that both versions give the same values. Print the first 3 rows of your features.

Expected output
age_at_sale sqft_per_bedroom has_garage
0 6 605.0 1
1 4 805.0 1
2 30 630.0 1
Starter
rows = []
for _, house in houses.iterrows():
sale_year = int(house["sold_date"][:4])
rows.append({
"age_at_sale": sale_year - house["year_built"],
"sqft_per_bedroom": house["sqft"] / house["bedrooms"],
"has_garage": 1 if house["garage_spaces"] > 0 else 0,
})
loop_features = pd.DataFrame(rows, index=houses.index)
# TODO: build the same three columns without a loop
Hint 1

pd.to_datetime(houses["sold_date"]).dt.year gives the sale year for every row at once.

Hint 2

Comparisons on whole columns return Boolean columns: (houses["garage_spaces"] > 0).astype(int).

Solution
rows = []
for _, house in houses.iterrows():
sale_year = int(house["sold_date"][:4])
rows.append({
"age_at_sale": sale_year - house["year_built"],
"sqft_per_bedroom": house["sqft"] / house["bedrooms"],
"has_garage": 1 if house["garage_spaces"] > 0 else 0,
})
loop_features = pd.DataFrame(rows, index=houses.index)
vector_features = pd.DataFrame({
"age_at_sale": pd.to_datetime(houses["sold_date"]).dt.year - houses["year_built"],
"sqft_per_bedroom": houses["sqft"] / houses["bedrooms"],
"has_garage": (houses["garage_spaces"] > 0).astype(int),
})
print(vector_features.head(3))
pd.testing.assert_frame_equal(loop_features, vector_features, check_dtype=False)
assert (vector_features["age_at_sale"] >= 1).all()
Output
age_at_sale sqft_per_bedroom has_garage
0 6 605.0 1
1 4 805.0 1
2 30 630.0 1

How it works:

  1. Each vectorized line computes a whole column in one call to compiled code. iterrows() builds a Series object per row, which is slow and loses the column dtypes.
  2. pd.testing.assert_frame_equal compares the two frames value by value. check_dtype=False allows the loop’s integer columns to differ in dtype from the vectorized ones.
  3. None of the three features uses price, so none leaks the target. A tempting fourth feature, price / sqft, would.

Alternative: houses.assign(age_at_sale=..., sqft_per_bedroom=..., has_garage=...) adds the columns to a copy of the table in one method chain.

M33-C11 · Interpret: correlation misses a U-shape

Section titled “M33-C11 · Interpret: correlation misses a U-shape”
Core

Interpret a result: churn is high for young and old customers. Compute the Pearson correlation of age with churned, and of a new feature age_gap = |age − 45| with churned. Then compute the mutual information of both features with churned (random_state=42). Explain why the correlations differ so much while the mutual information values do not.

Expected output
pearson_corr mutual_info
age -0.038 0.013
age_gap 0.151 0.012
Starter
from sklearn.feature_selection import mutual_info_classif
df = customers.assign(age_gap=(customers["age"] - 45).abs())
# TODO: correlation of age and age_gap with churned
# TODO: mutual_info_classif(df[["age", "age_gap"]], df["churned"], random_state=42)
Hint 1

df[["age", "age_gap"]].corrwith(df["churned"]) computes both correlations.

Hint 2

Think about what each measure can detect: only straight-line relations, or any dependence?

Solution
from sklearn.feature_selection import mutual_info_classif
df = customers.assign(age_gap=(customers["age"] - 45).abs())
corr = df[["age", "age_gap"]].corrwith(df["churned"])
mi = mutual_info_classif(df[["age", "age_gap"]], df["churned"], random_state=42)
result = pd.DataFrame({"pearson_corr": corr, "mutual_info": mi})
print(result.round(4))
assert abs(corr["age"]) < 0.05 < corr["age_gap"]
Output
pearson_corr mutual_info
age -0.038 0.013
age_gap 0.151 0.012

How it works:

  1. Pearson correlation measures a straight-line relation. Churn falls from age 18 to middle age and rises again, so the two halves cancel and the correlation of age is close to 0.
  2. age_gap folds the U-shape into a straight line: the farther from 45, the higher the churn. Its correlation is clearly positive.
  3. Mutual information detects any dependence, so it already sees the U-shape in raw age. Both values are about equal. Interpretation: a correlation filter would drop age as useless; mutual information would keep it; and a linear model needs age_gap (or age bins) to use it.

Alternative: a squared term, (age - 45) ** 2, or PolynomialFeatures(degree=2) on age gives the linear model the same U-shape with a smooth curve.

M33-C12 · The Lasso path: alpha controls how many features survive

Section titled “M33-C12 · The Lasso path: alpha controls how many features survive”
Core

Fit Lasso models to predict log(price) from the house features, with alpha values 0.001, 0.01, 0.05 and 0.2. Use a pipeline of SimpleImputer(strategy="median"), StandardScaler and Lasso, so that every step is fitted inside each fold. For each alpha, print the number of non-zero coefficients (fitted on all training rows) and the 5-fold cross-validated R² on the training rows. Leave the test set unused.

Expected output
alpha 0.001 non-zero 16 of 17 CV R2 0.8904
alpha 0.01 non-zero 12 of 17 CV R2 0.8796
alpha 0.05 non-zero 8 of 17 CV R2 0.8286
alpha 0.2 non-zero 2 of 17 CV R2 0.5005
Starter
from sklearn.impute import SimpleImputer
from sklearn.linear_model import Lasso
from sklearn.model_selection import KFold, cross_val_score, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X = pd.concat([
houses.drop(columns=["house_id", "neighborhood", "sold_date", "price"]),
pd.get_dummies(houses["neighborhood"], prefix="nb", drop_first=True, dtype=int),
], axis=1)
y = np.log(houses["price"])
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=42
)
folds = KFold(5, shuffle=True, random_state=42)
# TODO: for each alpha: build the pipeline, count non-zero coef_ after a fit
# on all training rows, and print the mean CV R2
Hint 1

Lasso penalizes all coefficients equally, so the features must share one scale. The imputer and the scaler sit in front of Lasso in the pipeline.

Hint 2

After pipe.fit(X_train, y_train), the Lasso step is pipe[-1]; (pipe[-1].coef_ != 0).sum() counts the kept features.

Solution
from sklearn.impute import SimpleImputer
from sklearn.linear_model import Lasso
from sklearn.model_selection import KFold, cross_val_score, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X = pd.concat([
houses.drop(columns=["house_id", "neighborhood", "sold_date", "price"]),
pd.get_dummies(houses["neighborhood"], prefix="nb", drop_first=True, dtype=int),
], axis=1)
y = np.log(houses["price"])
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=42
)
folds = KFold(5, shuffle=True, random_state=42)
counts, cv_r2 = [], []
for alpha in [0.001, 0.01, 0.05, 0.2]:
pipe = make_pipeline(SimpleImputer(strategy="median"), StandardScaler(),
Lasso(alpha=alpha))
cv_r2.append(cross_val_score(pipe, X_train, y_train, cv=folds, scoring="r2").mean())
counts.append(int((pipe.fit(X_train, y_train)[-1].coef_ != 0).sum()))
print(f"alpha {alpha:<5} non-zero {counts[-1]:>2} of {X.shape[1]} "
f"CV R2 {cv_r2[-1]:.4f}")
assert counts == sorted(counts, reverse=True)
assert cv_r2[0] > cv_r2[-1]
Output
alpha 0.001 non-zero 16 of 17 CV R2 0.8904
alpha 0.01 non-zero 12 of 17 CV R2 0.8796
alpha 0.05 non-zero 8 of 17 CV R2 0.8286
alpha 0.2 non-zero 2 of 17 CV R2 0.5005

How it works:

  1. The L1 penalty α∥w∥1\alpha \lVert w \rVert_1 grows with every non-zero coefficient. A larger α\alpha makes it cheaper to set weak coefficients to exactly 0.
  2. At small α\alpha, almost every feature survives and the CV R² is highest. At α=0.2\alpha = 0.2, only a few strong features remain and the fit gets worse.
  3. The right α\alpha balances fewer features against accuracy, and cross-validation on the training rows makes that choice without touching the test set. LassoCV automates the same search.

Alternative: SelectFromModel(Lasso(alpha=0.01)) inside the pipeline, followed by LinearRegression(), keeps the selected features but fits them without the penalty’s shrinkage.

M33-C13 · Interpret: why does the house id look important?

Section titled “M33-C13 · Interpret: why does the house id look important?”
Core

Interpret a result: a colleague adds house_num (the number in house_id, for example 537 for H0537) to a random forest for log(price) and finds a sizable importance. Fit the forest on sqft, bedrooms, condition, distance_to_center_km and house_num (n_estimators=100, random_state=42) and print the importances. Then print the correlation between house_num and the sale date. Explain the result.

Expected output
sqft 0.561
bedrooms 0.012
condition 0.060
distance_to_center_km 0.312
house_num 0.056
dtype: float64
corr(house_num, days since first sale): 0.9998
Starter
from sklearn.ensemble import RandomForestRegressor
df = houses.assign(house_num=houses["house_id"].str[1:].astype(int))
cols = ["sqft", "bedrooms", "condition", "distance_to_center_km", "house_num"]
# TODO: fit the forest on df[cols] and np.log(df["price"]); print importances
# TODO: correlation of house_num with the sale date as a number
Hint 1

Turn the date into a number with pd.to_datetime(df["sold_date"]).map(pd.Timestamp.toordinal), or count days from the first sale.

Hint 2

The data dictionary says the houses are sorted by sold_date. In the lesson’s Example 7, the sequential selector keeps sale_year, so the sale date carries a price signal.

Solution
from sklearn.ensemble import RandomForestRegressor
df = houses.assign(house_num=houses["house_id"].str[1:].astype(int))
cols = ["sqft", "bedrooms", "condition", "distance_to_center_km", "house_num"]
forest = RandomForestRegressor(n_estimators=100, random_state=42, n_jobs=-1)
forest.fit(df[cols], np.log(df["price"]))
importance = pd.Series(forest.feature_importances_, index=cols)
print(importance.round(3))
sold = pd.to_datetime(df["sold_date"])
day_number = (sold - sold.min()).dt.days
corr = df["house_num"].corr(day_number)
print(f"corr(house_num, days since first sale): {corr:.4f}")
assert corr > 0.99
Output
sqft 0.561
bedrooms 0.012
condition 0.060
distance_to_center_km 0.312
house_num 0.056
dtype: float64
corr(house_num, days since first sale): 0.9998

How it works:

  1. The forest gives house_num an importance close to that of condition. An id should mean nothing.
  2. The ids were assigned in sale order, so house_num is almost perfectly correlated with the sale date. Whatever price trend the sale date carries, the id carries too.
  3. Interpretation: the id is a proxy for time. It works on this data but breaks on new houses, whose ids lie beyond the training range (a tree cannot extrapolate them). Replace it with an explicit, meaningful feature such as sale_year or days since a fixed date, and never use row ids as features.

Alternative: permutation importance on a hold-out set (module 43) would likely rank house_num too, if the time signal is real. The fix is a better feature, not a better importance measure.

M33-C14 · Forward or backward sequential selection?

Section titled “M33-C14 · Forward or backward sequential selection?”
Core

Choose a method and justify it: run SequentialFeatureSelector on the churn training rows to pick 4 of 13 features, once forward and once backward. Use a scaled logistic regression, cv=3 and scoring="roc_auc". The features are the six numeric columns plus one-hot contract and payment_method. Print both selections and the time each took. Which direction do you prefer here?

Expected output
forward ['tenure_months', 'monthly_charges', 'support_tickets', 'contract_month-to-month']
backward ['tenure_months', 'monthly_charges', 'support_tickets', 'contract_two-year']
13 candidates; backward slower: True
Starter
import time
from sklearn.feature_selection import SequentialFeatureSelector
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
num = ["age", "tenure_months", "monthly_charges", "support_tickets",
"logins_last_30d", "has_autopay"]
train, _ = train_test_split(
customers, test_size=0.25, stratify=customers["churned"], random_state=42
)
dummies = pd.get_dummies(train[["contract", "payment_method"]], dtype=int)
X = pd.concat([train[num], dummies], axis=1)
# TODO: for each direction ("forward", "backward"): fit, print the chosen names
Hint 1

The estimator can be a pipeline: make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)). The selector then scales inside each fold.

Hint 2

Measure the time with time.perf_counter() before and after fit. Print a comparison, not raw seconds, so the output stays stable.

Solution
import time
from sklearn.feature_selection import SequentialFeatureSelector
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
num = ["age", "tenure_months", "monthly_charges", "support_tickets",
"logins_last_30d", "has_autopay"]
train, _ = train_test_split(
customers, test_size=0.25, stratify=customers["churned"], random_state=42
)
dummies = pd.get_dummies(train[["contract", "payment_method"]], dtype=int)
X = pd.concat([train[num], dummies], axis=1)
seconds = {}
for direction in ["forward", "backward"]:
start = time.perf_counter()
selector = SequentialFeatureSelector(
make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)),
n_features_to_select=4, direction=direction, cv=3, scoring="roc_auc",
).fit(X, train["churned"])
seconds[direction] = time.perf_counter() - start
print(f"{direction:<8}", list(X.columns[selector.get_support()]))
slower = seconds["backward"] > seconds["forward"]
print(X.shape[1], "candidates; backward slower:", slower)
assert seconds["backward"] > seconds["forward"]
Output
forward ['tenure_months', 'monthly_charges', 'support_tickets', 'contract_month-to-month']
backward ['tenure_months', 'monthly_charges', 'support_tickets', 'contract_two-year']
13 candidates; backward slower: True

How it works:

  1. Forward selection starts empty and adds the best feature 4 times: 13 + 12 + 11 + 10 = 46 candidate subsets, each scored with 3-fold CV.
  2. Backward selection starts with all 13 and removes one at a time until 4 remain: 13 + 12 + … + 5 = 81 subsets, and each subset has more features. It takes longer.
  3. Both agree on three features. They differ in the contract dummy: forward picks month-to-month, backward keeps two-year. The two dummies carry almost the same information, so either is fine. Choice: forward here, because few features are wanted out of many. Backward pays off when you keep most of the features, or when features only help in combination.
  4. get_dummies on the training rows is acceptable here: it learns only the category list, and every contract type and payment method occurs in each fold.

Alternative: RFE with the same pipeline (using importance_getter="named_steps.logisticregression.coef_") needs only one fit per removed feature and is faster still, but it ranks by coefficient size, not by cross-validated score.

M33-X01 · Out-of-fold target encoding by hand

Section titled “M33-X01 · Out-of-fold target encoding by hand”
Challenge

Implement cross-fitted target encoding yourself. Add a random postcode column to customers (codes Z0000 to Z0999 from np.random.default_rng(42)), as in the lesson. Write oof_encode(cat, y, folds, m): for each fold, compute smoothed means (smoothing m) on the other folds and encode the fold with them; unseen codes get the global mean of those other folds. Fit a scaled logistic regression on five numeric features plus the encoded postcode. Print train and test ROC-AUC for the naive encoding (training means, no folds) and your out-of-fold encoding (m=10, StratifiedKFold(5, shuffle=True, random_state=42)).

Expected output
naive: train 0.900 test 0.668
out-of-fold: train 0.787 test 0.782
Starter
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import StratifiedKFold, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
rng = np.random.default_rng(42)
codes = rng.integers(0, 1000, len(customers))
df = customers.assign(postcode=[f"Z{n:04d}" for n in codes])
train, test = train_test_split(
df, test_size=0.25, stratify=df["churned"], random_state=42
)
num = ["tenure_months", "monthly_charges", "support_tickets",
"logins_last_30d", "has_autopay"]
def smoothed_map(cat, y, m):
# TODO: smoothed mean per category and the global mean
...
def oof_encode(cat, y, folds, m):
# TODO: an empty float Series; fill each validation fold from the other folds
...
# TODO: naive and out-of-fold encodings for train; full-train mapping for test
# TODO: fit and print train/test ROC-AUC for both
Hint 1

folds.split(cat, y) yields pairs of position arrays (fit_idx, enc_idx). Use .iloc with them.

Hint 2

cat.iloc[enc_idx].map(means).fillna(global_mean) encodes the fold and handles codes that are missing from the other folds.

Hint 3

The test set is encoded once, with smoothed means from all training rows. Only the training rows need cross-fitting.

Solution
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import StratifiedKFold, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
rng = np.random.default_rng(42)
df = customers.assign(
postcode=[f"Z{n:04d}" for n in rng.integers(0, 1000, len(customers))]
)
train, test = train_test_split(
df, test_size=0.25, stratify=df["churned"], random_state=42
)
num = ["tenure_months", "monthly_charges", "support_tickets",
"logins_last_30d", "has_autopay"]
def smoothed_map(cat, y, m):
"""Return (smoothed mean per category, global mean)."""
stats = y.groupby(cat).agg(["size", "mean"])
global_mean = y.mean()
means = (stats["size"] * stats["mean"] + m * global_mean) / (stats["size"] + m)
return means, global_mean
def oof_encode(cat, y, folds, m):
"""Encode each fold with smoothed means learned on the other folds."""
encoded = pd.Series(np.nan, index=cat.index)
for fit_idx, enc_idx in folds.split(cat, y):
means, global_mean = smoothed_map(cat.iloc[fit_idx], y.iloc[fit_idx], m)
encoded.iloc[enc_idx] = cat.iloc[enc_idx].map(means).fillna(global_mean)
return encoded
def scores(train_code, test_code):
X_tr = train[num].assign(postcode_te=train_code)
X_te = test[num].assign(postcode_te=test_code)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
model.fit(X_tr, train["churned"])
return (roc_auc_score(train["churned"], model.predict_proba(X_tr)[:, 1]),
roc_auc_score(test["churned"], model.predict_proba(X_te)[:, 1]))
y_tr = train["churned"]
naive_means, naive_global = smoothed_map(train["postcode"], y_tr, m=0)
naive = scores(train["postcode"].map(naive_means),
test["postcode"].map(naive_means).fillna(naive_global))
folds = StratifiedKFold(5, shuffle=True, random_state=42)
full_means, full_global = smoothed_map(train["postcode"], y_tr, m=10)
oof = scores(oof_encode(train["postcode"], y_tr, folds, m=10),
test["postcode"].map(full_means).fillna(full_global))
print(f"naive: train {naive[0]:.3f} test {naive[1]:.3f}")
print(f"out-of-fold: train {oof[0]:.3f} test {oof[1]:.3f}")
assert naive[0] - naive[1] > 0.15
assert abs(oof[0] - oof[1]) < 0.02
Output
naive: train 0.900 test 0.668
out-of-fold: train 0.787 test 0.782

How it works:

  1. smoothed_map with m=0 is the naive encoding: every training row’s own churn value is inside its postcode mean. The model trusts the column, so the training score is high and the test score drops far below the no-postcode level (about 0.78).
  2. oof_encode encodes each fold with means from the other four folds. A row never sees its own target, so on the training set the column is as uninformative as it will be on new data.
  3. The test rows are encoded with means from all training rows, exactly as TargetEncoder.transform does. Train and test scores now agree, and the model is not fooled.

Alternative: TargetEncoder(cv=StratifiedKFold(5, shuffle=True, random_state=42)).fit_transform(train[["postcode"]], y_tr) does all of this, with an automatic smoothing strength.

M33-X02 · Leakage hunt in a churn extract

Section titled “M33-X02 · Leakage hunt in a churn extract”
Challenge

A new churn extract has three extra columns. The code below simulates them: nps_score (a satisfaction survey sent every quarter), refund_amount (money refunded to the customer) and newsletter_opt_in. Score every candidate feature alone with ROC-AUC (use max(auc, 1 − auc) so that negative relations count too). Print the ranking. Find the leaky column, show the evidence and fit the final model without it. Print the hold-out ROC-AUC with and without the leak.

Expected output
refund_amount 0.845
tenure_months 0.746
support_tickets 0.625
logins_last_30d 0.580
monthly_charges 0.575
nps_score 0.574
has_autopay 0.540
newsletter_opt_in 0.501
dtype: float64
share with a refund: {0: 0.0, 1: 0.691}
all candidates hold-out ROC-AUC 0.937
without refund_amount hold-out ROC-AUC 0.783
Starter
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
rng = np.random.default_rng(42)
n = len(customers)
df = customers.copy()
df["nps_score"] = np.clip(np.round(
7 + 0.08 * (df["logins_last_30d"] - 12) - 0.6 * df["support_tickets"]
+ rng.normal(0, 2, n)), 0, 10).astype(int)
refund = (df["churned"] == 1) & (rng.random(n) < 0.7)
df["refund_amount"] = np.where(refund, np.round(rng.uniform(5, 60, n), 2), 0.0)
df["newsletter_opt_in"] = (rng.random(n) < 0.4).astype(int)
candidates = ["tenure_months", "monthly_charges", "support_tickets",
"logins_last_30d", "has_autopay", "nps_score",
"refund_amount", "newsletter_opt_in"]
# TODO: single-feature AUC per candidate, sorted
# TODO: evidence for the leak (who gets a refund?)
# TODO: hold-out AUC with all candidates and without the leak
Hint 1

roc_auc_score(df["churned"], df[col]) uses the raw column as a score. An AUC of 0.3 means a strong negative relation, which max(auc, 1 - auc) turns into 0.7.

Hint 2

For the top column, compare its distribution for churners and non-churners: (df["refund_amount"] > 0).groupby(df["churned"]).mean().

Hint 3

Ask the timing question for each column: is it known before the customer decides to leave?

Solution
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
rng = np.random.default_rng(42)
n = len(customers)
df = customers.copy()
df["nps_score"] = np.clip(np.round(
7 + 0.08 * (df["logins_last_30d"] - 12) - 0.6 * df["support_tickets"]
+ rng.normal(0, 2, n)), 0, 10).astype(int)
refund = (df["churned"] == 1) & (rng.random(n) < 0.7)
df["refund_amount"] = np.where(refund, np.round(rng.uniform(5, 60, n), 2), 0.0)
df["newsletter_opt_in"] = (rng.random(n) < 0.4).astype(int)
candidates = ["tenure_months", "monthly_charges", "support_tickets",
"logins_last_30d", "has_autopay", "nps_score",
"refund_amount", "newsletter_opt_in"]
def single_auc(col):
auc = roc_auc_score(df["churned"], df[col])
return max(auc, 1 - auc)
ranking = pd.Series({col: single_auc(col) for col in candidates})
print(ranking.sort_values(ascending=False).round(3))
print("share with a refund:", (df["refund_amount"] > 0).groupby(df["churned"]).mean()
.round(3).to_dict())
train, test = train_test_split(
df, test_size=0.25, stratify=df["churned"], random_state=42
)
aucs = {}
for name, cols in [("all candidates", candidates),
("without refund_amount", [c for c in candidates
if c != "refund_amount"])]:
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
model.fit(train[cols], train["churned"])
aucs[name] = roc_auc_score(test["churned"], model.predict_proba(test[cols])[:, 1])
print(f"{name:<22} hold-out ROC-AUC {aucs[name]:.3f}")
assert ranking.idxmax() == "refund_amount"
assert aucs["all candidates"] - aucs["without refund_amount"] > 0.05
Output
refund_amount 0.845
tenure_months 0.746
support_tickets 0.625
logins_last_30d 0.580
monthly_charges 0.575
nps_score 0.574
has_autopay 0.540
newsletter_opt_in 0.501
dtype: float64
share with a refund: {0: 0.0, 1: 0.691}
all candidates hold-out ROC-AUC 0.937
without refund_amount hold-out ROC-AUC 0.783

How it works:

  1. refund_amount alone beats every real driver, including tenure_months. That alone is suspicious.
  2. The evidence: about 70% of churners got a refund and no non-churner did. A refund is paid after a cancellation, so the column records the outcome. It does not exist when the model must predict.
  3. nps_score is related to churn through logins and tickets, but the survey comes before the decision, so it is a legitimate feature. newsletter_opt_in scores 0.5: no signal. The honest model drops refund_amount and reports the lower score.

Alternative: fit a gradient boosting model and inspect the top importance, or fit a model per single feature with cross-validation. Any method that reveals “one feature does almost all the work” points to the leak; the timing question confirms it.

M33-X03 · Leakage-safe feature selection on wide data

Section titled “M33-X03 · Leakage-safe feature selection on wide data”
Challenge

Wide data makes selection leakage severe. Take a sample of 300 customers (random_state=42), six numeric features and 500 random noise columns (np.random.default_rng(42)). Compare three 5-fold cross-validated ROC-AUC scores (StratifiedKFold(5, shuffle=True, random_state=42)): (a) SelectKBest(f_classif, k=10) fitted on all 300 rows before CV; (b) the same selector inside a pipeline; (c) the six real features only, no selection. Print the three scores and the noise columns that the leaky selector picked.

Expected output
noise picked on all rows: 8 of 10
(a) select before CV: 0.863
(b) select inside CV: 0.709
(c) real features only: 0.791
Starter
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
rng = np.random.default_rng(42)
sample = customers.sample(300, random_state=42)
num = ["tenure_months", "monthly_charges", "support_tickets",
"logins_last_30d", "has_autopay", "age"]
noise = pd.DataFrame(rng.normal(size=(300, 500)), index=sample.index)
X = pd.concat([sample[num], noise.add_prefix("noise_")], axis=1)
y = sample["churned"]
folds = StratifiedKFold(5, shuffle=True, random_state=42)
# TODO: (a) select on all rows, then cross_val_score on the selected columns
# TODO: (b) cross_val_score on a pipeline with the selector inside
# TODO: (c) cross_val_score on the six real features
Hint 1

For (a): selector = SelectKBest(f_classif, k=10).fit(X, y), then X.loc[:, selector.get_support()].

Hint 2

For (b): make_pipeline(SelectKBest(f_classif, k=10), StandardScaler(), LogisticRegression(max_iter=1000)). Pass scoring="roc_auc" to cross_val_score.

Solution
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
rng = np.random.default_rng(42)
sample = customers.sample(300, random_state=42)
num = ["tenure_months", "monthly_charges", "support_tickets",
"logins_last_30d", "has_autopay", "age"]
noise = pd.DataFrame(rng.normal(size=(300, 500)), index=sample.index)
X = pd.concat([sample[num], noise.add_prefix("noise_")], axis=1)
y = sample["churned"]
folds = StratifiedKFold(5, shuffle=True, random_state=42)
def cv_auc(model, features):
return cross_val_score(model, features, y, cv=folds, scoring="roc_auc").mean()
selector = SelectKBest(f_classif, k=10).fit(X, y)
picked = list(X.columns[selector.get_support()])
logreg = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
leaky = cv_auc(logreg, X[picked])
safe = cv_auc(make_pipeline(SelectKBest(f_classif, k=10), StandardScaler(),
LogisticRegression(max_iter=1000)), X)
real_only = cv_auc(logreg, X[num])
noise_picked = [c for c in picked if c.startswith("noise_")]
print(f"noise picked on all rows: {len(noise_picked)} of 10")
print(f"(a) select before CV: {leaky:.3f}")
print(f"(b) select inside CV: {safe:.3f}")
print(f"(c) real features only: {real_only:.3f}")
assert leaky > real_only > safe
Output
noise picked on all rows: 8 of 10
(a) select before CV: 0.863
(b) select inside CV: 0.709
(c) real features only: 0.791

How it works:

  1. With 500 noise columns and only 300 rows, some noise columns match the labels by chance. The leaky selector uses all rows and fills 8 of its 10 slots with noise. Those columns also “predict” the validation folds, because the folds took part in the choice. Score (a) beats even the model with only the real features.
  2. Inside the pipeline, each training fold picks its own top 10. The chance matches of one fold do not repeat in the validation fold, so these columns hurt, and score (b) is the honest one.
  3. Score (c) shows the cost of the noise columns: on wide data, a selector that picks noise is worse than no selection. In practice, you would remove columns without a plausible link to the target before any automatic selection.

Alternative: SelectFromModel(LogisticRegression(l1_ratio=1.0, solver="liblinear", C=0.1)) inside the same pipeline selects with an L1 penalty instead of univariate tests. scikit-learn 1.9 sets the L1 penalty through l1_ratio; the old penalty="l1" argument is deprecated.

M33-X04 · Time leakage from a centered rolling mean

Section titled “M33-X04 · Time leakage from a centered rolling mean”
Challenge

A planner smooths daily units from sales with a 3-day rolling mean and uses it as a feature to predict the units of the same day. Compare a centered window (center=True, which uses yesterday, today and tomorrow) with a trailing window shifted by one day (the 3 days before today). Train a linear regression on days before 2024-07-01 and test on the rest. Print the test MAE and R² for both features, and explain why one of them leaks.

Expected output
centered_3 MAE 10.47 R2 0.693
trailing_3 MAE 17.34 R2 0.062
units centered_3 trailing_3
order_date
2024-07-09 24 36.7 39.7
2024-07-10 49 44.0 32.7
2024-07-11 59 51.7 36.7
Starter
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, r2_score
daily = sales.groupby("order_date")["quantity"].sum().rename("units").to_frame()
# TODO: daily["centered_3"] = daily["units"].rolling(3, center=True).mean()
# TODO: daily["trailing_3"] = daily["units"].shift(1).rolling(3).mean()
# TODO: drop the rows with NaN, split by date, fit and score each feature
Hint 1

daily.index < "2024-07-01" gives the training mask; the index holds dates.

Hint 2

Write out which days each window averages for 2024-07-10. Does the target day itself appear?

Solution
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, r2_score
daily = sales.groupby("order_date")["quantity"].sum().rename("units").to_frame()
daily["centered_3"] = daily["units"].rolling(3, center=True).mean()
daily["trailing_3"] = daily["units"].shift(1).rolling(3).mean()
daily = daily.dropna()
is_train = daily.index < "2024-07-01"
results = {}
for col in ["centered_3", "trailing_3"]:
train_part, test_part = daily[is_train], daily[~is_train]
model = LinearRegression().fit(train_part[[col]], train_part["units"])
pred = model.predict(test_part[[col]])
mae = mean_absolute_error(test_part["units"], pred)
results[col] = r2_score(test_part["units"], pred)
print(f"{col:<11} MAE {mae:5.2f} R2 {results[col]:.3f}")
print(daily.loc["2024-07-09":"2024-07-11"].round(1))
assert results["centered_3"] > results["trailing_3"] + 0.4
Output
centered_3 MAE 10.47 R2 0.693
trailing_3 MAE 17.34 R2 0.062
units centered_3 trailing_3
order_date
2024-07-09 24 36.7 39.7
2024-07-10 49 44.0 32.7
2024-07-11 59 51.7 36.7

How it works:

  1. The centered window for a day averages the day before, the day itself and the day after. The feature contains a third of the target and a piece of the future. It scores an R² near 0.7.
  2. The trailing window averages the three days before the target day. It uses only the past, which is all a real forecast has. Its R² is low, which is the honest difficulty of predicting daily units from recent days alone.
  3. The printed rows make it concrete: for 2024-07-10, centered_3 includes 2024-07-11, a day that has not happened when you forecast 2024-07-10. Any rolling, expanding or bfill operation on a time series can leak this way. Shift first, then roll.

Alternative: daily["units"].shift(1).ewm(span=3).mean() is an exponentially weighted trailing average. It also uses only the past and reacts faster to recent days. Module 40 builds lag and rolling features for forecasting.

M33-X05 · Engineer churn features and measure each gain

Section titled “M33-X05 · Engineer churn features and measure each gain”
Challenge

Start from the six numeric churn columns plus one-hot dummies of the four text columns. An analyst proposes five candidate features after an exploratory look at the data. Treat each one as a hypothesis, not a known fact. Add them one at a time, cumulatively, and print the 5-fold cross-validated ROC-AUC after each addition (scaled logistic regression, StratifiedKFold(5, shuffle=True, random_state=42)):

  1. new_customer = exp(−tenure_months / 5) (hypothesis: churn risk fades over the first months);
  2. low_logins = 1 when logins_last_30d <= 3;
  3. high_charges = 1 when monthly_charges > 85;
  4. mtm_x_tickets = month-to-month flag × support_tickets;
  5. age_gap = |age − 45|.

Then say which features earned their place. The cross-validated gain is the test of each hypothesis.

Expected output
baseline 0.8136
+ new_customer 0.8231 (+0.0095)
+ low_logins 0.8363 (+0.0132)
+ high_charges 0.8365 (+0.0001)
+ mtm_x_tickets 0.8394 (+0.0029)
+ age_gap 0.8535 (+0.0141)
Starter
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
num = ["age", "tenure_months", "monthly_charges", "support_tickets",
"logins_last_30d", "has_autopay"]
cats = ["region", "plan", "contract", "payment_method"]
X = pd.concat([customers[num], pd.get_dummies(customers[cats], dtype=int)], axis=1)
y = customers["churned"]
folds = StratifiedKFold(5, shuffle=True, random_state=42)
# TODO: a function cv_auc(X) with a scaler + logistic regression pipeline
# TODO: add the five features one by one; print the score after each
Hint 1

Keep a dictionary {name: column} of the five new features and add them to X in a loop.

Hint 2

The month-to-month dummy is the column contract_month-to-month created by get_dummies. get_dummies is acceptable here: it learns only the list of categories, and every category occurs in every training fold. The five new features are computed row by row, so they learn nothing from other rows.

Solution
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
num = ["age", "tenure_months", "monthly_charges", "support_tickets",
"logins_last_30d", "has_autopay"]
cats = ["region", "plan", "contract", "payment_method"]
X = pd.concat([customers[num], pd.get_dummies(customers[cats], dtype=int)], axis=1)
y = customers["churned"]
folds = StratifiedKFold(5, shuffle=True, random_state=42)
def cv_auc(features):
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
return cross_val_score(model, features, y, cv=folds, scoring="roc_auc").mean()
new_features = {
"new_customer": np.exp(-customers["tenure_months"] / 5),
"low_logins": (customers["logins_last_30d"] <= 3).astype(int),
"high_charges": (customers["monthly_charges"] > 85).astype(int),
"mtm_x_tickets": X["contract_month-to-month"] * customers["support_tickets"],
"age_gap": (customers["age"] - 45).abs(),
}
scores = {"baseline": cv_auc(X)}
print(f"{'baseline':<16} {scores['baseline']:.4f}")
for name, column in new_features.items():
X = X.assign(**{name: column})
scores[name] = cv_auc(X)
gain = scores[name] - list(scores.values())[-2]
print(f"+ {name:<14} {scores[name]:.4f} ({gain:+.4f})")
assert scores["age_gap"] > scores["baseline"] + 0.03
Output
baseline 0.8136
+ new_customer 0.8231 (+0.0095)
+ low_logins 0.8363 (+0.0132)
+ high_charges 0.8365 (+0.0001)
+ mtm_x_tickets 0.8394 (+0.0029)
+ age_gap 0.8535 (+0.0141)

How it works:

  1. Each candidate feature tests a pattern that a linear model cannot form from the raw columns: a fast-fading early-tenure risk, a threshold on logins, a threshold on charges, an interaction and a U-shape. The thresholds and the time scale of 5 months are guesses; other values may fit better, and only the CV score can tell.
  2. Cross-validation scores every version on the same 5 folds, so the differences come from the features, not from the split. Every step inside the pipeline (the scaler) is refit on each training fold.
  3. Verdict: low_logins, age_gap and new_customer earn their place with clear gains. mtm_x_tickets adds a small gain that is not consistent: a per-fold check shows it helps in 4 of 5 folds and hurts in one. high_charges adds almost nothing: monthly_charges and the plan dummies already carry that information. Drop it, or keep it only if it helps explain the model to the business.

Alternative: a HistGradientBoostingClassifier on the raw columns finds thresholds, interactions and U-shapes by itself without hand-made features. The data dictionary reports a CV ROC-AUC of 0.831 for its default settings and 0.847 tuned, close to the 0.854 of the engineered linear model here. Hand-made features matter most for linear models and for explaining a model.