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:
- Read the task and the expected output.
- 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. - Run the script with
python exercise.pyfrom your project folder, the folder that holdsdata/. Compare your output with the expected output. - 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 npimport 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"])Warm-up
Section titled “Warm-up”M33-W01 · Standardize monthly charges by hand
Section titled “M33-W01 · Standardize monthly charges by hand”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.
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.854from 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.allcloseHint 1
. 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-12values: [ 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.854How it works:
values.mean()andvalues.std()are the two parameters thatStandardScalerlearns (mean_andscale_).- Subtracting the mean centers the values at 0. Dividing by the standard deviation gives them a spread of 1.
- pandas
.std()divides by and NumPy’s.std()by . With 5 values the difference is visible. A hand-made scaler that uses pandas.std()does not matchStandardScaler.
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”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.
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 . 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[0.] [72.][ 0.5 1.25 -0.083]How it works:
fitstoresdata_min_ = 0anddata_max_ = 72. The other training values do not matter.- 36 is halfway between 0 and 72, so it becomes 0.5.
- 90 is above the training maximum, so it becomes 90 / 72 = 1.25. −6 is below the minimum and becomes −0.083.
MinMaxScalerguarantees 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.
M33-W03 · One-hot encode the plan
Section titled “M33-W03 · One-hot encode the plan”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.
['plan_basic', 'plan_premium', 'plan_standard']plan_basic 2028plan_premium 990plan_standard 1982dtype: int64from 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 sumsHint 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()['plan_basic', 'plan_premium', 'plan_standard']plan_basic 2028plan_premium 990plan_standard 1982dtype: int64How it works:
sparse_output=Falsereturns a dense array;set_output(transform="pandas")wraps it in a DataFrame with the names fromget_feature_names_out().- The categories are sorted, so the columns come in the order basic, premium, standard.
- 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”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.
['basic', 'standard', 'premium']{'basic': 0.0, 'standard': 1.0, 'premium': 2.0}from sklearn.preprocessing import OrdinalEncoder
plans = pd.DataFrame({"plan": ["basic", "standard", "premium"]})encoder = OrdinalEncoder() # TODO: fix the ordercodes = 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]['basic', 'standard', 'premium']{'basic': 0.0, 'standard': 1.0, 'premium': 2.0}How it works:
- Without
categories=,OrdinalEncodersorts the categories alphabetically: basic, premium, standard. Standard then gets code 2. - The explicit list fixes the order. The code of each category is its position in the list.
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.
M33-W05 · Bin customer age into bands
Section titled “M33-W05 · Bin customer age into bands”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.
size meanage18-29 842 0.27930-44 1994 0.17045-59 1703 0.15260+ 461 0.282edges = [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 meanHint 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") size meanage18-29 842 0.27930-44 1994 0.17045-59 1703 0.15260+ 461 0.282How it works:
pd.cutassigns each age to the interval it falls in. The last edge is 81, so 80 lands in “60+”.observed=Truekeeps only the bands that occur. It is the pandas 3 default; writing it makes the intent clear.- Churn is highest for the youngest and the oldest customers, a U-shape. A linear model with
ageas 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.
M33-W06 · Weekend flags from web traffic
Section titled “M33-W06 · Weekend flags from web traffic”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.
is_weekend0 4577.01 3810.0Name: visits, dtype: float64weekend days: 314 of 1096# TODO: traffic["day_of_week"] = ...# TODO: traffic["is_weekend"] = ...# TODO: mean visits per is_weekend valueHint 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_weektraffic["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]is_weekend0 4577.01 3810.0Name: visits, dtype: float64weekend days: 314 of 1096How it works:
- The
.dtaccessor works because the setup readsdatewithparse_dates=. day_of_week >= 5selects Saturday (5) and Sunday (6)..astype(int)turns the Boolean column into 0/1.- The site gets fewer visits at weekends.
mean()skips the 5 blankvisitsvalues (tracking outages).
Alternative: traffic["date"].dt.day_name().isin(["Saturday", "Sunday"]) builds the same flag from day names, which reads well in reports.
M33-W07 · Log-transform support tickets
Section titled “M33-W07 · Log-transform support tickets”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.
zeros: 1537skew before: 1.045skew after: 0.028min and max after: 0.0 2.303tickets = 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 ticketsHint 1
np.log(0) is -inf, so a plain log fails on the zeros. np.log1p(x) computes , which is 0 for .
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())zeros: 1537skew before: 1.045skew after: 0.028min and max after: 0.0 2.303How it works:
- 1,537 customers have no ticket, so
np.logwould give-inffor them.log1pmaps 0 to 0. - The transform compresses the tail: 9 tickets become 2.303 instead of standing far out.
np.expm1is the exact inverse ofnp.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.
M33-W08 · Drop near-constant flags
Section titled “M33-W08 · Drop near-constant flags”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.
has_autopay 0.249is_premium 0.159many_tickets 0.004age_78_plus 0.004dtype: float64kept: ['has_autopay', 'is_premium']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 namesHint 1
A flag with a share of ones has variance . 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"]has_autopay 0.249is_premium 0.159many_tickets 0.004age_78_plus 0.004dtype: float64kept: ['has_autopay', 'is_premium']How it works:
variances_holds the population variance of each column, for a flag.many_ticketsis 1 for only 19 customers (0.38%) andage_78_plusfor 21 (0.42%), so their variances fall below 0.01.- 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”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.
hours = pd.Series([0, 6, 12, 23], index=[0, 6, 12, 23])angle = 2 * np.pi * hours / 24circle = 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 apart.
Solution
hours = pd.Series([0, 6, 12, 23], index=[0, 6, 12, 23])angle = 2 * np.pi * hours / 24circle = 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 sin cos0 0.000 1.0006 1.000 0.00012 0.000 -1.00023 -0.259 0.9660.2612.0How it works:
- 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 into 0. - Hour 23 is one step before midnight: a small negative sine and a cosine near 1. Its distance to hour 0 is 0.261.
- 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”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.
skew 1.13, median 7,530, max 39,180StandardScaler median lot -0.16 largest lot 6.30 share in [-1, 1] 0.701RobustScaler median lot 0.00 largest lot 4.89 share in [-1, 1] 0.880from 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 1Hint 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-12skew 1.13, median 7,530, max 39,180StandardScaler median lot -0.16 largest lot 6.30 share in [-1, 1] 0.701RobustScaler median lot 0.00 largest lot 4.89 share in [-1, 1] 0.880How it works:
StandardScalersubtracts 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.RobustScalersubtracts the median (the median lot becomes exactly 0) and divides by the interquartile range, which ignores the tail.- Choice:
RobustScalerfor 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”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.
[-0.047 0.01 -0.011 -0.002]0.764from sklearn.metrics import roc_auc_scorefrom sklearn.model_selection import train_test_splitfrom sklearn.neighbors import KNeighborsClassifierfrom 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 lineknn = 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_scorefrom sklearn.model_selection import train_test_splitfrom sklearn.neighbors import KNeighborsClassifierfrom 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)[-0.047 0.01 -0.011 -0.002]0.764How it works:
- The bug: a second
fit_transformlearns 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. - 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.
- 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”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.
get_dummies columns: 6 vs 4OneHotEncoder columns: 6 Beauty Books Clothing Electronics Home SportsClothing 0 0 1 0 0 0Electronics 0 0 0 1 0 0Beauty 1 0 0 0 0 0Home 0 0 0 0 1 0Beauty 1 0 0 0 0 0train_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 rowsHint 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]get_dummies columns: 6 vs 4OneHotEncoder columns: 6 Beauty Books Clothing Electronics Home SportsClothing 0 0 1 0 0 0Electronics 0 0 0 1 0 0Beauty 1 0 0 0 0 0Home 0 0 0 0 1 0Beauty 1 0 0 0 0 0How it works:
get_dummiescreates 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.OneHotEncoderlearns the 6 categories from the training lines once. Every latertransformreturns the same 6 columns.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”Write a function smoothed_means(categories, target, m) that returns the smoothed target mean of each category: . 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.
count m=0 m=20payment_methodbank_transfer 10 0.000 0.078credit_card 19 0.105 0.111electronic_check 19 0.263 0.188paypal 12 0.000 0.073global mean: 0.117def 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 itHint 1
target.groupby(categories).agg(["size", "mean"]) gives and 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() count m=0 m=20payment_methodbank_transfer 10 0.000 0.078credit_card 19 0.105 0.111electronic_check 19 0.263 0.188paypal 12 0.000 0.073global mean: 0.117How it works:
- 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. - With
m=20, each category gets 20 imaginary customers at the global churn rate. Small categories move most toward the global mean. - 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”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.
edges: [ 28.05 37.84 53.37 62.49 86.12 143.24] train testmonthly_chargesQ1 0.159 0.135Q2 0.184 0.161Q3 0.162 0.177Q4 0.161 0.175Q5 0.296 0.320from 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 setsHint 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.inftest_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"edges: [ 28.05 37.84 53.37 62.49 86.12 143.24] train testmonthly_chargesQ1 0.159 0.135Q2 0.184 0.161Q3 0.162 0.177Q4 0.161 0.175Q5 0.296 0.320How it works:
pd.qcuton the training rows finds the 20%, 40%, 60% and 80% quantiles, so each training bin holds about 750 customers.- Replacing the outer edges with makes the bins cover every possible value. A test customer with a charge above the training maximum still gets bin Q5.
- 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_chargesspreads 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”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?
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]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)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:
"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."quantile"puts the edges at the 20%, 40%, 60% and 80% quantiles, so each bin holds about 582 houses.- 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”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 .
- Run the code. Your prediction matches the Output in the solution.
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 and : .
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['a', 'b', 'c', 'a b', 'a c', 'b c'][[ 1. 3. 5. 3. 5. 15.] [ 2. 4. 6. 8. 12. 24.]]19How it works:
- With
interaction_only=True, degree 2 gives the three originals and the three pairwise products, no squares. For the first row: , , . - With
include_bias=False, there is no constant column of ones. - 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”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.
support_tickets 0 1 2 3 4contractmonth-to-month 0.21 0.23 0.32 0.48 0.71one-year 0.07 0.11 0.09 0.08 0.12two-year 0.02 0.04 0.06 0.03 0.00base CV ROC-AUC 0.8065+ mtm_x_tickets CV ROC-AUC 0.8081gain per fold: [ 0.0012 -0.0024 0.0059 0.0061 -0.0025]from sklearn.linear_model import LogisticRegressionfrom sklearn.model_selection import StratifiedKFold, cross_val_score, train_test_splitfrom sklearn.pipeline import make_pipelinefrom 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-4base = ["tenure_months", "monthly_charges", "support_tickets", "logins_last_30d", "has_autopay", "mtm"]# TODO: CV ROC-AUC on train with base and with base + interactionHint 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 LogisticRegressionfrom sklearn.model_selection import StratifiedKFold, cross_val_score, train_test_splitfrom sklearn.pipeline import make_pipelinefrom 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() > 0support_tickets 0 1 2 3 4contractmonth-to-month 0.21 0.23 0.32 0.48 0.71one-year 0.07 0.11 0.09 0.08 0.12two-year 0.02 0.04 0.06 0.03 0.00base CV ROC-AUC 0.8065+ mtm_x_tickets CV ROC-AUC 0.8081gain per fold: [ 0.0012 -0.0024 0.0059 0.0061 -0.0025]How it works:
- 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.
- Without the product, the model has one
support_ticketscoefficient for everybody, a compromise between a steep slope and a flat one. Withmtm_x_tickets, the slope for month-to-month customers is the sum of two coefficients, and for the others it is one. - 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”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.
customers without orders: 1746count 3254.0mean 138.4std 157.2min 0.025% 25.050% 69.075% 200.0max 724.0Name: days_since_last_order, dtype: float64snapshot = 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 0Hint 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.daysfeatures = 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() >= 0assert len(features) == len(customers)customers without orders: 1746count 3254.0mean 138.4std 157.2min 0.025% 25.050% 69.075% 200.0max 724.0Name: days_since_last_order, dtype: float64How it works:
- Named aggregation computes the last order date and the number of distinct orders in one pass.
nuniquecounts orders, not lines, because one order can have up to 3 lines. - The fixed snapshot date makes the recency reproducible. Days since the last order is one of the strongest churn signals in real subscription data.
- A blank recency is information too (“never ordered”). Keep it as NaN for a gradient boosting model, or add a
has_orderedflag 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”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.
age_at_sale sqft_per_bedroom has_garage0 6 605.0 11 4 805.0 12 30 630.0 1rows = []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 loopHint 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() age_at_sale sqft_per_bedroom has_garage0 6 605.0 11 4 805.0 12 30 630.0 1How it works:
- 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. pd.testing.assert_frame_equalcompares the two frames value by value.check_dtype=Falseallows the loop’s integer columns to differ in dtype from the vectorized ones.- 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”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.
pearson_corr mutual_infoage -0.038 0.013age_gap 0.151 0.012from 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"] pearson_corr mutual_infoage -0.038 0.013age_gap 0.151 0.012How it works:
- 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
ageis close to 0. age_gapfolds the U-shape into a straight line: the farther from 45, the higher the churn. Its correlation is clearly positive.- 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 dropageas useless; mutual information would keep it; and a linear model needsage_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”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.
alpha 0.001 non-zero 16 of 17 CV R2 0.8904alpha 0.01 non-zero 12 of 17 CV R2 0.8796alpha 0.05 non-zero 8 of 17 CV R2 0.8286alpha 0.2 non-zero 2 of 17 CV R2 0.5005from sklearn.impute import SimpleImputerfrom sklearn.linear_model import Lassofrom sklearn.model_selection import KFold, cross_val_score, train_test_splitfrom sklearn.pipeline import make_pipelinefrom 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 R2Hint 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 SimpleImputerfrom sklearn.linear_model import Lassofrom sklearn.model_selection import KFold, cross_val_score, train_test_splitfrom sklearn.pipeline import make_pipelinefrom 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]alpha 0.001 non-zero 16 of 17 CV R2 0.8904alpha 0.01 non-zero 12 of 17 CV R2 0.8796alpha 0.05 non-zero 8 of 17 CV R2 0.8286alpha 0.2 non-zero 2 of 17 CV R2 0.5005How it works:
- The L1 penalty grows with every non-zero coefficient. A larger makes it cheaper to set weak coefficients to exactly 0.
- At small , almost every feature survives and the CV R² is highest. At , only a few strong features remain and the fit gets worse.
- The right balances fewer features against accuracy, and cross-validation on the training rows makes that choice without touching the test set.
LassoCVautomates 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?”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.
sqft 0.561bedrooms 0.012condition 0.060distance_to_center_km 0.312house_num 0.056dtype: float64corr(house_num, days since first sale): 0.9998from 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 numberHint 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.dayscorr = df["house_num"].corr(day_number)print(f"corr(house_num, days since first sale): {corr:.4f}")assert corr > 0.99sqft 0.561bedrooms 0.012condition 0.060distance_to_center_km 0.312house_num 0.056dtype: float64corr(house_num, days since first sale): 0.9998How it works:
- The forest gives
house_numan importance close to that ofcondition. An id should mean nothing. - The ids were assigned in sale order, so
house_numis almost perfectly correlated with the sale date. Whatever price trend the sale date carries, the id carries too. - 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_yearor 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?”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?
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: Trueimport time
from sklearn.feature_selection import SequentialFeatureSelectorfrom sklearn.linear_model import LogisticRegressionfrom sklearn.model_selection import train_test_splitfrom sklearn.pipeline import make_pipelinefrom 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 namesHint 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 SequentialFeatureSelectorfrom sklearn.linear_model import LogisticRegressionfrom sklearn.model_selection import train_test_splitfrom sklearn.pipeline import make_pipelinefrom 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"]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: TrueHow it works:
- Forward selection starts empty and adds the best feature 4 times: 13 + 12 + 11 + 10 = 46 candidate subsets, each scored with 3-fold CV.
- 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.
- 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.
get_dummieson 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.
Challenge
Section titled “Challenge”M33-X01 · Out-of-fold target encoding by hand
Section titled “M33-X01 · Out-of-fold target encoding by hand”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)).
naive: train 0.900 test 0.668out-of-fold: train 0.787 test 0.782from sklearn.linear_model import LogisticRegressionfrom sklearn.metrics import roc_auc_scorefrom sklearn.model_selection import StratifiedKFold, train_test_splitfrom sklearn.pipeline import make_pipelinefrom 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 bothHint 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 LogisticRegressionfrom sklearn.metrics import roc_auc_scorefrom sklearn.model_selection import StratifiedKFold, train_test_splitfrom sklearn.pipeline import make_pipelinefrom 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.15assert abs(oof[0] - oof[1]) < 0.02naive: train 0.900 test 0.668out-of-fold: train 0.787 test 0.782How it works:
smoothed_mapwithm=0is 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).oof_encodeencodes 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.- The test rows are encoded with means from all training rows, exactly as
TargetEncoder.transformdoes. 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”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.
refund_amount 0.845tenure_months 0.746support_tickets 0.625logins_last_30d 0.580monthly_charges 0.575nps_score 0.574has_autopay 0.540newsletter_opt_in 0.501dtype: float64share with a refund: {0: 0.0, 1: 0.691}all candidates hold-out ROC-AUC 0.937without refund_amount hold-out ROC-AUC 0.783from sklearn.linear_model import LogisticRegressionfrom sklearn.metrics import roc_auc_scorefrom sklearn.model_selection import train_test_splitfrom sklearn.pipeline import make_pipelinefrom 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 leakHint 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 LogisticRegressionfrom sklearn.metrics import roc_auc_scorefrom sklearn.model_selection import train_test_splitfrom sklearn.pipeline import make_pipelinefrom 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.05refund_amount 0.845tenure_months 0.746support_tickets 0.625logins_last_30d 0.580monthly_charges 0.575nps_score 0.574has_autopay 0.540newsletter_opt_in 0.501dtype: float64share with a refund: {0: 0.0, 1: 0.691}all candidates hold-out ROC-AUC 0.937without refund_amount hold-out ROC-AUC 0.783How it works:
refund_amountalone beats every real driver, includingtenure_months. That alone is suspicious.- 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.
nps_scoreis related to churn through logins and tickets, but the survey comes before the decision, so it is a legitimate feature.newsletter_opt_inscores 0.5: no signal. The honest model dropsrefund_amountand 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”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.
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.791from sklearn.feature_selection import SelectKBest, f_classiffrom sklearn.linear_model import LogisticRegressionfrom sklearn.model_selection import StratifiedKFold, cross_val_scorefrom sklearn.pipeline import make_pipelinefrom 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 featuresHint 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_classiffrom sklearn.linear_model import LogisticRegressionfrom sklearn.model_selection import StratifiedKFold, cross_val_scorefrom sklearn.pipeline import make_pipelinefrom 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 > safenoise picked on all rows: 8 of 10(a) select before CV: 0.863(b) select inside CV: 0.709(c) real features only: 0.791How it works:
- 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.
- 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.
- 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”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.
centered_3 MAE 10.47 R2 0.693trailing_3 MAE 17.34 R2 0.062 units centered_3 trailing_3order_date2024-07-09 24 36.7 39.72024-07-10 49 44.0 32.72024-07-11 59 51.7 36.7from sklearn.linear_model import LinearRegressionfrom 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 featureHint 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 LinearRegressionfrom 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.4centered_3 MAE 10.47 R2 0.693trailing_3 MAE 17.34 R2 0.062 units centered_3 trailing_3order_date2024-07-09 24 36.7 39.72024-07-10 49 44.0 32.72024-07-11 59 51.7 36.7How it works:
- 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.
- 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.
- The printed rows make it concrete: for 2024-07-10,
centered_3includes 2024-07-11, a day that has not happened when you forecast 2024-07-10. Any rolling, expanding orbfilloperation 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”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)):
new_customer = exp(−tenure_months / 5)(hypothesis: churn risk fades over the first months);low_logins= 1 whenlogins_last_30d <= 3;high_charges= 1 whenmonthly_charges > 85;mtm_x_tickets= month-to-month flag ×support_tickets;age_gap = |age − 45|.
Then say which features earned their place. The cross-validated gain is the test of each hypothesis.
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)from sklearn.linear_model import LogisticRegressionfrom sklearn.model_selection import StratifiedKFold, cross_val_scorefrom sklearn.pipeline import make_pipelinefrom 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 eachHint 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 LogisticRegressionfrom sklearn.model_selection import StratifiedKFold, cross_val_scorefrom sklearn.pipeline import make_pipelinefrom 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.03baseline 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:
- 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.
- 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.
- Verdict:
low_logins,age_gapandnew_customerearn their place with clear gains.mtm_x_ticketsadds a small gain that is not consistent: a per-fold check shows it helps in 4 of 5 folds and hurts in one.high_chargesadds almost nothing:monthly_chargesand 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.