Skip to content

34. The scikit-learn workflow — Exercises

These exercises practice every idea of the scikit-learn workflow lesson. Almost all of them use the churn data in data/customers.csv (see the data dictionary). One challenge uses data/houses.csv.

How to work:

  1. Read the task and the expected output.
  2. Copy the setup block and the starter code into one script and replace each to-do comment with your code.
  3. Run the script and 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.

Run this block before each exercise. It loads the customers and makes the 75/25 stratified split of the lesson.

import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer, make_column_selector
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import (
StratifiedKFold,
cross_val_score,
cross_validate,
train_test_split,
)
from sklearn.pipeline import Pipeline, make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
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")
X = customers.drop(columns=["customer_id", "signup_date", "churned"])
y = customers["churned"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=42
)
NUMERIC = ["age", "has_autopay", "tenure_months", "monthly_charges", "total_charges",
"support_tickets", "logins_last_30d", "avg_session_minutes"]
TEXT = ["region", "plan", "contract", "payment_method"]
skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)

M34-W01 · Fit a scaler and read what it learned

Section titled “M34-W01 · Fit a scaler and read what it learned”
Warm-up

Fit a StandardScaler on the training rows of tenure_months and monthly_charges. Print the learned means and standard deviations rounded to 2 decimals. Then transform the first test row and print it rounded to 2 decimals.

Expected output
mean_ : [23.31 60.78]
scale_: [19.87 22.99]
first test row: [[-0.62 -0.11]]
Starter
cols = ["tenure_months", "monthly_charges"]
scaler = StandardScaler()
# TODO: fit on X_train[cols]
# TODO: print mean_ and scale_ rounded to 2 decimals
# TODO: transform X_test[cols].head(1) and print it rounded
Hint 1

fit() stores mean_ and scale_ on the scaler. They are NumPy arrays, so .round(2) works on them.

Hint 2

scaler.transform(X_test[cols].head(1)) returns a 2-D array with one row.

Solution
cols = ["tenure_months", "monthly_charges"]
scaler = StandardScaler()
scaler.fit(X_train[cols])
print("mean_ :", scaler.mean_.round(2))
print("scale_:", scaler.scale_.round(2))
first = scaler.transform(X_test[cols].head(1))
print("first test row:", first.round(2))
assert scaler.n_features_in_ == 2
assert np.allclose(first, (X_test[cols].head(1) - scaler.mean_) / scaler.scale_)
Output
mean_ : [23.31 60.78]
scale_: [19.87 22.99]
first test row: [[-0.62 -0.11]]

How it works:

  1. fit() computes one mean and one standard deviation per column from the 3,750 training rows and stores them in the learned attributes mean_ and scale_.
  2. transform() applies z=(x−mean)/scalez = (x - \text{mean}) / \text{scale} with those stored values. The test row never changes them.
  3. The second assert recomputes the formula by hand with pandas broadcasting, which proves what transform() does.

Alternative: scaler.set_output(transform="pandas") before fit() makes transform() return a DataFrame with the column names, which is easier to read for one row.

M34-W02 · Sort hyperparameters from learned attributes

Section titled “M34-W02 · Sort hyperparameters from learned attributes”
Warm-up

Fit LogisticRegression(max_iter=1000) on the training rows of tenure_months and support_tickets. Print how many hyperparameters it has, and print the sorted list of its public learned attributes (names that end with _ and do not start with _).

Expected output
hyperparameters: 14
learned: ['classes_', 'coef_', 'feature_names_in_', 'intercept_', 'n_features_in_', 'n_iter_']
Starter
cols = ["tenure_months", "support_tickets"]
model = LogisticRegression(max_iter=1000)
# TODO: fit the model
# TODO: count the hyperparameters with get_params()
# TODO: find the learned attributes in vars(model)
Hint 1

model.get_params() returns a dict of hyperparameters. vars(model) returns a dict of every attribute.

Hint 2

sorted(k for k in vars(model) if k.endswith("_") and not k.startswith("_"))

Solution
cols = ["tenure_months", "support_tickets"]
model = LogisticRegression(max_iter=1000)
model.fit(X_train[cols], y_train)
hyper = model.get_params()
learned = sorted(k for k in vars(model) if k.endswith("_") and not k.startswith("_"))
print("hyperparameters:", len(hyper))
print("learned:", learned)
assert "C" in hyper and "C_" not in learned
assert set(hyper).isdisjoint(learned)
Output
hyperparameters: 14
learned: ['classes_', 'coef_', 'feature_names_in_', 'intercept_', 'n_features_in_', 'n_iter_']

How it works:

  1. get_params() reads the names of the __init__ arguments, so it lists only hyperparameters.
  2. fit() adds the learned attributes. Because the model was fitted on a DataFrame, it also stored feature_names_in_.
  3. The second assert checks that the two groups never share a name, which is the point of the underscore convention.

Alternative: compare vars(LogisticRegression()) with vars(model). The keys that appear only after fit() are the learned attributes.

M34-W03 · Predict the output: set_params and clone

Section titled “M34-W03 · Predict the output: set_params and clone”
Warm-up

Predict the output: read the code and write down the four lines it prints. Then run it.

Starter
from sklearn.base import clone
model = LogisticRegression(C=0.5)
same = model.set_params(max_iter=300)
copy = clone(model)
copy.set_params(C=5.0)
print(same is model)
print(model)
print(copy)
print(copy is model, copy.get_params()["max_iter"])

Acceptance criteria:

  • Write your prediction line by line, then run the code. Your prediction matches the Output in the solution.
  • You can explain each line with the words “returns self”, “unchanged copy” and “independent object”.
Hint 1

set_params() changes the estimator in place and returns it.

Hint 2

clone() copies the hyperparameters into a new object. Changing the copy leaves the original alone. print() shows only the hyperparameters that differ from their defaults.

Solution
from sklearn.base import clone
model = LogisticRegression(C=0.5)
same = model.set_params(max_iter=300)
copy = clone(model)
copy.set_params(C=5.0)
print(same is model)
print(model)
print(copy)
print(copy is model, copy.get_params()["max_iter"])
assert model.C == 0.5 and copy.C == 5.0
Output
True
LogisticRegression(C=0.5, max_iter=300)
LogisticRegression(C=5.0, max_iter=300)
False 300

How it works:

  1. set_params(max_iter=300) changes model and returns the same object, so same is model is True.
  2. print(model) shows C=0.5 and max_iter=300, the two values that differ from the defaults.
  3. clone(model) builds a new object with the same hyperparameters. copy.set_params(C=5.0) changes only the copy, which still has max_iter=300.

Alternative: copy.deepcopy(model) also copies, but it copies learned attributes too. clone() is the right tool when you want an unfitted copy for a new fit.

Warm-up

Split X and y into 80% training and 20% test rows, stratified on y, with random_state=7. Print the shapes of the two feature tables and the churn rate of each part to 4 decimals.

Expected output
(4000, 12) (1000, 12)
train churn 0.1925 test churn 0.1930
Starter
# TODO: split X and y with test_size=0.2, stratify=y, random_state=7
# TODO: print the two shapes and the two churn rates
Hint 1

train_test_split(X, y, test_size=0.2, stratify=y, random_state=7) returns four objects.

Hint 2

The order is X_tr, X_te, y_tr, y_te. The churn rate is the mean of a 0/1 column.

Solution
X_tr, X_te, y_tr, y_te = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=7
)
print(X_tr.shape, X_te.shape)
print(f"train churn {y_tr.mean():.4f} test churn {y_te.mean():.4f}")
assert len(X_tr) == 4000 and len(X_te) == 1000
assert abs(y_tr.mean() - y_te.mean()) < 0.001
assert (X_te.index == y_te.index).all()
Output
(4000, 12) (1000, 12)
train churn 0.1925 test churn 0.1930

How it works:

  1. 20% of 5,000 rows is 1,000 test rows.
  2. stratify=y puts 193 of the 963 churners in the test set and the rest in the training set, so both rates stay at about 19.26%.
  3. The last assert checks that the features and labels of each row stayed together.

Alternative: StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=7) from sklearn.model_selection gives the same kind of split as row positions, which is useful when you want several random splits in a loop.

M34-W05 · Fix the bug: the scaler that saw the test set

Section titled “M34-W05 · Fix the bug: the scaler that saw the test set”
Warm-up

Fix the bug: this code scales the test rows with their own mean and standard deviation. Change it so that the test rows use what the scaler learned from the training rows. Print the mean of the scaled test column, rounded to 3 decimals. A correct test mean is close to 0, but not exactly 0.

Expected output
scaled test mean: -0.002
Starter
cols = ["logins_last_30d"]
scaler = StandardScaler()
train_scaled = scaler.fit_transform(X_train[cols])
test_scaled = scaler.fit_transform(X_test[cols]) # TODO: fix this line
print(f"scaled test mean: {test_scaled.mean():.3f}")
Hint 1

fit_transform() refits the scaler. On test data, you want only the second half of that call.

Hint 2

After the fix, the scaler’s mean_ must still equal the training mean.

Solution
cols = ["logins_last_30d"]
scaler = StandardScaler()
train_scaled = scaler.fit_transform(X_train[cols])
test_scaled = scaler.transform(X_test[cols])
print(f"scaled test mean: {test_scaled.mean():.3f}")
assert np.isclose(scaler.mean_[0], X_train["logins_last_30d"].mean())
assert not np.isclose(test_scaled.mean(), 0.0)
Output
scaled test mean: -0.002

How it works:

  1. fit_transform() on the training rows learns the training mean and standard deviation.
  2. transform() on the test rows reuses them. The test mean is then a small non-zero number, because the test rows are a different sample.
  3. The buggy version gave a test mean of exactly 0, which looks perfect and is wrong: the scaler had learned from the test rows, and the training and test values were on different scales.

