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:
- Read the task and the expected output.
- Copy the setup block and the starter code into one script and replace each to-do comment with your code.
- Run the script and 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.
Run this block before each exercise. It loads the customers and makes the 75/25 stratified split of the lesson.
import numpy as npimport pandas as pdfrom sklearn.compose import ColumnTransformer, make_column_selectorfrom sklearn.impute import SimpleImputerfrom sklearn.linear_model import LogisticRegressionfrom sklearn.model_selection import ( StratifiedKFold, cross_val_score, cross_validate, train_test_split,)from sklearn.pipeline import Pipeline, make_pipelinefrom 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)Warm-up
Section titled “Warm-up”M34-W01 · Fit a scaler and read what it learned
Section titled “M34-W01 · Fit a scaler and read what it learned”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.
mean_ : [23.31 60.78]scale_: [19.87 22.99]first test row: [[-0.62 -0.11]]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 roundedHint 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_ == 2assert np.allclose(first, (X_test[cols].head(1) - scaler.mean_) / scaler.scale_)mean_ : [23.31 60.78]scale_: [19.87 22.99]first test row: [[-0.62 -0.11]]How it works:
fit()computes one mean and one standard deviation per column from the 3,750 training rows and stores them in the learned attributesmean_andscale_.transform()applies with those stored values. The test row never changes them.- 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”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 _).
hyperparameters: 14learned: ['classes_', 'coef_', 'feature_names_in_', 'intercept_', 'n_features_in_', 'n_iter_']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 learnedassert set(hyper).isdisjoint(learned)hyperparameters: 14learned: ['classes_', 'coef_', 'feature_names_in_', 'intercept_', 'n_features_in_', 'n_iter_']How it works:
get_params()reads the names of the__init__arguments, so it lists only hyperparameters.fit()adds the learned attributes. Because the model was fitted on a DataFrame, it also storedfeature_names_in_.- 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”Predict the output: read the code and write down the four lines it prints. Then run it.
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.0TrueLogisticRegression(C=0.5, max_iter=300)LogisticRegression(C=5.0, max_iter=300)False 300How it works:
set_params(max_iter=300)changesmodeland returns the same object, sosame is modelisTrue.print(model)showsC=0.5andmax_iter=300, the two values that differ from the defaults.clone(model)builds a new object with the same hyperparameters.copy.set_params(C=5.0)changes only the copy, which still hasmax_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.
M34-W04 · Split with stratify
Section titled “M34-W04 · Split with stratify”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.
(4000, 12) (1000, 12)train churn 0.1925 test churn 0.1930# TODO: split X and y with test_size=0.2, stratify=y, random_state=7# TODO: print the two shapes and the two churn ratesHint 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) == 1000assert abs(y_tr.mean() - y_te.mean()) < 0.001assert (X_te.index == y_te.index).all()(4000, 12) (1000, 12)train churn 0.1925 test churn 0.1930How it works:
- 20% of 5,000 rows is 1,000 test rows.
stratify=yputs 193 of the 963 churners in the test set and the rest in the training set, so both rates stay at about 19.26%.- 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”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.
scaled test mean: -0.002cols = ["logins_last_30d"]scaler = StandardScaler()train_scaled = scaler.fit_transform(X_train[cols])test_scaled = scaler.fit_transform(X_test[cols]) # TODO: fix this lineprint(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)scaled test mean: -0.002How it works:
fit_transform()on the training rows learns the training mean and standard deviation.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.- 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”Predict the output: write down the three lines this code prints. Then run it.
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"['simpleimputer', 'standardscaler', 'logisticregression']Pipeline 2TrueHow it works:
pipe.stepsis a list of(name, estimator)pairs, and the names are the lowercase class names.pipe[:-1]is aPipelinewith every step except the model, so its length is 2.pipe["standardscaler"]andpipe[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”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().
impute__strategy = most_frequentscale__with_mean = Falsemodel__C = 0.2pipe = Pipeline([ ("impute", SimpleImputer()), ("scale", StandardScaler()), ("model", LogisticRegression()),])# TODO: one set_params() call with three step__parameter names# TODO: print the three valuesHint 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 Falseimpute__strategy = most_frequentscale__with_mean = Falsemodel__C = 0.2How it works:
- The pipeline splits each name at the first
__: the left part names the step, and the rest goes to that step’sset_params(). get_params()on the pipeline returns the nested names in the same format, so you can read the values back.- 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”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.
[0.774 0.776 0.786 0.8 0.759]ROC-AUC 0.779 ± 0.014cols = ["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 lineHint 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) == 5assert 0.5 < scores.mean() < 1.0assert not hasattr(pipe[-1], "coef_") # cross_val_score fitted clones, not pipe[0.774 0.776 0.786 0.8 0.759]ROC-AUC 0.779 ± 0.014How it works:
cross_val_scoreclones the pipeline 5 times, fits each clone on 4 folds and scores it on the fifth.- The scaler is refitted inside each fold, so no fold leaks into its own preprocessing.
- The last assert shows that
pipeitself 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.
M34-W09 · Name the one-hot columns
Section titled “M34-W09 · Name the one-hot columns”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.
6 columns['plan_basic', 'plan_premium', 'plan_standard']['contract_month-to-month', 'contract_one-year', 'contract_two-year']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 listHint 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() == 26 columns['plan_basic', 'plan_premium', 'plan_standard']['contract_month-to-month', 'contract_one-year', 'contract_two-year']How it works:
planhas 3 categories andcontracthas 3, so the encoder makes 6 columns.- The names join the input column and the category with
_, in sorted order within each column. - 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”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.
test shape: (1250, 22)num: 8 cat: 14['num__age', 'num__has_autopay', 'num__tenure_months']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()test shape: (1250, 22)num: 8 cat: 14['num__age', 'num__has_autopay', 'num__tenure_months']How it works:
- Each branch is a
(name, transformer, columns)triple. The numeric branch is a pipeline, which a column transformer accepts like any transformer. fit()learns the medians, means, standard deviations and categories fromX_trainonly.transform()applies them to the test rows.- 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”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".
numeric: 8 columnstext: ['region', 'plan', 'contract', 'payment_method']charges: ['monthly_charges', 'total_charges']same text columns: True# 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) == TEXTnumeric: 8 columnstext: ['region', 'plan', 'contract', 'payment_method']charges: ['monthly_charges', 'total_charges']same text columns: TrueHow it works:
dtype_include="number"matches every integer and float column.dtype_include="str"matches the pandas 3 text columns. The olderdtype_include=objectstill works in pandas 3 but warns that it is deprecated.pattern=runsre.searchon 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”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.
lower churn:tenure_months -0.911contract_two-year -0.815logins_last_30d -0.278dtype: float64higher churn:monthly_charges 0.449support_tickets 0.544contract_month-to-month 0.949dtype: float64preprocess = 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) == 22lower churn:tenure_months -0.911contract_two-year -0.815logins_last_30d -0.278dtype: float64higher churn:monthly_charges 0.449support_tickets 0.544contract_month-to-month 0.949dtype: float64How it works:
verbose_feature_names_out=Falseremoves thenum__andcat__prefixes. This is safe here because no two branches produce the same name.- The pipeline slice
model[:-1]is the fitted preprocessing, so its names match the columns the model saw. - 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”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.
DataFrame (1250, 22)['num__age', 'num__has_autopay', 'num__tenure_months', 'num__monthly_charges']num__tenure_months -0.62cat__contract_two-year 0.00Name: 3185, dtype: float64preprocess = 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())DataFrame (1250, 22)['num__age', 'num__has_autopay', 'num__tenure_months', 'num__monthly_charges']num__tenure_months -0.62cat__contract_two-year 0.00Name: 3185, dtype: float64How it works:
set_output()on the column transformer reaches every step inside it, including the inner pipeline.- The output keeps the index of
X_test, so you can look up a customer by id in the transformed data. - 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”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.
first probabilities: [0.16 0.186 0.087]test accuracy: 0.819same as manual: Truecols = ["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 manualHint 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_)first probabilities: [0.16 0.186 0.087]test accuracy: 0.819same as manual: TrueHow it works:
- The pipeline runs
fit_transformfor the imputer and the scaler, thenfitfor the model, exactly like the hand-written chain. - At prediction time, it runs
transformwith the stored values. The probabilities match to the last digit. - 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”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.
KFold min 0.160 max 0.210 spread 0.050StratifiedKFold min 0.192 max 0.194 spread 0.002from 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 passHint 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.005KFold min 0.160 max 0.210 spread 0.050StratifiedKFold min 0.192 max 0.194 spread 0.002How it works:
- Each fold has 500 customers.
KFoldpicks them at random, so one fold can have many more churners than another. StratifiedKFolddeals the churners and the non-churners out separately, so every fold has 96 or 97 churners.- 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”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.
test_acc test_auc test_prec test_recmean 0.836 0.813 0.669 0.288std 0.011 0.013 0.065 0.043lowest: test_recmodel = ... # TODO: the pipeline of M34-C03scoring = {"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, printHint 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" test_acc test_auc test_prec test_recmean 0.836 0.813 0.669 0.288std 0.011 0.013 0.065 0.043lowest: test_recHow it works:
- A dict in
scoringgives each metric your own short name.cross_validatecomputes all four on each fold from one fit. - 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.
- 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”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).
k=1 train 1.000 test 0.747 gap +0.2531k=15 train 0.822 test 0.806 gap +0.0167k=101 train 0.808 test 0.809 gap -0.0002overfits most: k = 1from 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 gapHint 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 == 1assert gaps[101] < gaps[15] < gaps[1]k=1 train 1.000 test 0.747 gap +0.2531k=15 train 0.822 test 0.806 gap +0.0167k=101 train 0.808 test 0.809 gap -0.0002overfits most: k = 1How it works:
- 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. - A larger
kaverages more neighbors. The gap shrinks, and the test accuracy improves. - 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”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.
before aftertotal_charges 1.648 -0.601monthly_charges 0.618 0.098['total_charges', 'monthly_charges']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 afterHint 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() before aftertotal_charges 1.648 -0.601monthly_charges 0.618 0.098['total_charges', 'monthly_charges']How it works:
- Skewness measures how lopsided a distribution is: 0 is symmetric, a positive value has a long right tail.
np.log1pcompresses large values more than small ones, which pulls the long right tail in.monthly_chargesbecomes almost symmetric;total_chargesovershoots and becomes left-skewed, because many new customers have small totals.- 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”Write MiniMinMaxScaler(OneToOneFeatureMixin, TransformerMixin, BaseEstimator). fit() learns data_min_ and data_max_ per column; transform() maps each column to with . 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.
min: [18. 0. 0. 1.]max: [80. 72. 8. 68.1]matches MinMaxScaler: True['age', 'tenure_months']from sklearn.base import BaseEstimator, OneToOneFeatureMixin, TransformerMixinfrom sklearn.preprocessing import MinMaxScalerfrom 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, TransformerMixinfrom sklearn.preprocessing import MinMaxScalerfrom 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 sameassert np.allclose(ours.fit_transform(np.ones((3, 2))), 0.0) # constant columnsmin: [18. 0. 0. 1.]max: [80. 72. 8. 68.1]matches MinMaxScaler: True['age', 'tenure_months']How it works:
- The class has no
__init__, because it has no hyperparameters.BaseEstimatorstill gives itget_params()(an empty dict) and a repr. validate_datarecordsn_features_in_andfeature_names_in_infit(), and checks the columns again intransform()withreset=False.- The test rows can fall outside when they are below the training minimum or above the training maximum. scikit-learn’s
MinMaxScalerbehaves the same unless you passclip=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__.
M34-C11 · Choose a metric and justify it
Section titled “M34-C11 · Choose a metric and justify it”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: . Print the metric with the larger relative gain as the recommendation.
baseline accuracy 0.807 ROC-AUC 0.500model accuracy 0.836 ROC-AUC 0.813accuracy: 14.7% of the possible gainroc_auc: 62.5% of the possible gainreport: roc_aucfrom sklearn.dummy import DummyClassifier
models = {"baseline": DummyClassifier(strategy="most_frequent"), "model": ...} # TODOmeans = {}for name, est in models.items(): # TODO: cross_validate with scoring=["accuracy", "roc_auc"] pass# TODO: relative gain per metric, then the recommendationHint 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"]baseline accuracy 0.807 ROC-AUC 0.500model accuracy 0.836 ROC-AUC 0.813accuracy: 14.7% of the possible gainroc_auc: 62.5% of the possible gainreport: roc_aucHow it works:
- 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.
- 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.
- 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”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.
written: ['output/numeric_churn.joblib']metadata keys: ['features', 'sklearn_version', 'test_accuracy']test accuracy: 0.833 same predictions: Trueimport jsonfrom pathlib import Path
import joblibimport 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 jsonfrom pathlib import Path
import joblibimport 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__written: ['output/numeric_churn.joblib']metadata keys: ['features', 'sklearn_version', 'test_accuracy']test accuracy: 0.833 same predictions: TrueHow it works:
joblib.dumppickles the whole fitted pipeline: the medians, the means and standard deviations, and the coefficients.- 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.
- 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.
M34-C13 · Measure what each step adds
Section titled “M34-C13 · Measure what each step adds”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.
log=False clip=False ROC-AUC 0.8126log=False clip=True ROC-AUC 0.8126log=True clip=False ROC-AUC 0.8237log=True clip=True ROC-AUC 0.8243log alone adds +0.0111, clip alone adds +0.0000from sklearn.base import BaseEstimator, OneToOneFeatureMixin, TransformerMixinfrom sklearn.preprocessing import FunctionTransformerfrom 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-validateHint 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, TransformerMixinfrom sklearn.preprocessing import FunctionTransformerfrom 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)log=False clip=False ROC-AUC 0.8126log=False clip=True ROC-AUC 0.8126log=True clip=False ROC-AUC 0.8237log=True clip=True ROC-AUC 0.8243log alone adds +0.0111, clip alone adds +0.0000How it works:
- 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.
- All four variants use the same
skffolds, so the differences come from the pipelines, not from the data split. - 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”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).
ChargeScaler(factor=2.0) {'factor': 2.0}first value: 0.2909 (raw 29.09)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.0assert np.isclose(first, X_train["monthly_charges"].iloc[0] * 0.01)ChargeScaler(factor=2.0) {'factor': 2.0}first value: 0.2909 (raw 29.09)How it works:
BaseEstimator.get_params()reads the__init__signature, finds the argumentfactorand callsgetattr(self, "factor"). The buggy class stored it asfactor_, so the lookup failed.__repr__andclone()both callget_params(), so both crashed.- Storing the argument unchanged under its own name fixes all three.
set_params(factor=0.01)now changes the attribute thattransform()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.
Challenge
Section titled “Challenge”M34-X01 · Rebuild minilearn’s LinearRegression for many features
Section titled “M34-X01 · Rebuild minilearn’s LinearRegression for many features”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².
coef_: [ 323.2 -14351.5 29080.7 -16042.4 72257.2]intercept_: -236889.7match: True True TrueCV R² 0.623 ± 0.011 same as sklearn: Truefrom sklearn.base import BaseEstimator, RegressorMixinfrom sklearn.linear_model import LinearRegressionfrom sklearn.model_selection import KFoldfrom 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-validateHint 1
With an intercept, solve where 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, RegressorMixinfrom sklearn.linear_model import LinearRegressionfrom sklearn.model_selection import KFoldfrom 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))coef_: [ 323.2 -14351.5 29080.7 -16042.4 72257.2]intercept_: -236889.7match: True True TrueCV R² 0.623 ± 0.011 same as sklearn: TrueHow it works:
np.linalg.lstsqfinds 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.validate_data(..., y_numeric=True)converts both inputs to float arrays and recordsn_features_in_andfeature_names_in_.RegressorMixinprovidesscore()as R² and marks the class as a regressor, socross_val_scoreaccepts it like any scikit-learn model. The five fold scores match scikit-learn exactly.- 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”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.
C=0.001 ROC-AUC 0.8030 ± 0.0145C=0.01 ROC-AUC 0.8087 ± 0.0136C=0.1 ROC-AUC 0.8122 ± 0.0123C=1 ROC-AUC 0.8126 ± 0.0113C=10 ROC-AUC 0.8126 ± 0.0113best C = 1, test ROC-AUC 0.8131from sklearn.base import clonefrom 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-AUCHint 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 clonefrom 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 fittedC=0.001 ROC-AUC 0.8030 ± 0.0145C=0.01 ROC-AUC 0.8087 ± 0.0136C=0.1 ROC-AUC 0.8122 ± 0.0123C=1 ROC-AUC 0.8126 ± 0.0113C=10 ROC-AUC 0.8126 ± 0.0113best C = 1, test ROC-AUC 0.8131How it works:
clone()gives each candidate its own unfitted pipeline, so no value ofCreuses another one’s fit.set_params(model__C=c)reaches the model step with the__syntax.- All candidates use the same folds, so the comparison is fair. Very strong regularization (
C=0.001) clearly hurts. FromC=0.1up, the differences are far smaller than the standard deviations, so any of them is a reasonable choice. - 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”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.
auc_mean auc_std acc_meanmodellogreg 0.813 0.011 0.836tree5 0.794 0.022 0.829knn25 0.779 0.018 0.822dummy 0.500 0.000 0.807from sklearn.base import clonefrom sklearn.dummy import DummyClassifierfrom sklearn.neighbors import KNeighborsClassifierfrom sklearn.tree import DecisionTreeClassifier
preprocess = ... # TODO: the column transformer of M34-C01models = { "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 DataFrameHint 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 clonefrom sklearn.dummy import DummyClassifierfrom sklearn.neighbors import KNeighborsClassifierfrom 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 auc_mean auc_std acc_meanmodellogreg 0.813 0.011 0.836tree5 0.794 0.022 0.829knn25 0.779 0.018 0.822dummy 0.500 0.000 0.807How it works:
- One splitter object gives all four models the same folds, so differences in the table come from the models.
- 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.
- 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”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.
proba match: Truefit raised: weights must be 'uniform' or 'distance', got 'closest'uniform ROC-AUC 0.732 ± 0.013distance ROC-AUC 0.735 ± 0.011from sklearn.base import BaseEstimator, ClassifierMixinfrom sklearn.neighbors import KNeighborsClassifierfrom 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, ClassifierMixinfrom sklearn.neighbors import KNeighborsClassifierfrom 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 finetry: 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"}proba match: Truefit raised: weights must be 'uniform' or 'distance', got 'closest'uniform ROC-AUC 0.732 ± 0.013distance ROC-AUC 0.735 ± 0.011How it works:
weightsis stored unchanged in__init__and checked infit(). SoMiniKNNClassifier(weights="closest")can be created (and cloned, and set by a search), and the error appears when the bad value is used.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.get_params()reports the new hyperparameter with no extra code, becauseBaseEstimatorreads it from the signature.- 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.
M34-X05 · Debug a broken churn pipeline
Section titled “M34-X05 · Debug a broken churn pipeline”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.
CV ROC-AUC 0.813 ± 0.012test ROC-AUC 0.813features: 22from sklearn.metrics import roc_auc_score
scaler = StandardScaler().fit(X[["tenure_months"]]) # bug 1: fitted on all rowsX_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 fitpipe.set_params(model__C=0.5) # bug 4scores = cross_val_score(pipe, X_train, y_train, cv=5, scoring="roc_auc") # bug 5Hint 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.5assert abs(test_auc - scores.mean()) < 2 * scores.std() + 0.01CV ROC-AUC 0.813 ± 0.012test ROC-AUC 0.813features: 22How it works:
- Leak: the hand-made scaler learned from all 5,000 rows, test rows included. The pipeline’s numeric branch already scales
tenure_monthson the training rows (and on each training fold), so the extra code was both leaky and redundant. - Dtype:
dtype_include=objectwarns in pandas 3."str"selects the text columns directly. - Order: after
set_output()on a fitted pipeline, the inner steps receive DataFrames that they were not fitted on, so the nextpredict()warns about feature names. Setting it first avoids the mismatch. - Name:
set_params(model__C=0.5)raisesValueError, because the step is calledclf. - Folds:
cv=5uses unshuffled stratified folds, so the folds depend on the current row order ofX_train, and they differ from the folds of every other comparison on this page.skfshuffles 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.