Alternative: put the scaler in a pipeline, make_pipeline(StandardScaler(), model). The pipeline calls the right method on each set of rows for you.

M34-W06 · Predict the output: the steps of make_pipeline

Section titled “M34-W06 · Predict the output: the steps of make_pipeline”
Warm-up

Predict the output: write down the three lines this code prints. Then run it.

Starter
pipe = make_pipeline(
SimpleImputer(strategy="median"), StandardScaler(), LogisticRegression()
)
print([name for name, _ in pipe.steps])
print(type(pipe[:-1]).__name__, len(pipe[:-1]))
print(pipe["standardscaler"] is pipe[1])

Acceptance criteria:

  • Write your prediction line by line, then run the code. Your prediction matches the Output in the solution.
Hint 1

make_pipeline names each step after its class, in lowercase.

Hint 2

Slicing a pipeline returns a new pipeline. Indexing by name or by position returns the step object itself.

Solution
pipe = make_pipeline(
SimpleImputer(strategy="median"), StandardScaler(), LogisticRegression()
)
print([name for name, _ in pipe.steps])
print(type(pipe[:-1]).__name__, len(pipe[:-1]))
print(pipe["standardscaler"] is pipe[1])
assert list(pipe.named_steps)[-1] == "logisticregression"
Output
['simpleimputer', 'standardscaler', 'logisticregression']
Pipeline 2
True

How it works:

  1. pipe.steps is a list of (name, estimator) pairs, and the names are the lowercase class names.
  2. pipe[:-1] is a Pipeline with every step except the model, so its length is 2.
  3. pipe["standardscaler"] and pipe[1] are two ways to reach the same scaler object.

Alternative: build a Pipeline([("impute", ...), ("scale", ...), ("model", ...)]) to choose short names yourself.

M34-W07 · Route three parameters with one call

Section titled “M34-W07 · Route three parameters with one call”
Warm-up

The pipeline below has the steps impute, scale and model. In one set_params() call, set the imputer strategy to "most_frequent", turn off centering in the scaler (with_mean=False) and set C of the model to 0.2. Print the three values from get_params().

Expected output
impute__strategy = most_frequent
scale__with_mean = False
model__C = 0.2
Starter
pipe = Pipeline([
("impute", SimpleImputer()),
("scale", StandardScaler()),
("model", LogisticRegression()),
])
# TODO: one set_params() call with three step__parameter names
# TODO: print the three values
Hint 1

The name is the step name, two underscores and the parameter name.

Hint 2

pipe.set_params(impute__strategy="most_frequent", ...)

Solution
pipe = Pipeline([
("impute", SimpleImputer()),
("scale", StandardScaler()),
("model", LogisticRegression()),
])
pipe.set_params(impute__strategy="most_frequent", scale__with_mean=False, model__C=0.2)
params = pipe.get_params()
for name in ["impute__strategy", "scale__with_mean", "model__C"]:
print(f"{name} = {params[name]}")
assert pipe["model"].C == 0.2 and pipe["scale"].with_mean is False
Output
impute__strategy = most_frequent
scale__with_mean = False
model__C = 0.2

How it works:

  1. The pipeline splits each name at the first __: the left part names the step, and the rest goes to that step’s set_params().
  2. get_params() on the pipeline returns the nested names in the same format, so you can read the values back.
  3. The assert checks the step objects themselves, which proves the values reached them.

Alternative: pipe["model"].set_params(C=0.2) changes one step directly. The __ form is the one that tools such as GridSearchCV use, so learn it.

M34-W08 · Report a CV score as mean ± std

Section titled “M34-W08 · Report a CV score as mean ± std”
Warm-up

Cross-validate make_pipeline(StandardScaler(), LogisticRegression()) on the training rows of tenure_months, logins_last_30d, support_tickets and monthly_charges. Use the setup’s skf and scoring="roc_auc". Print the five fold scores and a line ROC-AUC 0.xxx ± 0.xxx.

Expected output
[0.774 0.776 0.786 0.8 0.759]
ROC-AUC 0.779 ± 0.014
Starter
cols = ["tenure_months", "logins_last_30d", "support_tickets", "monthly_charges"]
pipe = make_pipeline(StandardScaler(), LogisticRegression())
# TODO: scores = cross_val_score(...)
# TODO: print the fold scores and the mean ± std line
Hint 1

cross_val_score(pipe, X_train[cols], y_train, cv=skf, scoring="roc_auc")

Hint 2

scores.mean() and scores.std() give the two numbers. Format them with :.3f.

Solution
cols = ["tenure_months", "logins_last_30d", "support_tickets", "monthly_charges"]
pipe = make_pipeline(StandardScaler(), LogisticRegression())
scores = cross_val_score(pipe, X_train[cols], y_train, cv=skf, scoring="roc_auc")
print(scores.round(3))
print(f"ROC-AUC {scores.mean():.3f} ± {scores.std():.3f}")
assert len(scores) == 5
assert 0.5 < scores.mean() < 1.0
assert not hasattr(pipe[-1], "coef_") # cross_val_score fitted clones, not pipe
Output
[0.774 0.776 0.786 0.8 0.759]
ROC-AUC 0.779 ± 0.014

How it works:

  1. cross_val_score clones the pipeline 5 times, fits each clone on 4 folds and scores it on the fifth.
  2. The scaler is refitted inside each fold, so no fold leaks into its own preprocessing.
  3. The last assert shows that pipe itself stays unfitted: only the clones were trained.

Alternative: cross_validate(pipe, ..., scoring="roc_auc")["test_score"] returns the same five numbers plus fit and score times.

Warm-up

Fit a OneHotEncoder(sparse_output=False) on the training rows of plan and contract. Print the number of output columns and the output feature names as a list.

Expected output
6 columns
['plan_basic', 'plan_premium', 'plan_standard']
['contract_month-to-month', 'contract_one-year', 'contract_two-year']
Starter
encoder = OneHotEncoder(sparse_output=False)
# TODO: fit on X_train[["plan", "contract"]]
# TODO: print the number of output columns and get_feature_names_out() as a list
Hint 1

encoder.get_feature_names_out() returns an array of names after fit().

Hint 2

Each name is <column>_<category>, and the categories are sorted.

Solution
encoder = OneHotEncoder(sparse_output=False)
encoder.fit(X_train[["plan", "contract"]])
names = encoder.get_feature_names_out().tolist()
print(len(names), "columns")
print(names[:3])
print(names[3:])
assert names[0] == "plan_basic"
assert encoder.transform(X_test[["plan", "contract"]]).sum(axis=1).max() == 2
Output
6 columns
['plan_basic', 'plan_premium', 'plan_standard']
['contract_month-to-month', 'contract_one-year', 'contract_two-year']

How it works:

  1. plan has 3 categories and contract has 3, so the encoder makes 6 columns.
  2. The names join the input column and the category with _, in sorted order within each column.
  3. Each row has exactly one 1 per input column, so every row sums to 2. The last assert checks this on the test rows.

Alternative: inside a ColumnTransformer, the names get a branch prefix, such as cat__plan_basic, unless you pass verbose_feature_names_out=False.

M34-C01 · Build a ColumnTransformer with explicit lists

Section titled “M34-C01 · Build a ColumnTransformer with explicit lists”
Core

Build a ColumnTransformer with two branches: num imputes the setup’s NUMERIC columns with the median and scales them, and cat one-hot encodes the TEXT columns (handle_unknown="ignore", sparse_output=False). Fit it on X_train, then print the shape of the transformed test rows, the number of columns per branch and the first 3 output names.

Expected output
test shape: (1250, 22)
num: 8 cat: 14
['num__age', 'num__has_autopay', 'num__tenure_months']
Starter
preprocess = ColumnTransformer([
# TODO: ("num", ..., NUMERIC)
# TODO: ("cat", ..., TEXT)
])
# TODO: fit on X_train, transform X_test, print the shape
# TODO: count the names that start with "num__" and with "cat__"
Hint 1

The numeric branch is a small pipeline: make_pipeline(SimpleImputer(strategy="median"), StandardScaler()).

Hint 2

preprocess.get_feature_names_out() returns names such as num__age and cat__plan_basic. Count them with str.startswith.

Solution
preprocess = ColumnTransformer([
("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), NUMERIC),
("cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False), TEXT),
])
preprocess.fit(X_train)
Xt_test = preprocess.transform(X_test)
names = preprocess.get_feature_names_out()
n_num = sum(name.startswith("num__") for name in names)
n_cat = sum(name.startswith("cat__") for name in names)
print("test shape:", Xt_test.shape)
print("num:", n_num, " cat:", n_cat)
print(names[:3].tolist())
assert Xt_test.shape == (1250, n_num + n_cat)
assert not np.isnan(Xt_test).any()
Output
test shape: (1250, 22)
num: 8 cat: 14
['num__age', 'num__has_autopay', 'num__tenure_months']

How it works:

  1. Each branch is a (name, transformer, columns) triple. The numeric branch is a pipeline, which a column transformer accepts like any transformer.
  2. fit() learns the medians, means, standard deviations and categories from X_train only. transform() applies them to the test rows.
  3. 8 numeric columns stay 8 columns, and 4 text columns become 14 one-hot columns. The second assert proves that the imputer filled the missing total_charges.

Alternative: make_column_transformer((numeric_steps, NUMERIC), (encoder, TEXT)) builds the same object with automatic branch names (pipeline and onehotencoder).

M34-C02 · Select columns by dtype and by name pattern

Section titled “M34-C02 · Select columns by dtype and by name pattern”
Core

Use make_column_selector three ways on X_train: the numeric columns, the text columns, and the columns whose name ends with charges (a regular expression). Print each list. Then check that dtype_exclude="number" selects the same columns as dtype_include="str".

Expected output
numeric: 8 columns
text: ['region', 'plan', 'contract', 'payment_method']
charges: ['monthly_charges', 'total_charges']
same text columns: True
Starter
# TODO: pick_num = make_column_selector(dtype_include="number")
# TODO: pick_text = make_column_selector(...)
# TODO: pick_charges = make_column_selector(pattern=...)
# TODO: print the three lists and compare with dtype_exclude="number"
Hint 1

A selector is an object that you call with a DataFrame: pick_num(X_train).

Hint 2

The regular expression "charges$" matches names that end with charges. In pandas 3, text columns have the dtype "str".

Solution
pick_num = make_column_selector(dtype_include="number")
pick_text = make_column_selector(dtype_include="str")
pick_charges = make_column_selector(pattern="charges$")
print("numeric:", len(pick_num(X_train)), "columns")
print("text: ", pick_text(X_train))
print("charges:", pick_charges(X_train))
not_numbers = make_column_selector(dtype_exclude="number")(X_train)
print("same text columns:", not_numbers == pick_text(X_train))
assert sorted(pick_num(X_train)) == sorted(NUMERIC)
assert pick_text(X_train) == TEXT
Output
numeric: 8 columns
text: ['region', 'plan', 'contract', 'payment_method']
charges: ['monthly_charges', 'total_charges']
same text columns: True

How it works:

  1. dtype_include="number" matches every integer and float column.
  2. dtype_include="str" matches the pandas 3 text columns. The older dtype_include=object still works in pandas 3 but warns that it is deprecated.
  3. pattern= runs re.search on each column name. Selectors keep the column order of the DataFrame.

Alternative: pass dtype_include="number", pattern="^(?!total)" to combine both filters: numeric columns whose name does not start with total.

M34-C03 · Read the model’s coefficients by name

Section titled “M34-C03 · Read the model’s coefficients by name”
Core

Build the full churn pipeline: a column transformer like in M34-C01 with verbose_feature_names_out=False, then LogisticRegression(max_iter=1000). Fit it on the training rows. Put the coefficients in a Series indexed by feature name and print the 3 most negative and the 3 most positive ones, rounded to 3 decimals.

Expected output
lower churn:
tenure_months -0.911
contract_two-year -0.815
logins_last_30d -0.278
dtype: float64
higher churn:
monthly_charges 0.449
support_tickets 0.544
contract_month-to-month 0.949
dtype: float64
Starter
preprocess = ColumnTransformer(
[
# TODO: the two branches
],
verbose_feature_names_out=False,
)
model = Pipeline([("prep", preprocess), ("model", LogisticRegression(max_iter=1000))])
# TODO: fit, build the Series, sort it, print head(3) and tail(3)
Hint 1

model[:-1].get_feature_names_out() gives the names in the order of model[-1].coef_[0].

Hint 2

pd.Series(values, index=names).sort_values(); then head(3) and tail(3).

Solution
preprocess = ColumnTransformer(
[
("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()),
NUMERIC),
("cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False), TEXT),
],
verbose_feature_names_out=False,
)
model = Pipeline([("prep", preprocess), ("model", LogisticRegression(max_iter=1000))])
model.fit(X_train, y_train)
coefs = pd.Series(model[-1].coef_[0], index=model[:-1].get_feature_names_out())
coefs = coefs.sort_values()
print("lower churn:")
print(coefs.head(3).round(3))
print("higher churn:")
print(coefs.tail(3).round(3))
assert coefs.index[-1] == "contract_month-to-month"
assert len(coefs) == 22
Output
lower churn:
tenure_months -0.911
contract_two-year -0.815
logins_last_30d -0.278
dtype: float64
higher churn:
monthly_charges 0.449
support_tickets 0.544
contract_month-to-month 0.949
dtype: float64

How it works:

  1. verbose_feature_names_out=False removes the num__ and cat__ prefixes. This is safe here because no two branches produce the same name.
  2. The pipeline slice model[:-1] is the fitted preprocessing, so its names match the columns the model saw.
  3. On standardized features, a negative coefficient lowers the churn probability and a positive one raises it. A month-to-month contract is the strongest churn signal, as in the data dictionary.

Alternative: model.named_steps["model"].coef_ and model.named_steps["prep"].get_feature_names_out() reach the same objects by name instead of position.

M34-C04 · Keep DataFrames through the pipeline

Section titled “M34-C04 · Keep DataFrames through the pipeline”
Core

Build the preprocessing of M34-C01 and call set_output(transform="pandas") before fitting it. Transform the test rows and check that the result is a DataFrame with the same index as X_test. Print its shape, its first 4 column names, and the num__tenure_months and cat__contract_two-year values of customer index 3185.

Expected output
DataFrame (1250, 22)
['num__age', 'num__has_autopay', 'num__tenure_months', 'num__monthly_charges']
num__tenure_months -0.62
cat__contract_two-year 0.00
Name: 3185, dtype: float64
Starter
preprocess = ColumnTransformer([
# TODO: the two branches of M34-C01
])
# TODO: preprocess.set_output(transform="pandas"), then fit on X_train
# TODO: Xt = preprocess.transform(X_test); print shape, columns[:4] and Xt.loc[3185, ...]
Hint 1

set_output() returns the estimator, so you can write preprocess.set_output(transform="pandas").fit(X_train).

Hint 2

Xt.loc[3185, ["num__tenure_months", "cat__contract_two-year"]] selects one row and two columns.

Solution
preprocess = ColumnTransformer([
("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), NUMERIC),
("cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False), TEXT),
])
preprocess.set_output(transform="pandas").fit(X_train)
Xt = preprocess.transform(X_test)
print(type(Xt).__name__, Xt.shape)
print(Xt.columns[:4].tolist())
print(Xt.loc[3185, ["num__tenure_months", "cat__contract_two-year"]].round(3))
assert Xt.index.equals(X_test.index)
assert list(Xt.columns) == list(preprocess.get_feature_names_out())
Output
DataFrame (1250, 22)
['num__age', 'num__has_autopay', 'num__tenure_months', 'num__monthly_charges']
num__tenure_months -0.62
cat__contract_two-year 0.00
Name: 3185, dtype: float64

How it works:

  1. set_output() on the column transformer reaches every step inside it, including the inner pipeline.
  2. The output keeps the index of X_test, so you can look up a customer by id in the transformed data.
  3. Customer 3185 has a short tenure (a negative z-score) and no two-year contract (0.0).

Alternative: sklearn.set_config(transform_output="pandas") switches pandas output on for every estimator in the script. A local set_output() call is clearer and does not surprise other code.

M34-C05 · Refactor hand-written preprocessing into a Pipeline

Section titled “M34-C05 · Refactor hand-written preprocessing into a Pipeline”
Core

Refactor: the code in the starter imputes, scales and fits a model by hand. Rewrite it as a Pipeline with the steps impute, scale and model. Check that both versions give the same test probabilities, and print the first 3 probabilities of churn and the test accuracy.

Expected output
first probabilities: [0.16 0.186 0.087]
test accuracy: 0.819
same as manual: True
Starter
cols = ["tenure_months", "total_charges", "support_tickets"]
imputer = SimpleImputer(strategy="median").fit(X_train[cols])
scaler = StandardScaler().fit(imputer.transform(X_train[cols]))
Xt_train = scaler.transform(imputer.transform(X_train[cols]))
clf = LogisticRegression().fit(Xt_train, y_train)
manual = clf.predict_proba(scaler.transform(imputer.transform(X_test[cols])))[:, 1]
# TODO: pipe = Pipeline([...]); fit on the training rows
# TODO: compare pipe.predict_proba(X_test[cols])[:, 1] with manual
Hint 1

The pipeline steps are the same three objects, created fresh, in the same order.

Hint 2

np.allclose(manual, piped) compares two arrays of floats.

Solution
cols = ["tenure_months", "total_charges", "support_tickets"]
imputer = SimpleImputer(strategy="median").fit(X_train[cols])
scaler = StandardScaler().fit(imputer.transform(X_train[cols]))
Xt_train = scaler.transform(imputer.transform(X_train[cols]))
clf = LogisticRegression().fit(Xt_train, y_train)
manual = clf.predict_proba(scaler.transform(imputer.transform(X_test[cols])))[:, 1]
pipe = Pipeline([
("impute", SimpleImputer(strategy="median")),
("scale", StandardScaler()),
("model", LogisticRegression()),
])
pipe.fit(X_train[cols], y_train)
piped = pipe.predict_proba(X_test[cols])[:, 1]
print("first probabilities:", piped[:3].round(3))
print(f"test accuracy: {pipe.score(X_test[cols], y_test):.3f}")
print("same as manual:", np.allclose(manual, piped))
assert np.allclose(manual, piped)
assert np.allclose(pipe["impute"].statistics_, imputer.statistics_)
Output
first probabilities: [0.16 0.186 0.087]
test accuracy: 0.819
same as manual: True

How it works:

  1. The pipeline runs fit_transform for the imputer and the scaler, then fit for the model, exactly like the hand-written chain.
  2. At prediction time, it runs transform with the stored values. The probabilities match to the last digit.
  3. The pipeline replaces a chain of method calls and three separate objects with one object that you can cross-validate, tune and save.

Alternative: make_pipeline(SimpleImputer(strategy="median"), StandardScaler(), LogisticRegression()) builds the same pipeline with automatic step names.

M34-C06 · Compare the folds of KFold and StratifiedKFold

Section titled “M34-C06 · Compare the folds of KFold and StratifiedKFold”
Core

With 10 folds (shuffle=True, random_state=42), compute the churn rate of each scoring fold on the whole data (X, y) for KFold and for StratifiedKFold. For each splitter, print the lowest and highest fold churn rate and their difference, to 3 decimals.

Expected output
KFold min 0.160 max 0.210 spread 0.050
StratifiedKFold min 0.192 max 0.194 spread 0.002
Starter
from sklearn.model_selection import KFold
splitters = {
"KFold": KFold(n_splits=10, shuffle=True, random_state=42),
# TODO: add StratifiedKFold with the same settings
}
for name, cv in splitters.items():
# TODO: rates = churn rate of y for each test fold
# TODO: print min, max and the spread
pass
Hint 1

cv.split(X, y) yields (train_positions, test_positions) pairs. y.iloc[test_positions].mean() is a fold’s churn rate.

Hint 2

KFold.split() accepts y and ignores it, so the same loop works for both splitters.

Solution
from sklearn.model_selection import KFold
splitters = {
"KFold": KFold(n_splits=10, shuffle=True, random_state=42),
"StratifiedKFold": StratifiedKFold(n_splits=10, shuffle=True, random_state=42),
}
spreads = {}
for name, cv in splitters.items():
rates = np.array([y.iloc[test].mean() for _, test in cv.split(X, y)])
spreads[name] = rates.max() - rates.min()
print(f"{name:<16} min {rates.min():.3f} max {rates.max():.3f} "
f"spread {spreads[name]:.3f}")
assert spreads["StratifiedKFold"] < spreads["KFold"]
assert spreads["StratifiedKFold"] < 0.005
Output
KFold min 0.160 max 0.210 spread 0.050
StratifiedKFold min 0.192 max 0.194 spread 0.002

How it works:

  1. Each fold has 500 customers. KFold picks them at random, so one fold can have many more churners than another.
  2. StratifiedKFold deals the churners and the non-churners out separately, so every fold has 96 or 97 churners.
  3. Stable fold populations make the fold scores comparable, which makes the standard deviation of a CV score smaller and more honest.

Alternative: np.bincount(y.iloc[test]) shows the count of each class per fold instead of the rate.

M34-C07 · Cross-validate four metrics at once

Section titled “M34-C07 · Cross-validate four metrics at once”
Core

Cross-validate the churn pipeline of M34-C03 on the training rows with skf and four metrics, named in a dict: acc (accuracy), auc (ROC-AUC), prec (precision) and rec (recall). Print a table with the mean and the standard deviation of each test metric, rounded to 3 decimals. Then print which metric is the lowest.

Expected output
test_acc test_auc test_prec test_rec
mean 0.836 0.813 0.669 0.288
std 0.011 0.013 0.065 0.043
lowest: test_rec
Starter
model = ... # TODO: the pipeline of M34-C03
scoring = {"acc": "accuracy", "auc": "roc_auc", "prec": "precision", "rec": "recall"}
# TODO: results = cross_validate(model, X_train, y_train, cv=skf, scoring=scoring)
# TODO: keep the test_ columns, aggregate mean and std, print
Hint 1

With a dict, the result keys are test_acc, test_auc, test_prec and test_rec.

Hint 2

pd.DataFrame(results).filter(like="test_").agg(["mean", "std"])

Solution
preprocess = ColumnTransformer([
("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), NUMERIC),
("cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False), TEXT),
])
model = Pipeline([("prep", preprocess), ("model", LogisticRegression(max_iter=1000))])
scoring = {"acc": "accuracy", "auc": "roc_auc", "prec": "precision", "rec": "recall"}
results = cross_validate(model, X_train, y_train, cv=skf, scoring=scoring)
table = pd.DataFrame(results).filter(like="test_").agg(["mean", "std"])
print(table.round(3))
lowest = table.loc["mean"].idxmin()
print("lowest:", lowest)
assert lowest == "test_rec"
assert table.loc["mean", "test_acc"] > 0.807 # beats "nobody churns"
Output
test_acc test_auc test_prec test_rec
mean 0.836 0.813 0.669 0.288
std 0.011 0.013 0.065 0.043
lowest: test_rec

How it works:

  1. A dict in scoring gives each metric your own short name. cross_validate computes all four on each fold from one fit.
  2. Precision is the share of predicted churners who really churn. Recall is the share of real churners the model finds. Both use the default threshold of 0.5.
  3. Recall is the lowest: the model finds only about 3 in 10 churners. Accuracy hides this, because most customers stay. Module 36 shows how a lower threshold trades precision for recall.

Alternative: pass a list, scoring=["accuracy", "roc_auc", "precision", "recall"], to use the scikit-learn names as keys (test_accuracy, and so on).

M34-C08 · Interpret training versus test scores

Section titled “M34-C08 · Interpret training versus test scores”
Core

Interpret a result: cross-validate make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=k)) on four numeric columns for k in 1, 15 and 101, with return_train_score=True and accuracy. Print the mean training and test accuracy for each k. Then decide in code which k overfits the most (the largest gap between training and test accuracy).

Expected output
k=1 train 1.000 test 0.747 gap +0.2531
k=15 train 0.822 test 0.806 gap +0.0167
k=101 train 0.808 test 0.809 gap -0.0002
overfits most: k = 1
Starter
from sklearn.neighbors import KNeighborsClassifier
cols = ["tenure_months", "logins_last_30d", "monthly_charges", "avg_session_minutes"]
gaps = {}
for k in [1, 15, 101]:
# TODO: cross_validate with return_train_score=True
# TODO: print k, mean train accuracy, mean test accuracy; store the gap
pass
# TODO: print the k with the largest gap
Hint 1

The result dict has the keys train_score and test_score when you pass one metric.

Hint 2

max(gaps, key=gaps.get) returns the key with the largest value.

Solution
from sklearn.neighbors import KNeighborsClassifier
cols = ["tenure_months", "logins_last_30d", "monthly_charges", "avg_session_minutes"]
gaps = {}
for k in [1, 15, 101]:
pipe = make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=k))
res = cross_validate(pipe, X_train[cols], y_train, cv=skf, return_train_score=True)
train, test = res["train_score"].mean(), res["test_score"].mean()
gaps[k] = train - test
print(f"k={k:<4} train {train:.3f} test {test:.3f} gap {gaps[k]:+.4f}")
worst = max(gaps, key=gaps.get)
print("overfits most: k =", worst)
assert worst == 1
assert gaps[101] < gaps[15] < gaps[1]
Output
k=1 train 1.000 test 0.747 gap +0.2531
k=15 train 0.822 test 0.806 gap +0.0167
k=101 train 0.808 test 0.809 gap -0.0002
overfits most: k = 1

How it works:

  1. With k=1, each training row is its own nearest neighbor, so the training accuracy is about 1.0. The model memorizes the training rows. This is overfitting: a high training score with a much lower test score.
  2. A larger k averages more neighbors. The gap shrinks, and the test accuracy improves.
  3. The test score, not the training score, tells you how the model generalizes. A big train–test gap is the warning sign. A gap at or below 0, as for k=101, means no overfitting: the small negative value is fold-to-fold noise. Module 37 draws this as a validation curve.

Alternative: sklearn.model_selection.validation_curve(pipe, X, y, param_name="kneighborsclassifier__n_neighbors", param_range=[1, 15, 101], cv=skf) computes the same table in one call.

M34-C09 · Log-transform skewed columns with FunctionTransformer

Section titled “M34-C09 · Log-transform skewed columns with FunctionTransformer”
Core

total_charges and monthly_charges are right-skewed. Build FunctionTransformer(np.log1p, feature_names_out="one-to-one") with pandas output and apply it to the training rows of the two columns. Print a table of the skewness before and after (pandas .skew()), rounded to 3 decimals, and the output feature names.

Expected output
before after
total_charges 1.648 -0.601
monthly_charges 0.618 0.098
['total_charges', 'monthly_charges']
Starter
from sklearn.preprocessing import FunctionTransformer
cols = ["total_charges", "monthly_charges"]
log_step = FunctionTransformer(np.log1p, feature_names_out="one-to-one")
# TODO: set pandas output, fit_transform the training rows
# TODO: print a DataFrame with the skew before and after
Hint 1

log_step.set_output(transform="pandas") makes the output a DataFrame with the same column names.

Hint 2

pd.DataFrame({"before": raw.skew(), "after": logged.skew()})

Solution
from sklearn.preprocessing import FunctionTransformer
cols = ["total_charges", "monthly_charges"]
log_step = FunctionTransformer(np.log1p, feature_names_out="one-to-one")
log_step.set_output(transform="pandas")
raw = X_train[cols]
logged = log_step.fit_transform(raw)
print(pd.DataFrame({"before": raw.skew(), "after": logged.skew()}).round(3))
print(log_step.get_feature_names_out().tolist())
assert (logged.skew().abs() < raw.skew().abs()).all()
assert logged["total_charges"].isna().sum() == raw["total_charges"].isna().sum()
Output
before after
total_charges 1.648 -0.601
monthly_charges 0.618 0.098
['total_charges', 'monthly_charges']

How it works:

  1. Skewness measures how lopsided a distribution is: 0 is symmetric, a positive value has a long right tail.
  2. np.log1p compresses large values more than small ones, which pulls the long right tail in. monthly_charges becomes almost symmetric; total_charges overshoots and becomes left-skewed, because many new customers have small totals.
  3. The transformer learns nothing (it is stateless), so fit() does nothing and it is safe anywhere in a pipeline. The missing values stay missing; an imputer must handle them.

Alternative: PowerTransformer(method="yeo-johnson") from sklearn.preprocessing learns the best power transform per column. It is stateful, so it must be fitted on training rows only.

M34-C10 · Write a MinMaxScaler on the scikit-learn base classes

Section titled “M34-C10 · Write a MinMaxScaler on the scikit-learn base classes”
Core

Write MiniMinMaxScaler(OneToOneFeatureMixin, TransformerMixin, BaseEstimator). fit() learns data_min_ and data_max_ per column; transform() maps each column to [0,1][0, 1] with (x−min⁡)/(max⁡−min⁡)(x - \min) / (\max - \min). A constant column must not divide by zero. Check it against sklearn.preprocessing.MinMaxScaler on four numeric columns, and print the learned minimum and maximum, the result of the comparison and the first two output feature names.

Expected output
min: [18. 0. 0. 1.]
max: [80. 72. 8. 68.1]
matches MinMaxScaler: True
['age', 'tenure_months']
Starter
from sklearn.base import BaseEstimator, OneToOneFeatureMixin, TransformerMixin
from sklearn.preprocessing import MinMaxScaler
from sklearn.utils.validation import check_is_fitted, validate_data
class MiniMinMaxScaler(OneToOneFeatureMixin, TransformerMixin, BaseEstimator):
def fit(self, X, y=None):
# TODO: validate X, learn data_min_ and data_max_, return self
...
def transform(self, X):
# TODO: check fitted, validate with reset=False, scale
...
Hint 1

validate_data(self, X, dtype=np.float64) returns a float array and sets n_features_in_. Use X.min(axis=0) and X.max(axis=0).

Hint 2

Replace a zero range with 1: np.where(rng > 0, rng, 1.0).

Solution
from sklearn.base import BaseEstimator, OneToOneFeatureMixin, TransformerMixin
from sklearn.preprocessing import MinMaxScaler
from sklearn.utils.validation import check_is_fitted, validate_data
class MiniMinMaxScaler(OneToOneFeatureMixin, TransformerMixin, BaseEstimator):
"""Scale each column to [0, 1] with the training minimum and maximum."""
def fit(self, X, y=None):
X = validate_data(self, X, dtype=np.float64)
self.data_min_ = X.min(axis=0)
self.data_max_ = X.max(axis=0)
return self
def transform(self, X):
check_is_fitted(self)
X = validate_data(self, X, dtype=np.float64, reset=False)
span = self.data_max_ - self.data_min_
return (X - self.data_min_) / np.where(span > 0, span, 1.0)
cols = ["age", "tenure_months", "support_tickets", "avg_session_minutes"]
ours = MiniMinMaxScaler().fit(X_train[cols])
theirs = MinMaxScaler().fit(X_train[cols])
print("min:", ours.data_min_)
print("max:", ours.data_max_)
same = np.allclose(ours.transform(X_test[cols]), theirs.transform(X_test[cols]))
print("matches MinMaxScaler:", same)
print(ours.get_feature_names_out()[:2].tolist())
assert same
assert np.allclose(ours.fit_transform(np.ones((3, 2))), 0.0) # constant columns
Output
min: [18. 0. 0. 1.]
max: [80. 72. 8. 68.1]
matches MinMaxScaler: True
['age', 'tenure_months']

How it works:

  1. The class has no __init__, because it has no hyperparameters. BaseEstimator still gives it get_params() (an empty dict) and a repr.
  2. validate_data records n_features_in_ and feature_names_in_ in fit(), and checks the columns again in transform() with reset=False.
  3. The test rows can fall outside [0,1][0, 1] when they are below the training minimum or above the training maximum. scikit-learn’s MinMaxScaler behaves the same unless you pass clip=True.

Alternative: add a feature_range=(0, 1) hyperparameter in __init__ and rescale the result with low + z * (high - low). Validate the tuple in fit(), not in __init__.

Core

Choose a method and justify it: the churn team asks whether to report accuracy or ROC-AUC. Cross-validate a DummyClassifier(strategy="most_frequent") and the churn pipeline of M34-C03 on the same folds with both metrics. Print the mean of each, then compute how much of the possible improvement over the baseline each metric shows: (model−baseline)/(1−baseline)(\text{model} - \text{baseline}) / (1 - \text{baseline}). Print the metric with the larger relative gain as the recommendation.

Expected output
baseline accuracy 0.807 ROC-AUC 0.500
model accuracy 0.836 ROC-AUC 0.813
accuracy: 14.7% of the possible gain
roc_auc: 62.5% of the possible gain
report: roc_auc
Starter
from sklearn.dummy import DummyClassifier
models = {"baseline": DummyClassifier(strategy="most_frequent"), "model": ...} # TODO
means = {}
for name, est in models.items():
# TODO: cross_validate with scoring=["accuracy", "roc_auc"]
pass
# TODO: relative gain per metric, then the recommendation
Hint 1

res["test_accuracy"].mean() and res["test_roc_auc"].mean() give the two means for one estimator.

Hint 2

For accuracy the baseline is about 0.807, so the possible improvement is only 0.193. For ROC-AUC the baseline is 0.5.

Solution
from sklearn.dummy import DummyClassifier
preprocess = ColumnTransformer([
("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), NUMERIC),
("cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False), TEXT),
])
models = {
"baseline": DummyClassifier(strategy="most_frequent"),
"model": make_pipeline(preprocess, LogisticRegression(max_iter=1000)),
}
means = {}
for name, est in models.items():
res = cross_validate(est, X_train, y_train, cv=skf, scoring=["accuracy", "roc_auc"])
means[name] = {m: res[f"test_{m}"].mean() for m in ["accuracy", "roc_auc"]}
print(f"{name:<9} accuracy {means[name]['accuracy']:.3f} "
f"ROC-AUC {means[name]['roc_auc']:.3f}")
gain = {}
for metric in ["accuracy", "roc_auc"]:
base, mod = means["baseline"][metric], means["model"][metric]
gain[metric] = (mod - base) / (1 - base)
print(f"{metric}: {gain[metric]:.1%} of the possible gain")
print("report:", max(gain, key=gain.get))
assert gain["roc_auc"] > 3 * gain["accuracy"]
Output
baseline accuracy 0.807 ROC-AUC 0.500
model accuracy 0.836 ROC-AUC 0.813
accuracy: 14.7% of the possible gain
roc_auc: 62.5% of the possible gain
report: roc_auc

How it works:

  1. The baseline predicts “no churn” for everyone. Its accuracy is high only because 81% of customers stay, and its ROC-AUC is 0.5 because it ranks nobody above anybody.
  2. The relative gain divides the improvement by the room for improvement. Accuracy shows a small share of the possible gain; ROC-AUC shows a much larger one.
  3. Recommendation: report ROC-AUC (with recall or precision at the chosen threshold), because accuracy on imbalanced classes hides how well the model ranks risky customers.

Alternative: balanced_accuracy (the mean recall of both classes) is another imbalance-aware score; its baseline is also 0.5.

M34-C12 · Save and reload a pipeline with its metadata

Section titled “M34-C12 · Save and reload a pipeline with its metadata”
Core

Fit make_pipeline(SimpleImputer(strategy="median"), StandardScaler(), LogisticRegression()) on the training rows of the NUMERIC columns. Save it to output/numeric_churn.joblib and save a JSON file output/numeric_churn.json with the scikit-learn version, the feature list and the test accuracy. Load both back, check that the loaded pipeline predicts the same probabilities, and print the files written, the metadata keys and the accuracy.

Expected output
written: ['output/numeric_churn.joblib']
metadata keys: ['features', 'sklearn_version', 'test_accuracy']
test accuracy: 0.833 same predictions: True
Starter
import json
from pathlib import Path
import joblib
import sklearn
pipe = make_pipeline(SimpleImputer(strategy="median"), StandardScaler(), LogisticRegression())
# TODO: fit, create output/, dump the pipeline, write the JSON
# TODO: load both and compare predict_proba on X_test[NUMERIC]
Hint 1

Path("output").mkdir(exist_ok=True) creates the folder. joblib.dump(obj, path) returns the list of written files.

Hint 2

json.dumps(metadata, indent=2) turns a dict into text. Convert NumPy floats with float() before you save them.

Solution
import json
from pathlib import Path
import joblib
import sklearn
pipe = make_pipeline(
SimpleImputer(strategy="median"), StandardScaler(), LogisticRegression()
)
pipe.fit(X_train[NUMERIC], y_train)
Path("output").mkdir(exist_ok=True)
written = joblib.dump(pipe, "output/numeric_churn.joblib")
metadata = {
"sklearn_version": sklearn.__version__,
"features": NUMERIC,
"test_accuracy": round(float(pipe.score(X_test[NUMERIC], y_test)), 3),
}
Path("output/numeric_churn.json").write_text(json.dumps(metadata, indent=2))
loaded = joblib.load("output/numeric_churn.joblib")
meta = json.loads(Path("output/numeric_churn.json").read_text())
same = np.array_equal(loaded.predict_proba(X_test[meta["features"]]),
pipe.predict_proba(X_test[NUMERIC]))
print("written:", written)
print("metadata keys:", sorted(meta))
print("test accuracy:", meta["test_accuracy"], " same predictions:", same)
assert same and meta["sklearn_version"] == sklearn.__version__
Output
written: ['output/numeric_churn.joblib']
metadata keys: ['features', 'sklearn_version', 'test_accuracy']
test accuracy: 0.833 same predictions: True

How it works:

  1. joblib.dump pickles the whole fitted pipeline: the medians, the means and standard deviations, and the coefficients.
  2. The JSON file keeps facts that the model file does not show at a glance: the version it needs, the columns it expects and its measured score.
  3. The loader uses the saved feature list to select the columns, so the column order is always the one the model was trained with.

Alternative: joblib.dump(pipe, "output/numeric_churn.joblib", compress=3) writes a smaller file at the cost of slower saving and loading.

Core

The lesson’s final pipeline added a log step for the charges and a QuantileClipper for the count columns. Measure each one: write a function build(log, clip) that returns the pipeline with or without each step, and cross-validate all four combinations with ROC-AUC on skf. Print one line per combination and the gain that each step brings on its own.

Expected output
log=False clip=False ROC-AUC 0.8126
log=False clip=True ROC-AUC 0.8126
log=True clip=False ROC-AUC 0.8237
log=True clip=True ROC-AUC 0.8243
log alone adds +0.0111, clip alone adds +0.0000
Starter
from sklearn.base import BaseEstimator, OneToOneFeatureMixin, TransformerMixin
from sklearn.preprocessing import FunctionTransformer
from sklearn.utils.validation import check_is_fitted, validate_data
LOG_COLS = ["monthly_charges", "total_charges"]
COUNT_COLS = ["age", "has_autopay", "tenure_months", "support_tickets",
"logins_last_30d", "avg_session_minutes"]
class QuantileClipper(OneToOneFeatureMixin, TransformerMixin, BaseEstimator):
... # TODO: copy it from Example 7 of the lesson
def build(log: bool, clip: bool) -> Pipeline:
... # TODO: the lesson's pipeline, with the two steps optional
# TODO: loop over the four combinations and cross-validate
Hint 1

Build the step lists first: log_steps = [SimpleImputer(strategy="median")], then append the FunctionTransformer only when log is true, then a StandardScaler. Pass them with make_pipeline(*log_steps).

Hint 2

Store the four means in a dict keyed by (log, clip). The gain of the log step is means[(True, False)] - means[(False, False)].

Solution
from sklearn.base import BaseEstimator, OneToOneFeatureMixin, TransformerMixin
from sklearn.preprocessing import FunctionTransformer
from sklearn.utils.validation import check_is_fitted, validate_data
LOG_COLS = ["monthly_charges", "total_charges"]
COUNT_COLS = ["age", "has_autopay", "tenure_months", "support_tickets",
"logins_last_30d", "avg_session_minutes"]
class QuantileClipper(OneToOneFeatureMixin, TransformerMixin, BaseEstimator):
"""Clip each column to quantiles learned on the training rows."""
def __init__(self, lower: float = 0.01, upper: float = 0.99) -> None:
self.lower = lower
self.upper = upper
def fit(self, X, y=None):
if not 0 <= self.lower < self.upper <= 1:
raise ValueError("need 0 <= lower < upper <= 1")
X = validate_data(self, X, dtype=np.float64)
self.lower_, self.upper_ = np.quantile(X, [self.lower, self.upper], axis=0)
return self
def transform(self, X):
check_is_fitted(self)
X = validate_data(self, X, dtype=np.float64, reset=False)
return np.clip(X, self.lower_, self.upper_)
def build(log: bool, clip: bool) -> Pipeline:
log_steps = [SimpleImputer(strategy="median")]
if log:
log_steps.append(FunctionTransformer(np.log1p, feature_names_out="one-to-one"))
count_steps = [QuantileClipper()] if clip else []
prep = ColumnTransformer([
("log", make_pipeline(*log_steps, StandardScaler()), LOG_COLS),
("num", make_pipeline(*count_steps, StandardScaler()), COUNT_COLS),
("cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False), TEXT),
])
return Pipeline([("prep", prep), ("model", LogisticRegression(max_iter=1000))])
means = {}
for log in [False, True]:
for clip in [False, True]:
scores = cross_val_score(build(log, clip), X_train, y_train, cv=skf,
scoring="roc_auc")
means[(log, clip)] = scores.mean()
print(f"log={log!s:<5} clip={clip!s:<5} ROC-AUC {scores.mean():.4f}")
log_gain = means[(True, False)] - means[(False, False)]
clip_gain = means[(False, True)] - means[(False, False)]
print(f"log alone adds {log_gain:+.4f}, clip alone adds {clip_gain:+.4f}")
assert log_gain > 10 * abs(clip_gain)
Output
log=False clip=False ROC-AUC 0.8126
log=False clip=True ROC-AUC 0.8126
log=True clip=False ROC-AUC 0.8237
log=True clip=True ROC-AUC 0.8243
log alone adds +0.0111, clip alone adds +0.0000

How it works:

  1. Removing one part at a time and measuring the change is called an ablation study. It tells you which parts of a pipeline earn their place.
  2. All four variants use the same skf folds, so the differences come from the pipelines, not from the data split.
  3. The log transform brings about 0.011 of ROC-AUC (Example 7 of the lesson explains why: it makes the churn log-odds closer to linear in total_charges). The clipping changes the score by less than 0.001, so a simpler pipeline without it would be just as good.

Alternative: make log and clip hyperparameters of one custom estimator, or use "passthrough" as a step in the pipeline, and let GridSearchCV (module 37) try the combinations.

M34-C14 · Fix the bug: a transformer that breaks get_params

Section titled “M34-C14 · Fix the bug: a transformer that breaks get_params”
Core

Fix the bug: ChargeScaler multiplies the charge columns by a factor. Printing it or cloning it raises AttributeError: 'ChargeScaler' object has no attribute 'factor'. Fix the class so that print(), clone() and set_params() work, then print the clone, its get_params() and the first transformed value after set_params(factor=0.01).

Expected output
ChargeScaler(factor=2.0) {'factor': 2.0}
first value: 0.2909 (raw 29.09)
Starter
from sklearn.base import BaseEstimator, TransformerMixin, clone
class ChargeScaler(TransformerMixin, BaseEstimator):
def __init__(self, factor=1.0):
self.factor_ = factor # TODO: the bug is here
def fit(self, X, y=None):
return self
def transform(self, X):
return np.asarray(X, dtype=np.float64) * self.factor_
Hint 1

get_params() looks for an attribute with exactly the name of each __init__ argument.

Hint 2

A trailing underscore means “learned in fit()”. A hyperparameter has no underscore.

Solution
from sklearn.base import BaseEstimator, TransformerMixin, clone
class ChargeScaler(TransformerMixin, BaseEstimator):
"""Multiply the input by a fixed factor (for example, cents to dollars)."""
def __init__(self, factor: float = 1.0) -> None:
self.factor = factor
def fit(self, X, y=None):
return self
def transform(self, X):
return np.asarray(X, dtype=np.float64) * self.factor
scaler = ChargeScaler(factor=2.0)
copy = clone(scaler)
print(copy, copy.get_params())
copy.set_params(factor=0.01)
first = copy.fit_transform(X_train[["monthly_charges"]])[0, 0]
print(f"first value: {first:.4f} (raw {X_train['monthly_charges'].iloc[0]})")
assert copy.factor == 0.01 and scaler.factor == 2.0
assert np.isclose(first, X_train["monthly_charges"].iloc[0] * 0.01)
Output
ChargeScaler(factor=2.0) {'factor': 2.0}
first value: 0.2909 (raw 29.09)

How it works:

  1. BaseEstimator.get_params() reads the __init__ signature, finds the argument factor and calls getattr(self, "factor"). The buggy class stored it as factor_, so the lookup failed. __repr__ and clone() both call get_params(), so both crashed.
  2. Storing the argument unchanged under its own name fixes all three.
  3. set_params(factor=0.01) now changes the attribute that transform() reads, so the new value takes effect.

Alternative: this transformer learns nothing, so a FunctionTransformer around a named function also works, for example def scale(X, factor): return X * factor with FunctionTransformer(scale, kw_args={"factor": 0.01}). Its kw_args is then the hyperparameter, so set_params(kw_args={"factor": 0.5}) changes it. The class is clearer when the factor has a meaning in your domain.

M34-X01 · Rebuild minilearn’s LinearRegression for many features

Section titled “M34-X01 · Rebuild minilearn’s LinearRegression for many features”
Challenge

In module 18, minilearn.LinearRegression fitted one feature with a closed-form formula. Rebuild it for any number of features with NumPy: MiniLinearRegression(RegressorMixin, BaseEstimator) with a fit_intercept hyperparameter, solved with np.linalg.lstsq. On data/houses.csv, predict price from sqft, bedrooms, bathrooms, distance_to_center_km and condition. Check that coef_, intercept_ and the predictions match sklearn.linear_model.LinearRegression, then cross-validate both inside a pipeline with a scaler using KFold(5, shuffle=True, random_state=42) and R².

Expected output
coef_: [ 323.2 -14351.5 29080.7 -16042.4 72257.2]
intercept_: -236889.7
match: True True True
CV R² 0.623 ± 0.011 same as sklearn: True
Starter
from sklearn.base import BaseEstimator, RegressorMixin
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import KFold
from sklearn.utils.validation import check_is_fitted, validate_data
class MiniLinearRegression(RegressorMixin, BaseEstimator):
def __init__(self, fit_intercept: bool = True) -> None:
self.fit_intercept = fit_intercept
def fit(self, X, y):
# TODO: add a column of ones when fit_intercept, solve with lstsq
...
def predict(self, X):
...
houses = pd.read_csv("data/houses.csv")
# TODO: features, target, compare, cross-validate
Hint 1

With an intercept, solve Aw≈yA\mathbf{w} \approx \mathbf{y} where AA is np.column_stack([np.ones(n), X]). Then intercept_ = w[0] and coef_ = w[1:].

Hint 2

w, *_ = np.linalg.lstsq(A, y, rcond=None) returns the least-squares solution first. RegressorMixin gives you score() as R².

Hint 3

For the CV, build make_pipeline(StandardScaler(), MiniLinearRegression()) and the same with LinearRegression(), and pass one KFold object to both cross_val_score calls with scoring="r2".

Solution
from sklearn.base import BaseEstimator, RegressorMixin
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import KFold
from sklearn.utils.validation import check_is_fitted, validate_data
class MiniLinearRegression(RegressorMixin, BaseEstimator):
"""Ordinary least squares for any number of features."""
def __init__(self, fit_intercept: bool = True) -> None:
self.fit_intercept = fit_intercept
def fit(self, X, y):
X, y = validate_data(self, X, y, dtype=np.float64, y_numeric=True)
A = np.column_stack([np.ones(len(X)), X]) if self.fit_intercept else X
w, *_ = np.linalg.lstsq(A, y, rcond=None)
self.intercept_ = float(w[0]) if self.fit_intercept else 0.0
self.coef_ = w[1:] if self.fit_intercept else w
return self
def predict(self, X):
check_is_fitted(self)
X = validate_data(self, X, dtype=np.float64, reset=False)
return X @ self.coef_ + self.intercept_
houses = pd.read_csv("data/houses.csv")
cols = ["sqft", "bedrooms", "bathrooms", "distance_to_center_km", "condition"]
Xh, yh = houses[cols], houses["price"]
mini = MiniLinearRegression().fit(Xh, yh)
real = LinearRegression().fit(Xh, yh)
print("coef_:", mini.coef_.round(1))
print(f"intercept_: {mini.intercept_:.1f}")
print("match:", np.allclose(mini.coef_, real.coef_),
np.isclose(mini.intercept_, real.intercept_),
np.allclose(mini.predict(Xh), real.predict(Xh)))
kf = KFold(n_splits=5, shuffle=True, random_state=42)
r2_mini = cross_val_score(make_pipeline(StandardScaler(), MiniLinearRegression()),
Xh, yh, cv=kf, scoring="r2")
r2_real = cross_val_score(make_pipeline(StandardScaler(), LinearRegression()),
Xh, yh, cv=kf, scoring="r2")
print(f"CV R² {r2_mini.mean():.3f} ± {r2_mini.std():.3f}",
" same as sklearn:", np.allclose(r2_mini, r2_real))
assert np.allclose(mini.coef_, real.coef_) and np.allclose(r2_mini, r2_real)
assert np.isclose(mini.score(Xh, yh), real.score(Xh, yh))
Output
coef_: [ 323.2 -14351.5 29080.7 -16042.4 72257.2]
intercept_: -236889.7
match: True True True
CV R² 0.623 ± 0.011 same as sklearn: True

How it works:

  1. np.linalg.lstsq finds the weights that minimize the sum of squared errors, the same problem that module 32 solved with the normal equations. The column of ones turns the first weight into the intercept.
  2. validate_data(..., y_numeric=True) converts both inputs to float arrays and records n_features_in_ and feature_names_in_.
  3. RegressorMixin provides score() as R² and marks the class as a regressor, so cross_val_score accepts it like any scikit-learn model. The five fold scores match scikit-learn exactly.
  4. Each extra square foot of floor adds about 323 USD here, and each kilometer from the center removes about 16,000 USD. Module 35 improves this model a lot with the neighborhood and a log target.

Alternative: solve the normal equations, np.linalg.solve(A.T @ A, A.T @ y). It gives the same answer on well-conditioned data, but lstsq is more stable when columns are nearly collinear.

M34-X02 · Tune C by hand with cross-validation

Section titled “M34-X02 · Tune C by hand with cross-validation”
Challenge

Tune C of the churn pipeline (M34-C03) without touching the test set. For C in 0.001, 0.01, 0.1, 1 and 10, clone the pipeline, set model__C, and cross-validate ROC-AUC with skf. Print mean ± std for each value. Pick the best C, refit on all training rows and score the test set once.

Expected output
C=0.001 ROC-AUC 0.8030 ± 0.0145
C=0.01 ROC-AUC 0.8087 ± 0.0136
C=0.1 ROC-AUC 0.8122 ± 0.0123
C=1 ROC-AUC 0.8126 ± 0.0113
C=10 ROC-AUC 0.8126 ± 0.0113
best C = 1, test ROC-AUC 0.8131
Starter
from sklearn.base import clone
from sklearn.metrics import roc_auc_score
base = ... # TODO: the pipeline of M34-C03, with the model step named "model"
results = {}
for c in [0.001, 0.01, 0.1, 1, 10]:
# TODO: clone, set_params(model__C=c), cross_val_score
pass
# TODO: best C, refit, test ROC-AUC
Hint 1

clone(base).set_params(model__C=c) gives a fresh pipeline for each value.

Hint 2

best_c = max(results, key=lambda c: results[c].mean()). Score the test set with roc_auc_score(y_test, final.predict_proba(X_test)[:, 1]).

Solution
from sklearn.base import clone
from sklearn.metrics import roc_auc_score
preprocess = ColumnTransformer([
("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), NUMERIC),
("cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False), TEXT),
])
base = Pipeline([("prep", preprocess), ("model", LogisticRegression(max_iter=1000))])
results = {}
for c in [0.001, 0.01, 0.1, 1, 10]:
candidate = clone(base).set_params(model__C=c)
results[c] = cross_val_score(candidate, X_train, y_train, cv=skf, scoring="roc_auc")
print(f"C={c:<6} ROC-AUC {results[c].mean():.4f} ± {results[c].std():.4f}")
best_c = max(results, key=lambda c: results[c].mean())
final = clone(base).set_params(model__C=best_c).fit(X_train, y_train)
test_auc = roc_auc_score(y_test, final.predict_proba(X_test)[:, 1])
print(f"best C = {best_c}, test ROC-AUC {test_auc:.4f}")
assert results[0.001].mean() < results[best_c].mean()
assert not hasattr(base[-1], "coef_") # the template itself was never fitted
Output
C=0.001 ROC-AUC 0.8030 ± 0.0145
C=0.01 ROC-AUC 0.8087 ± 0.0136
C=0.1 ROC-AUC 0.8122 ± 0.0123
C=1 ROC-AUC 0.8126 ± 0.0113
C=10 ROC-AUC 0.8126 ± 0.0113
best C = 1, test ROC-AUC 0.8131

How it works:

  1. clone() gives each candidate its own unfitted pipeline, so no value of C reuses another one’s fit. set_params(model__C=c) reaches the model step with the __ syntax.
  2. All candidates use the same folds, so the comparison is fair. Very strong regularization (C=0.001) clearly hurts. From C=0.1 up, the differences are far smaller than the standard deviations, so any of them is a reasonable choice.
  3. The test set is used once, after the choice. Its score is an honest estimate for the chosen model.

Alternative: GridSearchCV(base, {"model__C": [0.001, 0.01, 0.1, 1, 10]}, cv=skf, scoring="roc_auc") does the loop, the choice and the refit for you. Module 37 teaches it.

M34-X03 · Compare four models on the same folds

Section titled “M34-X03 · Compare four models on the same folds”
Challenge

Compare four estimators on the churn training rows with cross_validate, the setup’s skf and two metrics (ROC-AUC and accuracy): a most-frequent DummyClassifier, the logistic regression pipeline of M34-C03, a KNN pipeline with n_neighbors=25, and a DecisionTreeClassifier(max_depth=5, random_state=42). Every model except the dummy gets the same preprocessing. Print a table sorted by mean ROC-AUC with the mean and std of ROC-AUC and the mean accuracy.

Expected output
auc_mean auc_std acc_mean
model
logreg 0.813 0.011 0.836
tree5 0.794 0.022 0.829
knn25 0.779 0.018 0.822
dummy 0.500 0.000 0.807
Starter
from sklearn.base import clone
from sklearn.dummy import DummyClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
preprocess = ... # TODO: the column transformer of M34-C01
models = {
"dummy": DummyClassifier(strategy="most_frequent"),
# TODO: "logreg", "knn25", "tree5", each as make_pipeline(clone(preprocess), ...)
}
rows = []
# TODO: cross_validate each model, collect a dict per model, build a DataFrame
Hint 1

clone(preprocess) gives each pipeline its own copy of the preprocessing, so no two pipelines share fitted steps.

Hint 2

Collect one dict per model: {"model": name, "auc_mean": ..., "auc_std": ..., "acc_mean": ...}. Then pd.DataFrame(rows).set_index("model").sort_values("auc_mean", ascending=False).

Solution
from sklearn.base import clone
from sklearn.dummy import DummyClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
preprocess = ColumnTransformer([
("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), NUMERIC),
("cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False), TEXT),
])
models = {
"dummy": DummyClassifier(strategy="most_frequent"),
"logreg": make_pipeline(clone(preprocess), LogisticRegression(max_iter=1000)),
"knn25": make_pipeline(clone(preprocess), KNeighborsClassifier(n_neighbors=25)),
"tree5": make_pipeline(clone(preprocess),
DecisionTreeClassifier(max_depth=5, random_state=42)),
}
rows = []
for name, est in models.items():
res = cross_validate(est, X_train, y_train, cv=skf, scoring=["roc_auc", "accuracy"])
rows.append({
"model": name,
"auc_mean": res["test_roc_auc"].mean(),
"auc_std": res["test_roc_auc"].std(),
"acc_mean": res["test_accuracy"].mean(),
})
table = pd.DataFrame(rows).set_index("model").sort_values("auc_mean", ascending=False)
print(table.round(3))
assert table.index[0] == "logreg" and table.index[-1] == "dummy"
assert table.loc["dummy", "auc_mean"] == 0.5
Output
auc_mean auc_std acc_mean
model
logreg 0.813 0.011 0.836
tree5 0.794 0.022 0.829
knn25 0.779 0.018 0.822
dummy 0.500 0.000 0.807

How it works:

  1. One splitter object gives all four models the same folds, so differences in the table come from the models.
  2. The logistic regression ranks churners best. The shallow tree and KNN come next. All three beat the dummy by a wide margin in ROC-AUC, but by only a few points in accuracy.
  3. The polymorphism of module 19 is at work here: the loop calls only cross_validate, and every estimator (a dummy, three pipelines) fits the same interface.

Alternative: add return_estimator=True to cross_validate to get the five fitted pipelines of each model back, for example to read the tree’s feature importances per fold.

M34-X04 · Add distance weighting to MiniKNNClassifier

Section titled “M34-X04 · Add distance weighting to MiniKNNClassifier”
Challenge

Extend the lesson’s MiniKNNClassifier with a weights hyperparameter: "uniform" (one vote per neighbor) or "distance" (a vote of 1 / distance). Validate it in fit(). Check the "distance" version against KNeighborsClassifier(weights="distance") on four scaled churn columns, check that an invalid value raises ValueError at fit() time (not at construction), and cross-validate both settings in a pipeline.

Expected output
proba match: True
fit raised: weights must be 'uniform' or 'distance', got 'closest'
uniform ROC-AUC 0.732 ± 0.013
distance ROC-AUC 0.735 ± 0.011
Starter
from sklearn.base import BaseEstimator, ClassifierMixin
from sklearn.neighbors import KNeighborsClassifier
from sklearn.utils.validation import check_is_fitted, validate_data
class MiniKNNClassifier(ClassifierMixin, BaseEstimator):
def __init__(self, n_neighbors: int = 5, weights: str = "uniform") -> None:
... # TODO: store both, unchanged
def fit(self, X, y):
... # TODO: validate n_neighbors and weights, store the training data
def predict_proba(self, X):
... # TODO: votes of 1 or 1 / distance, normalized to sum to 1
def predict(self, X):
...
cols = ["tenure_months", "logins_last_30d", "monthly_charges", "avg_session_minutes"]
Hint 1

np.bincount(codes, weights=w, minlength=n_classes) adds the weights per class instead of counting.

Hint 2

Divide each row of votes by its sum to get probabilities. A distance of exactly 0 (a new row identical to a training row) would divide by zero, so guard it with np.maximum(dist, 1e-12).

Solution
from sklearn.base import BaseEstimator, ClassifierMixin
from sklearn.neighbors import KNeighborsClassifier
from sklearn.utils.validation import check_is_fitted, validate_data
class MiniKNNClassifier(ClassifierMixin, BaseEstimator):
"""k nearest neighbors with uniform or inverse-distance votes."""
def __init__(self, n_neighbors: int = 5, weights: str = "uniform") -> None:
self.n_neighbors = n_neighbors
self.weights = weights
def fit(self, X, y):
if self.n_neighbors < 1:
raise ValueError(f"n_neighbors must be >= 1, got {self.n_neighbors}")
if self.weights not in ("uniform", "distance"):
raise ValueError(
f"weights must be 'uniform' or 'distance', got {self.weights!r}"
)
X, y = validate_data(self, X, y, dtype=np.float64)
self.classes_, self.y_codes_ = np.unique(y, return_inverse=True)
self.X_train_ = X
return self
def predict_proba(self, X):
check_is_fitted(self)
X = validate_data(self, X, dtype=np.float64, reset=False)
proba = np.empty((X.shape[0], len(self.classes_)))
for i, row in enumerate(X):
dist = np.linalg.norm(self.X_train_ - row, axis=1)
nearest = np.argsort(dist, kind="stable")[: self.n_neighbors]
if self.weights == "distance":
w = 1.0 / np.maximum(dist[nearest], 1e-12)
else:
w = np.ones(len(nearest))
votes = np.bincount(self.y_codes_[nearest], weights=w,
minlength=len(self.classes_))
proba[i] = votes / votes.sum()
return proba
def predict(self, X):
return self.classes_[self.predict_proba(X).argmax(axis=1)]
cols = ["tenure_months", "logins_last_30d", "monthly_charges", "avg_session_minutes"]
scaler = StandardScaler().fit(X_train[cols])
Z_train, Z_test = scaler.transform(X_train[cols]), scaler.transform(X_test[cols])
mini = MiniKNNClassifier(n_neighbors=15, weights="distance").fit(Z_train, y_train)
real = KNeighborsClassifier(n_neighbors=15, weights="distance").fit(Z_train, y_train)
same = np.allclose(mini.predict_proba(Z_test), real.predict_proba(Z_test))
print("proba match:", same)
bad = MiniKNNClassifier(weights="closest") # constructing is fine
try:
bad.fit(Z_train, y_train)
except ValueError as err:
print("fit raised:", err)
for w in ["uniform", "distance"]:
pipe = make_pipeline(StandardScaler(), MiniKNNClassifier(n_neighbors=15, weights=w))
auc = cross_val_score(pipe, X_train[cols], y_train, cv=skf, scoring="roc_auc")
print(f"{w:<8} ROC-AUC {auc.mean():.3f} ± {auc.std():.3f}")
assert np.array_equal(mini.predict(Z_test), real.predict(Z_test))
assert mini.get_params() == {"n_neighbors": 15, "weights": "distance"}
Output
proba match: True
fit raised: weights must be 'uniform' or 'distance', got 'closest'
uniform ROC-AUC 0.732 ± 0.013
distance ROC-AUC 0.735 ± 0.011

How it works:

  1. weights is stored unchanged in __init__ and checked in fit(). So MiniKNNClassifier(weights="closest") can be created (and cloned, and set by a search), and the error appears when the bad value is used.
  2. np.bincount(..., weights=w) sums the votes per class. With "distance", close neighbors count more. Dividing by the sum turns the votes into probabilities, as scikit-learn does.
  3. get_params() reports the new hyperparameter with no extra code, because BaseEstimator reads it from the signature.
  4. On this data, distance weighting gives a slightly higher ROC-AUC than uniform votes, but the gain (0.003) is far below one standard deviation. Keep the simpler setting unless a larger test shows a clear gain.

Alternative: compute all distances at once with scipy.spatial.distance.cdist(X, self.X_train_) and np.argpartition for speed. The loop version is easier to read and fast enough for a few thousand rows.

Challenge

Fix the bug: the starter script has five bugs. It leaks the test rows into the scaler, selects the text columns with a deprecated dtype, switches on pandas output too late, routes a parameter with a wrong name, and cross-validates without shuffled stratified folds. Fix all five and print the CV ROC-AUC (mean ± std) and the test ROC-AUC.

Expected output
CV ROC-AUC 0.813 ± 0.012
test ROC-AUC 0.813
features: 22
Starter
from sklearn.metrics import roc_auc_score
scaler = StandardScaler().fit(X[["tenure_months"]]) # bug 1: fitted on all rows
X_train = X_train.assign(tenure_months=scaler.transform(X_train[["tenure_months"]]))
X_test = X_test.assign(tenure_months=scaler.transform(X_test[["tenure_months"]]))
prep = ColumnTransformer([
("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()),
make_column_selector(dtype_include="number")),
("cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False),
make_column_selector(dtype_include=object)), # bug 2
])
pipe = Pipeline([("prep", prep), ("clf", LogisticRegression(max_iter=1000))])
pipe.fit(X_train, y_train)
pipe.set_output(transform="pandas") # bug 3: after fit
pipe.set_params(model__C=0.5) # bug 4
scores = cross_val_score(pipe, X_train, y_train, cv=5, scoring="roc_auc") # bug 5
Hint 1

Bug 1 needs no replacement: the numeric branch of the pipeline already scales tenure_months, and it learns from the training folds only. Delete the three lines.

Hint 2

The model step is named clf, not model. In pandas 3, text columns have the dtype "str".

Hint 3

Call set_output() before fit(), and pass the setup’s skf instead of cv=5.

Solution
from sklearn.metrics import roc_auc_score
prep = ColumnTransformer([
("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()),
make_column_selector(dtype_include="number")),
("cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False),
make_column_selector(dtype_include="str")),
])
pipe = Pipeline([("prep", prep), ("clf", LogisticRegression(max_iter=1000))])
pipe.set_output(transform="pandas")
pipe.set_params(clf__C=0.5)
scores = cross_val_score(pipe, X_train, y_train, cv=skf, scoring="roc_auc")
pipe.fit(X_train, y_train)
test_auc = roc_auc_score(y_test, pipe.predict_proba(X_test)[:, 1])
print(f"CV ROC-AUC {scores.mean():.3f} ± {scores.std():.3f}")
print(f"test ROC-AUC {test_auc:.3f}")
print("features:", pipe[:-1].transform(X_test).shape[1])
assert pipe["clf"].C == 0.5
assert abs(test_auc - scores.mean()) < 2 * scores.std() + 0.01
Output
CV ROC-AUC 0.813 ± 0.012
test ROC-AUC 0.813
features: 22

How it works:

  1. Leak: the hand-made scaler learned from all 5,000 rows, test rows included. The pipeline’s numeric branch already scales tenure_months on the training rows (and on each training fold), so the extra code was both leaky and redundant.
  2. Dtype: dtype_include=object warns in pandas 3. "str" selects the text columns directly.
  3. Order: after set_output() on a fitted pipeline, the inner steps receive DataFrames that they were not fitted on, so the next predict() warns about feature names. Setting it first avoids the mismatch.
  4. Name: set_params(model__C=0.5) raises ValueError, because the step is called clf.
  5. Folds: cv=5 uses unshuffled stratified folds, so the folds depend on the current row order of X_train, and they differ from the folds of every other comparison on this page. skf shuffles with a fixed seed, so the score is reproducible and comparable with the other models.

Alternative: run the script with python -W error script.py while you develop. Every warning then becomes an exception with a traceback, so bugs 2 and 3 cannot slip through.