36. Classification
A subscription business loses about one customer in five every month. The retention team can call a few hundred customers and offer them a discount. Who should they call? This is a classification problem: the model predicts a category (“churns” or “stays”) instead of a number. Classification answers most yes/no questions in industry: fraud or not, spam or not, malignant or benign, click or no click.
This module trains nine kinds of classifiers on data/customers.csv, the churn dataset of the course. It then answers the questions that matter more than the choice of algorithm: which metric to trust, where to put the decision threshold, and whether a predicted 30% really means 30%. The data dictionary describes every column.
What you will learn
Section titled “What you will learn”- Explain the three outputs of a classifier (labels, scores and probabilities) and read logistic regression coefficients as log-odds and odds ratios.
- Train and compare logistic regression, k-nearest neighbors, Gaussian naive Bayes, support vector machines, decision trees, random forests,
HistGradientBoostingClassifier, XGBoost and LightGBM, and know which ones need scaling. - Compute and interpret the confusion matrix, accuracy, precision, recall, F1, ROC-AUC, PR-AUC (average precision), log loss and the Brier score, and explain why accuracy misleads when only 19% of customers churn.
- Choose a decision threshold from business costs on a validation split, never on the test set.
- Check calibration with a calibration curve and fix it with
CalibratedClassifierCV. - Handle multiclass problems with one-vs-rest and multinomial models, and read macro and weighted averages in a
classification_report.
Prerequisites
Section titled “Prerequisites”- 32. Math for ML: the sigmoid, log-odds, log loss, Bayes’ rule and gradient descent.
- 33. Feature engineering: scaling, one-hot encoding and data leakage.
- 34. scikit-learn workflow:
train_test_split,Pipeline,ColumnTransformerand cross-validation. - 35. Regression: KNN, decision trees, random forests and gradient boosting for numbers. This module reuses those models for categories.
- The dataset
data/customers.csv, described in the data dictionary.
Concepts
Section titled “Concepts”What classification is
Section titled “What classification is”In classification, the target is a category, not a number. Each possible value of the target is a class. A model that predicts a class is a classifier.
| Kind | Classes | Example |
|---|---|---|
| Binary classification | exactly 2 | churn (1) or stay (0); fraud or not |
| Multiclass classification | 3 or more, one per row | wine cultivar 0, 1 or 2; support ticket topic |
| Multilabel classification | several labels can be true at once | a movie is “comedy” and “romance” |
In binary problems, one class is the positive class: the class you want to find, coded as 1. For churn, the positive class is “churned”. “Positive” means “the thing we look for”, not “good”.
Labels, scores and probabilities
Section titled “Labels, scores and probabilities”A fitted scikit-learn classifier gives three kinds of output. Most mistakes in classification come from using the wrong one.
| Method | Returns | Shape for churn | Use it for |
|---|---|---|---|
predict(X) |
a class label per row | (n,) of 0/1 |
the final yes/no decision |
predict_proba(X) |
a probability per class per row | (n, 2); column 1 is P(churn) |
ranking metrics, costs, thresholds |
decision_function(X) |
a score: any real number, higher means “more positive” | (n,) |
ranking metrics when there is no predict_proba |
A decision threshold turns a score or probability into a label. predict flags a row when its probability is above 0.5 (or its score is above 0); an exact tie at 0.5 goes to class 0. You can choose a better threshold; a later section shows how.
flowchart LR
X["Customer row<br/>(features)"] --> M["Fitted classifier"]
M --> S["Probability or score<br/>predict_proba / decision_function"]
S --> T{"above<br/>the threshold?"}
T -->|yes| P["Label 1: churns"]
T -->|no| N["Label 0: stays"]
The churn data for this page
Section titled “The churn data for this page”The lesson page runs top to bottom in one namespace. The first block loads the libraries and the data and makes the same stratified train/test split as the data dictionary baseline. stratify=y keeps the churn rate equal in both parts.
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdfrom sklearn.compose import ColumnTransformerfrom sklearn.impute import SimpleImputerfrom sklearn.model_selection import train_test_splitfrom sklearn.pipeline import 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")num_cols = [ "age", "tenure_months", "monthly_charges", "total_charges", "support_tickets", "logins_last_30d", "avg_session_minutes", "has_autopay",]cat_cols = ["region", "plan", "contract", "payment_method"]X = customers[num_cols + cat_cols]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)print(X_train.shape, X_test.shape)print(f"churn rate: train {y_train.mean():.3f}, test {y_test.mean():.3f}")(3750, 12) (1250, 12)churn rate: train 0.193, test 0.193Many models need numbers on a common scale. The next function builds the preprocessing of module 34: fill the 10 blank total_charges with the median, standardize the numbers and one-hot encode the four text columns. drop="first" drops one level per text column. That level becomes the reference level of module 33, which makes the logistic regression coefficients easy to read later.
def make_preprocess() -> ColumnTransformer: """Impute and scale the numbers, one-hot encode the text columns.""" numeric = make_pipeline(SimpleImputer(strategy="median"), StandardScaler()) categorical = OneHotEncoder( drop="first", handle_unknown="ignore", sparse_output=False ) return ColumnTransformer( [("num", numeric, num_cols), ("cat", categorical, cat_cols)], verbose_feature_names_out=False, )It is a function, not one shared object, on purpose. A pipeline fits the exact object you give it. If two pipelines shared one preprocessor, fitting the second would overwrite what the first one learned.
Logistic regression
Section titled “Logistic regression”Logistic regression is the first model to try for a binary target. Module 32 built it from scratch. It computes a linear score from the features and squeezes the score into a probability with the sigmoid:
The score is the log-odds of churn, . The odds compare the chance of churn with the chance of staying: a probability of 0.2 is odds of 0.25, “1 to 4”.
from sklearn.linear_model import LogisticRegression
logreg = make_pipeline(make_preprocess(), LogisticRegression(max_iter=1000))logreg.fit(X_train, y_train)first3 = X_test.iloc[:3]print(logreg.predict_proba(first3).round(3))print(logreg.predict(first3))[[0.849 0.151] [0.703 0.297] [0.928 0.072]][0 0 0]Each row of predict_proba holds P(stay) and P(churn), and they add up to 1. predict returns 1 only when P(churn) is above 0.5. You can rebuild the probabilities from the fitted weights:
Z = logreg[:-1].transform(first3) # the 18 model inputs after preprocessingmodel = logreg[-1]log_odds = Z @ model.coef_[0] + model.intercept_[0]print("log-odds:", log_odds.round(3))print("sigmoid: ", (1 / (1 + np.exp(-log_odds))).round(3))log-odds: [-1.729 -0.862 -2.552]sigmoid: [0.151 0.297 0.072]logreg[:-1] is the pipeline without its last step, so it only transforms. The hand-made sigmoid matches column 1 of predict_proba. A logistic regression is a weighted sum and one sigmoid; nothing more.
Coefficients as odds ratios. Raise to the power of both sides of the score formula:
When feature grows by 1 and everything else stays fixed, the odds are multiplied by . This factor is the odds ratio of the feature. An odds ratio of 2 doubles the odds of churn. An odds ratio of 0.5 halves them. An odds ratio of 1 (coefficient 0) means no effect. Example 1 reads the full table.
Regularization. scikit-learn adds an L2 penalty to the log loss by default. A penalty is an extra cost for large weights; it keeps the model from trusting noise. The parameter C is the inverse of the penalty strength: smaller C means smaller weights. C=1.0 is the default and C=np.inf switches the penalty off. Because the penalty treats all weights alike, scale the features first.
The confusion matrix
Section titled “The confusion matrix”To judge predict, count the four ways a yes/no prediction can turn out:
| predicted 0 (stays) | predicted 1 (churns) | |
|---|---|---|
| actual 0 (stayed) | TN, true negative | FP, false positive: a needless offer |
| actual 1 (churned) | FN, false negative: a missed churner | TP, true positive: a churner found |
This table is the confusion matrix. scikit-learn puts the true classes in rows and the predicted classes in columns, sorted by label. For 0/1 labels, .ravel() returns the counts in the order TN, FP, FN, TP.
from sklearn.metrics import confusion_matrix
y_pred = logreg.predict(X_test)cm = confusion_matrix(y_test, y_pred)print(cm)tn, fp, fn, tp = cm.ravel()print(f"TN={tn} FP={fp} FN={fn} TP={tp}")[[972 37] [168 73]]TN=972 FP=37 FN=168 TP=73The model flags 110 customers. 73 of them really churn. It misses 168 churners, more than it finds. Every metric below is a different summary of these four numbers.
Accuracy, precision, recall and F1
Section titled “Accuracy, precision, recall and F1”- Accuracy is the share of correct labels.
- Precision answers: of the customers we flag, what share really churn? Low precision wastes offers.
- Recall (also sensitivity or true positive rate) answers: of the customers who churn, what share do we find? Low recall loses customers.
- F1 is the harmonic mean of the two, . It is high only when both are high.
- Specificity is the recall of the negative class, .
from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score
accuracy = (tp + tn) / (tp + tn + fp + fn)precision = tp / (tp + fp)recall = tp / (tp + fn)f1 = 2 * precision * recall / (precision + recall)print( f"by hand: acc {accuracy:.3f} prec {precision:.3f}" f" rec {recall:.3f} F1 {f1:.3f}")print( f"sklearn: acc {accuracy_score(y_test, y_pred):.3f}" f" prec {precision_score(y_test, y_pred):.3f}" f" rec {recall_score(y_test, y_pred):.3f}" f" F1 {f1_score(y_test, y_pred):.3f}")by hand: acc 0.836 prec 0.664 rec 0.303 F1 0.416sklearn: acc 0.836 prec 0.664 rec 0.303 F1 0.416An accuracy of 0.836 sounds good. Now compare it with a model that ignores every feature. A DummyClassifier with strategy="most_frequent" always predicts the most common class. Such a trivial reference model is a baseline.
from sklearn.dummy import DummyClassifier
dummy = DummyClassifier(strategy="most_frequent").fit(X_train, y_train)dummy_pred = dummy.predict(X_test)print(f"always 'stays': accuracy {accuracy_score(y_test, dummy_pred):.3f}")print(f"recall {recall_score(y_test, dummy_pred):.3f}")print(f"precision {precision_score(y_test, dummy_pred, zero_division=0):.3f}")always 'stays': accuracy 0.807recall 0.000precision 0.000This is why accuracy misleads at 19% churn. A model that never finds a single churner is right 80.7% of the time, because 80.7% of customers stay. The real model gains only 3 points of accuracy, yet it finds 73 churners instead of 0. On imbalanced data, report precision and recall (or the ranking metrics below), and always print the baseline next to your score. The dummy flags nobody, so its precision is 0/0; zero_division=0 reports it as 0 instead of warning.
ROC curve and ROC-AUC
Section titled “ROC curve and ROC-AUC”Precision and recall depend on the threshold. A ranking metric judges the probabilities themselves, for all thresholds at once.
Move the threshold from 1 down to 0. At each value, compute two rates:
The ROC curve (receiver operating characteristic) plots TPR against FPR. A random ranking gives the diagonal. A perfect one goes straight up to TPR 1, then right. ROC-AUC is the area under this curve. It has a plain meaning: the probability that a randomly chosen churner gets a higher score than a randomly chosen stayer.
from sklearn.metrics import roc_auc_score, roc_curve
p_test = logreg.predict_proba(X_test)[:, 1]fpr, tpr, roc_thresholds = roc_curve(y_test, p_test)print(f"{len(roc_thresholds)} thresholds on the curve")print(f"ROC-AUC: {roc_auc_score(y_test, p_test):.3f}")
is_churner = y_test.to_numpy() == 1pos, neg = p_test[is_churner], p_test[~is_churner]higher = (pos[:, None] > neg[None, :]).mean() # all churner-stayer pairstied = (pos[:, None] == neg[None, :]).mean()wins = higher + 0.5 * tiedprint(f"churner ranked above stayer in {wins:.3f} of all pairs")292 thresholds on the curveROC-AUC: 0.813churner ranked above stayer in 0.813 of all pairsThe check builds all 241 × 1,009 churner–stayer pairs with broadcasting and counts how often the churner scores higher (a tie counts half). The share equals the ROC-AUC. ROC-AUC needs scores, not labels: pass predict_proba(X)[:, 1] or decision_function(X), never predict(X).
Precision–recall curve and average precision
Section titled “Precision–recall curve and average precision”ROC-AUC counts false positives relative to the many stayers, so it can look good even when most flagged customers are false alarms. The precision–recall curve plots precision against recall for every threshold. Its summary is average precision (AP), often called PR-AUC:
and are the precision and recall at the -th threshold. AP is the precision averaged over all recall levels.
from sklearn.metrics import average_precision_score
print(f"average precision: {average_precision_score(y_test, p_test):.3f}")print(f"no-skill baseline: {y_test.mean():.3f}")average precision: 0.557no-skill baseline: 0.193A random ranking has an AP equal to the share of positives, 0.193 here, not 0.5. So read AP against the base rate: 0.56 is almost three times the no-skill level. Prefer AP to ROC-AUC when positives are rare and you care mostly about the flagged group: fraud, rare diseases, a short call list.
Log loss and the Brier score
Section titled “Log loss and the Brier score”Ranking metrics ignore whether the probabilities are right in size. A model that predicts 0.9 for every churner and 0.8 for every stayer ranks perfectly but is badly wrong. Two metrics judge the probabilities themselves. Lower is better for both.
Log loss (from module 32) punishes confident mistakes without limit. The Brier score is the mean squared error of the probabilities, between 0 (perfect) and 1.
from sklearn.metrics import brier_score_loss, log_loss
base_rate = np.full(len(y_test), y_train.mean())for name, p in [("base rate", base_rate), ("logistic", p_test)]: print( f"{name:<9} log loss {log_loss(y_test, p):.3f}" f" Brier {brier_score_loss(y_test, p):.3f}" )base rate log loss 0.490 Brier 0.156logistic log loss 0.382 Brier 0.119The base-rate model predicts 0.193 for everyone. The logistic model lowers both losses. Use these metrics when the probabilities feed a decision: an expected cost, a price, a risk score shown to a person.
k-nearest neighbors
Section titled “k-nearest neighbors”You met k-nearest neighbors (KNN) in module 33 and module 35. For classification, KNN finds the training customers closest to a new one and lets them vote. predict_proba returns the share of neighbors in each class.
from sklearn.neighbors import KNeighborsClassifier
knn = make_pipeline(make_preprocess(), KNeighborsClassifier(n_neighbors=50))knn.fit(X_train, y_train)knn_proba = knn.predict_proba(X_test)[:, 1]print("smallest distinct probabilities:", np.unique(knn_proba)[:6])print(f"ROC-AUC {roc_auc_score(y_test, knn_proba):.3f}")smallest distinct probabilities: [0. 0.02 0.04 0.06 0.08 0.1 ]ROC-AUC 0.796With 50 neighbors, every probability is a multiple of 1/50 = 0.02. KNN needs scaled features, because it compares customers by distance. A small follows noise; a large blurs the pattern. KNN stores the whole training set and computes distances at prediction time, so it gets slow on large data.
Gaussian naive Bayes
Section titled “Gaussian naive Bayes”Naive Bayes applies Bayes’ rule from module 32 with one bold simplification. It assumes that the features are independent of each other within each class. Then the probability of a whole row is the product of one small probability per feature:
is the prior: the share of each class in the training data. Gaussian naive Bayes models each as a normal curve with its own mean and variance per class. Training only computes these means and variances, so it takes milliseconds.
from sklearn.naive_bayes import GaussianNB
nb = make_pipeline(make_preprocess(), GaussianNB()).fit(X_train, y_train)nb_proba = nb.predict_proba(X_test)[:, 1]print("class priors:", nb[-1].class_prior_.round(3))print(f"ROC-AUC {roc_auc_score(y_test, nb_proba):.3f}")print(f"mean predicted churn {nb_proba.mean():.3f} vs true rate {y_test.mean():.3f}")class priors: [0.807 0.193]ROC-AUC 0.806mean predicted churn 0.345 vs true rate 0.193The ranking is decent. The probabilities are not: the model predicts 34.5% churn on average when the true rate is 19.3%. Two broken assumptions inflate the churn evidence. Correlated features (such as tenure_months and total_charges) carry the same signal, and the model counts it once per feature. And the 0/1 one-hot columns are not normal curves, so their fitted likelihoods are poor. The result here is one-sided: the model over-predicts churn. Naive Bayes is a fast baseline, and it is strong on word counts in text (module 41). Do not trust its probabilities without calibration.
Support vector machines
Section titled “Support vector machines”A support vector machine (SVM) looks for the boundary that separates the classes with the widest gap. The gap is the margin. The training points on the edge of the margin, or inside it, are the support vectors: they alone fix the boundary. The parameter C sets how many points may sit inside the margin; a large C allows few, which fits the training data more tightly.
A straight boundary is often not enough. A kernel lets the SVM draw curved boundaries by measuring similarity in a richer space without building that space. The default RBF kernel (radial basis function) scores two points as similar when they are close: . Because it uses distances, an SVM needs scaled features.
The breast cancer dataset bundled with scikit-learn shows how much scaling matters. Its 30 features range from below 0.01 to above 2,000. The target is 0 for malignant and 1 for benign.
from sklearn.datasets import load_breast_cancerfrom sklearn.svm import SVC
cancer = load_breast_cancer(as_frame=True)Xb_train, Xb_test, yb_train, yb_test = train_test_split( cancer.data, cancer.target, test_size=0.25, stratify=cancer.target, random_state=42,)print(cancer.data.shape, cancer.target_names.tolist())for name, svm_model in { "raw": SVC(), "scaled": make_pipeline(StandardScaler(), SVC()),}.items(): svm_model.fit(Xb_train, yb_train) print(f"{name:<6} accuracy {svm_model.score(Xb_test, yb_test):.3f}")(569, 30) ['malignant', 'benign']raw accuracy 0.923scaled accuracy 0.979score on a classifier returns the accuracy. Unscaled, the largest features decide every distance and the SVM loses 5.6 points.
An SVM has no natural probability. Its decision_function returns a signed score that grows with the distance from the boundary: positive means class 1, negative means class 0, and a larger size means more confidence.
svm = make_pipeline(StandardScaler(), SVC()).fit(Xb_train, yb_train)scores = svm.decision_function(Xb_test.iloc[:5])print("scores: ", scores.round(2))print("predict:", svm.predict(Xb_test.iloc[:5]))print("support vectors per class:", svm[-1].n_support_)svm_auc = roc_auc_score(yb_test, svm.decision_function(Xb_test))print(f"ROC-AUC from scores: {svm_auc:.3f}")scores: [ 1.33 -2.3 0.15 0.8 -0.05]predict: [1 0 1 1 0]support vectors per class: [50 46]ROC-AUC from scores: 0.997The sign of each score matches the label. Only 96 of 426 training rows are support vectors. For ROC-AUC and average precision, the scores are all you need.
Decision trees
Section titled “Decision trees”A decision tree asks a chain of yes/no questions about single features, such as “is tenure_months ≤ 5.5?”. Module 35 grew trees for prices. A classification tree differs in two places. Each leaf predicts the share of each class among its training rows. And each split is chosen to make the child nodes as pure as possible, measured by Gini impurity:
is the share of class in the node. A node with only stayers has . A 50/50 node has , the worst case for two classes. The whole training set, with 19.3% churners, has .
A tree compares one feature with a threshold at a time, so it needs no scaling. The next function keeps the numbers as they are and only one-hot encodes the text columns. scikit-learn trees accept the missing total_charges values directly.
from sklearn.tree import DecisionTreeClassifier, export_text
def make_tree_preprocess() -> ColumnTransformer: """Pass the numbers through unscaled, one-hot encode the text columns.""" categorical = OneHotEncoder(handle_unknown="ignore", sparse_output=False) return ColumnTransformer( [("num", "passthrough", num_cols), ("cat", categorical, cat_cols)], verbose_feature_names_out=False, )
small_tree = make_pipeline( make_tree_preprocess(), DecisionTreeClassifier(max_depth=2, random_state=42)).fit(X_train, y_train)names = list(small_tree[0].get_feature_names_out())print(export_text(small_tree[-1], feature_names=names, show_weights=True))|--- tenure_months <= 5.50| |--- support_tickets <= 3.50| | |--- weights: [353.00, 282.00] class: 0| |--- support_tickets > 3.50| | |--- weights: [19.00, 61.00] class: 1|--- tenure_months > 5.50| |--- logins_last_30d <= 3.50| | |--- weights: [155.00, 89.00] class: 0| |--- logins_last_30d > 3.50| | |--- weights: [2501.00, 290.00] class: 0show_weights=True prints the number of stayers and churners in each leaf. The first question is about tenure: customers in their first 5 months are at high risk. Among them, those with 4 or more support tickets churn in 61 of 80 cases (76%), and the leaf predicts class 1. The other leaves keep a majority of stayers, so they predict class 0, but their churn shares differ widely: 44%, 36% and 10%. Those shares are what predict_proba returns. A tree is easy to explain to a business team: it is a set of rules.
A tree with no depth limit keeps splitting until each leaf is pure. It then memorizes the training data. This is overfitting: excellent scores on the training data, worse scores on new data.
for depth in [3, 5, None]: tree_model = make_pipeline( make_tree_preprocess(), DecisionTreeClassifier(max_depth=depth, random_state=42), ).fit(X_train, y_train) auc_train = roc_auc_score(y_train, tree_model.predict_proba(X_train)[:, 1]) auc_test = roc_auc_score(y_test, tree_model.predict_proba(X_test)[:, 1]) print(f"max_depth={depth!s:<4} train ROC-AUC {auc_train:.3f} test {auc_test:.3f}")max_depth=3 train ROC-AUC 0.785 test 0.766max_depth=5 train ROC-AUC 0.839 test 0.791max_depth=None train ROC-AUC 1.000 test 0.678The unlimited tree scores 1.000 on the training data and the worst of the three on the test data. Limit the tree with max_depth, min_samples_leaf or ccp_alpha (cost-complexity pruning). Module 37 chooses these values with cross-validation.
Random forests
Section titled “Random forests”A random forest averages many deep trees. Each tree trains on a bootstrap sample: rows drawn at random with replacement from the training set. Each split considers only a random subset of the features (max_features="sqrt" by default). Training on resampled data and averaging is called bagging (bootstrap aggregating). The trees make different mistakes, and the average cancels many of them out. predict_proba returns the mean of the trees’ leaf shares.
from sklearn.ensemble import RandomForestClassifier
forest = make_pipeline( make_tree_preprocess(), RandomForestClassifier( n_estimators=300, min_samples_leaf=5, n_jobs=-1, random_state=42 ),).fit(X_train, y_train)forest_proba = forest.predict_proba(X_test)[:, 1]print(f"random forest ROC-AUC {roc_auc_score(y_test, forest_proba):.3f}")random forest ROC-AUC 0.833Three hundred trees beat every single tree above. A forest rarely needs tuning to be good, needs no scaling and is hard to overfit by adding trees. Its costs are size and speed: it stores every tree.
Gradient boosting: HistGradientBoosting, XGBoost and LightGBM
Section titled “Gradient boosting: HistGradientBoosting, XGBoost and LightGBM”Gradient boosting builds small trees one after another. Each new tree corrects the errors of the trees before it. For classification, the model adds up the trees’ outputs as a log-odds score, and the sigmoid turns the score into a probability:
is the -th tree. It is fitted to the gradient of the log loss: how far each training probability is from its 0/1 label. The learning rate shrinks each step. A small rate needs more trees but usually generalizes better.
Three implementations dominate tabular data. All three sort the values of each feature into a few hundred bins at most (a histogram; 255 by default in scikit-learn and LightGBM) and search splits between bins, which makes training fast. All three handle missing values and categorical columns natively.
| scikit-learn | XGBoost | LightGBM | |
|---|---|---|---|
| Class | HistGradientBoostingClassifier |
xgboost.XGBClassifier |
lightgbm.LGBMClassifier |
| Number of trees | max_iter=100 |
n_estimators (100 when unset) |
n_estimators=100 |
| Learning rate | learning_rate=0.1 |
learning_rate (0.3 when unset) |
learning_rate=0.1 |
| Tree size | max_leaf_nodes=31, max_depth |
max_depth=6 |
num_leaves=31 |
| Category columns | categorical_features="from_dtype" (default) |
enable_categorical=True |
pandas category columns, automatic |
| Early stopping | early_stopping="auto" (on above 10,000 rows) |
early_stopping_rounds=n + fit(eval_set=...) |
fit(eval_X=..., eval_y=..., callbacks=[lightgbm.early_stopping(n)]) |
| Silence | quiet by default | quiet by default | verbose=-1 |
All three read pandas category columns. Build one CategoricalDtype per column from the training data and apply it to every split. This fixes the schema: every split has the same levels in the same order, and a level that never appeared in training becomes a missing value instead of a silent new category.
from sklearn.ensemble import HistGradientBoostingClassifier
cat_dtypes = { col: pd.CategoricalDtype(sorted(X_train[col].unique())) for col in cat_cols}X_train_cat = X_train.astype(cat_dtypes)X_test_cat = X_test.astype(cat_dtypes)
hgb = HistGradientBoostingClassifier(random_state=42).fit(X_train_cat, y_train)hgb_proba = hgb.predict_proba(X_test_cat)[:, 1]print(X_train_cat["contract"].cat.categories.tolist())print(f"HistGradientBoosting ROC-AUC {roc_auc_score(y_test, hgb_proba):.3f}")['month-to-month', 'one-year', 'two-year']HistGradientBoosting ROC-AUC 0.825No imputer, no scaler, no encoder: the model reads the raw columns. Its ROC-AUC of 0.825 matches the reference score in the data dictionary. Example 2 adds XGBoost and LightGBM.
Thresholds and the precision–recall trade-off
Section titled “Thresholds and the precision–recall trade-off”The default threshold of 0.5 is a convention, not a law. Lower the threshold and the model flags more customers: recall rises and precision falls. Raise it and the opposite happens. The right threshold depends on what a false positive and a false negative cost.
Choose the threshold on data that the model did not train on and that is not the test set. If you try many thresholds on the test set and keep the best, the test score is no longer an honest estimate. Split a validation set off the training data for such decisions:
X_fit, X_val, y_fit, y_val = train_test_split( X_train, y_train, test_size=0.25, stratify=y_train, random_state=42)logreg_fit = make_pipeline(make_preprocess(), LogisticRegression(max_iter=1000))logreg_fit.fit(X_fit, y_fit)p_val = logreg_fit.predict_proba(X_val)[:, 1]print(f"fit {len(X_fit)} rows, validation {len(X_val)} rows")for threshold in [0.2, 0.3, 0.4, 0.5, 0.6]: flag = (p_val >= threshold).astype(int) print( f"threshold {threshold:.1f}: flagged {flag.sum():>3}" f" precision {precision_score(y_val, flag):.3f}" f" recall {recall_score(y_val, flag):.3f}" )fit 2812 rows, validation 938 rowsthreshold 0.2: flagged 321 precision 0.402 recall 0.713threshold 0.3: flagged 210 precision 0.486 recall 0.564threshold 0.4: flagged 127 precision 0.559 recall 0.392threshold 0.5: flagged 68 precision 0.647 recall 0.243threshold 0.6: flagged 34 precision 0.794 recall 0.149At 0.2 the team calls many customers and finds most churners. At 0.6 the calls are accurate but rare. Neither is “correct”. A cost turns the trade-off into a decision. This page flags a customer when the probability is at or above the threshold (>=), as FixedThresholdClassifier does; predict needs strictly more than 0.5. With continuous probabilities, exact ties almost never happen.
Suppose a retention offer costs c_offer per contacted customer, and an unflagged churner costs c_loss in lost revenue. Assume the offer keeps a churner. For a customer with churn probability , flagging costs c_offer for sure; not flagging costs c_loss with probability . Flag when
With an offer at USD 50 and a lost customer at USD 300, . The formula changes with the cost structure. In the classic cost matrix, a correct flag costs nothing, a false alarm costs and a miss costs . Then flag when , so . Either way, the rule trusts the probabilities, so it works only for a calibrated model. Example 4 checks it on the validation set.
Calibration
Section titled “Calibration”A model is calibrated when its probabilities match reality: among customers who get 0.3, about 30% churn. Ranking metrics do not check this; a model can have a high ROC-AUC and poor calibration.
A calibration curve (or reliability diagram) shows it. Sort the predictions into bins, then plot the mean predicted probability of each bin against the observed churn rate in that bin. A calibrated model lies on the diagonal. A curve below the diagonal means the model predicts too much churn.
CalibratedClassifierCV fixes a model’s probabilities. It fits the model on part of the training data and a calibrator (a small 1-D model from the raw probability or score to a corrected probability) on the rest, with cross-validation:
method= |
Calibrator | Use it when |
|---|---|---|
"sigmoid" (default) |
Platt scaling: a logistic regression on the model’s score | few calibration rows, or an S-shaped distortion (SVMs) |
"isotonic" |
isotonic regression: a free-form increasing step function | more than about 1,000 calibration rows (training rows ÷ cv); any monotonic distortion |
"temperature" |
divides the multiclass log-odds by one learned number | multiclass models |
Calibration changes the probabilities, not the order of the customers, so ROC-AUC stays almost the same. Logistic regression is usually well calibrated already, because it minimizes the log loss directly. Naive Bayes and SVM scores usually need calibration. Example 5 plots the curves.
Multiclass classification
Section titled “Multiclass classification”A classifier handles three or more classes in one of three ways:
| Strategy | How it works | Models for classes | In scikit-learn |
|---|---|---|---|
| One-vs-rest (OvR) | one binary model per class: “this class or any other” | OneVsRestClassifier(model) |
|
| One-vs-one (OvO) | one binary model per pair of classes; the pairs vote | OneVsOneClassifier(model); SVC does this inside |
|
| Native multiclass | one model for all classes; trees and forests count class shares in their leaves, logistic regression (multinomial) and boosting give a score per class and apply the softmax | 1 | LogisticRegression (default), trees, forests, boosting |
The softmax generalizes the sigmoid to classes. It makes every probability positive and makes them add up to 1:
Per-class metrics work as in the binary case: each class in turn is “positive”. To get one number, average the per-class values:
- The macro average is the plain mean over classes. Every class counts the same, so a weak rare class pulls it down.
- The weighted average weights each class by its support (its number of true rows). Large classes dominate.
- The micro average pools all TP, FP and FN first. For single-label multiclass problems, micro precision, micro recall and micro F1 all equal accuracy.
classification_report prints the per-class precision, recall, F1 and support, plus the averages. Even the binary churn report shows how far macro and weighted can drift apart on imbalanced data:
from sklearn.metrics import classification_report
print(classification_report(y_test, y_pred, target_names=["stays", "churns"], digits=3)) precision recall f1-score support
stays 0.853 0.963 0.905 1009 churns 0.664 0.303 0.416 241
accuracy 0.836 1250 macro avg 0.758 0.633 0.660 1250weighted avg 0.816 0.836 0.810 1250The weighted F1 of 0.810 is mostly the easy class “stays”. The macro F1 of 0.660 gives the rare class “churns” equal weight and exposes its F1 of 0.416. For a churn project, report the churn row itself. Example 6 works through a real multiclass problem.
Worked examples
Section titled “Worked examples”Example 1 — Explain churn drivers with odds ratios
Section titled “Example 1 — Explain churn drivers with odds ratios”Goal: The retention manager asks “what drives churn, and by how much?”. Turn the logistic regression coefficients into odds ratios with clear units.
Step 1 — Collect the coefficients with their names
Section titled “Step 1 — Collect the coefficients with their names”names = logreg[:-1].get_feature_names_out()coefs = pd.DataFrame({"coef": logreg[-1].coef_[0]}, index=names)coefs["odds_ratio"] = np.exp(coefs["coef"])print(coefs.sort_values("coef")) coef odds_ratiocontract_two-year -1.726 0.178contract_one-year -1.052 0.349tenure_months -0.916 0.400plan_standard -0.369 0.691logins_last_30d -0.278 0.757region_South -0.261 0.770payment_method_credit_card -0.208 0.812payment_method_paypal -0.167 0.846plan_premium -0.135 0.874age -0.111 0.895has_autopay -0.103 0.902avg_session_minutes -0.072 0.930region_West 0.031 1.032region_North 0.050 1.052total_charges 0.157 1.169payment_method_electronic_check 0.372 1.450monthly_charges 0.454 1.574support_tickets 0.543 1.721get_feature_names_out returns the 18 input names in the same order as the coefficients. Negative coefficients (odds ratio below 1) lower the churn risk; positive ones raise it.
Step 2 — Find the reference categories
Section titled “Step 2 — Find the reference categories”encoder = logreg[0].named_transformers_["cat"]for col, levels, dropped in zip(cat_cols, encoder.categories_, encoder.drop_idx_): print(f"{col:<15} reference: {levels[dropped]}")region reference: Eastplan reference: basiccontract reference: month-to-monthpayment_method reference: bank_transferA one-hot coefficient compares a level with the dropped reference level. contract_two-year has an odds ratio of 0.178: a two-year customer has 0.18 times the churn odds of an otherwise identical month-to-month customer, an 82% cut. Electronic check raises the odds by 45% compared with bank transfer.
Step 3 — Convert scaled coefficients to real units
Section titled “Step 3 — Convert scaled coefficients to real units”scaler = logreg[0].named_transformers_["num"][-1]per_sd = coefs.loc[num_cols, "coef"]per_unit = per_sd / scaler.scale_ # scale_ is each column's standard deviationeffects = pd.DataFrame({ "sd": scaler.scale_, "OR per sd": np.exp(per_sd), "OR per unit": np.exp(per_unit),})print(effects.loc[["tenure_months", "support_tickets", "monthly_charges"]]) sd OR per sd OR per unittenure_months 19.870 0.400 0.955support_tickets 1.159 1.721 1.597monthly_charges 22.985 1.574 1.020The numeric inputs were standardized, so their coefficients are per standard deviation. Dividing by the standard deviation gives the effect per real unit. Each extra support ticket multiplies the churn odds by 1.60. Each extra month of tenure multiplies them by 0.955, a 4.5% cut per month.
Step 4 — Verify an odds ratio on one customer
Section titled “Step 4 — Verify an odds ratio on one customer”customer = X_test.iloc[[0]].copy()p_before = logreg.predict_proba(customer)[0, 1]customer["support_tickets"] += 1p_after = logreg.predict_proba(customer)[0, 1]
def odds(p: float) -> float: return p / (1 - p)
print(f"P(churn): {p_before:.3f} -> {p_after:.3f}")print(f"odds ratio: {odds(p_after) / odds(p_before):.3f}")print(f"expected: {effects.loc['support_tickets', 'OR per unit']:.3f}")P(churn): 0.151 -> 0.221odds ratio: 1.597expected: 1.597One more ticket multiplies the odds by exactly the odds ratio. This is true for every customer, because the log-odds are linear in the features.
Step 5 — See that an odds ratio is not a probability ratio
Section titled “Step 5 — See that an odds ratio is not a probability ratio”odds_ratio = effects.loc["support_tickets", "OR per unit"] # 1.597for p in [0.05, 0.20, 0.50, 0.90]: new_odds = odds(p) * odds_ratio p_new = new_odds / (1 + new_odds) print(f"P {p:.2f} -> {p_new:.3f} (+{p_new - p:.3f})")P 0.05 -> 0.078 (+0.028)P 0.20 -> 0.285 (+0.085)P 0.50 -> 0.615 (+0.115)P 0.90 -> 0.935 (+0.035)The same odds ratio adds 2.8 points to a low-risk customer and 11.5 points to a 50/50 customer. Say “one more ticket raises the odds of churn by 60%”, not “raises churn by 60%”.
Common mistakes:
- Reading coefficients of unscaled features against each other. A coefficient per dollar and a coefficient per ticket are in different units. Compare per standard deviation, or convert to real units as in Step 3.
- Forgetting the reference category.
contract_one-yearis relative to month-to-month, not to “average”. - Reading coefficients as causes. They describe associations in this data. Correlated features (
tenure_monthsandtotal_charges) share their effect in unstable ways.
Example 2 — Compare nine classifiers with cross-validation
Section titled “Example 2 — Compare nine classifiers with cross-validation”Goal: Pick the model for the churn score. Compare nine classifiers fairly: the same features, 5-fold stratified cross-validation on the training set, and the test set used once at the end.
Step 1 — Define the candidates
Section titled “Step 1 — Define the candidates”from lightgbm import LGBMClassifierfrom xgboost import XGBClassifier
candidates = { "dummy (most frequent)": DummyClassifier(strategy="most_frequent"), "logistic regression": make_pipeline( make_preprocess(), LogisticRegression(max_iter=1000) ), "KNN (k=50)": make_pipeline( make_preprocess(), KNeighborsClassifier(n_neighbors=50) ), "Gaussian naive Bayes": make_pipeline(make_preprocess(), GaussianNB()), "SVM (RBF)": make_pipeline(make_preprocess(), SVC()), "decision tree (depth 5)": make_pipeline( make_tree_preprocess(), DecisionTreeClassifier(max_depth=5, random_state=42) ), "random forest": make_pipeline( make_tree_preprocess(), RandomForestClassifier( n_estimators=300, min_samples_leaf=5, n_jobs=-1, random_state=42 ), ), "HistGradientBoosting": HistGradientBoostingClassifier(random_state=42), "XGBoost": XGBClassifier( n_estimators=200, learning_rate=0.05, max_depth=4, enable_categorical=True, n_jobs=4, random_state=42, ), "LightGBM": LGBMClassifier( n_estimators=200, learning_rate=0.05, num_leaves=15, n_jobs=4, verbose=-1, random_state=42, ),}print(len(candidates), "models")10 modelsTen entries: nine classifiers plus the dummy baseline. Every model reads X_train_cat. The pipelines one-hot encode the category columns; the three boosting models use them natively. The boosting models get small, fixed settings. Module 37 tunes them.
Step 2 — Cross-validate every model on the training set
Section titled “Step 2 — Cross-validate every model on the training set”from sklearn.model_selection import StratifiedKFold, cross_validate
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)rows = []for name, candidate in candidates.items(): scoring = ["roc_auc", "average_precision"] if hasattr(candidate, "predict_proba"): scoring += ["neg_log_loss", "neg_brier_score"] result = cross_validate(candidate, X_train_cat, y_train, cv=cv, scoring=scoring) rows.append({ "model": name, "roc_auc": result["test_roc_auc"].mean(), "auc_std": result["test_roc_auc"].std(), "pr_auc": result["test_average_precision"].mean(), "log_loss": -result.get("test_neg_log_loss", np.array([np.nan])).mean(), "brier": -result.get("test_neg_brier_score", np.array([np.nan])).mean(), })print(f"{len(rows)} models x {cv.get_n_splits()} folds done")10 models x 5 folds donecross_validate fits each model 5 times, each time on 4 folds, and scores it on the fifth. The scorers roc_auc and average_precision try decision_function first and fall back to predict_proba, so every model, including the SVM, gets a ranking score. The SVM has no predict_proba, so it gets no log loss or Brier score. Losses come negated (“greater is better” for every scorer), so the code flips their sign.
Step 3 — Build the comparison table
Section titled “Step 3 — Build the comparison table”comparison = pd.DataFrame(rows).set_index("model")comparison = comparison.sort_values("roc_auc", ascending=False)print(comparison.round(3)) roc_auc auc_std pr_auc log_loss briermodelXGBoost 0.840 0.009 0.604 0.360 0.112random forest 0.837 0.010 0.594 0.365 0.113LightGBM 0.835 0.016 0.605 0.366 0.113HistGradientBoosting 0.821 0.013 0.587 0.394 0.118logistic regression 0.813 0.012 0.553 0.384 0.119Gaussian naive Bayes 0.805 0.012 0.544 0.639 0.175decision tree (depth 5) 0.794 0.022 0.502 0.502 0.124SVM (RBF) 0.791 0.020 0.545 NaN NaNKNN (k=50) 0.780 0.019 0.488 0.418 0.129dummy (most frequent) 0.500 0.000 0.193 6.940 0.193The table is the model-comparison report. Read it column by column:
- Ranking. XGBoost, the random forest and LightGBM lead with ROC-AUC 0.835 to 0.840. Their gaps are smaller than the fold-to-fold spread
auc_std(0.009 to 0.016), so the order among the three is not reliable. HistGradientBoosting at default settings (0.821) and logistic regression (0.813) follow. - Rare class. PR-AUC tells the same story with bigger gaps: 0.60 at the top, 0.49 for KNN. The baseline sits at the churn rate, 0.193.
- Probabilities. Naive Bayes ranks better than the tree, the SVM and KNN, but it has the worst log loss and Brier score of the real models: its probabilities are badly calibrated. The dummy predicts a churn probability of exactly 0. scikit-learn clips it to a tiny number, so each churner costs about 36, which averages to 6.94 over all customers.
- Baseline. The dummy’s ROC-AUC of 0.5 is the floor every real model must clear.
- Simplicity. Logistic regression is only 0.027 behind the leader, trains in milliseconds and explains itself with odds ratios (Example 1). That trade-off is a business decision, not a statistical one.
Step 4 — Score the chosen model once on the test set
Section titled “Step 4 — Score the chosen model once on the test set”best_name = comparison.index[0]best = candidates[best_name].fit(X_train_cat, y_train)best_proba = best.predict_proba(X_test_cat)[:, 1]print(best_name)print(f"test ROC-AUC {roc_auc_score(y_test, best_proba):.3f}")print(f"test PR-AUC {average_precision_score(y_test, best_proba):.3f}")print(f"test Brier {brier_score_loss(y_test, best_proba):.3f}")XGBoosttest ROC-AUC 0.838test PR-AUC 0.595test Brier 0.113The test scores land close to the cross-validation means. That agreement is the point of keeping the test set out of every decision: it gives an honest estimate of performance on new customers.
Common mistakes:
- Comparing models on the test set and keeping the winner. With ten models, the best test score is partly luck. Compare with cross-validation on the training set; test once.
- Reporting accuracy only. In this table, accuracy would range from 0.807 (dummy) to about 0.84 and hide most of the differences.
- Calling
roc_aucon an SVM’spredict. The labels throw away the ranking. The built-in scorer usesdecision_functionfor you; your own code must do the same.
Example 3 — Draw ROC and precision–recall curves
Section titled “Example 3 — Draw ROC and precision–recall curves”Goal: Show the retention team how the logistic model and the best boosting model trade found churners against false alarms, at every threshold.
Step 1 — Plot the ROC curves
Section titled “Step 1 — Plot the ROC curves”from sklearn.metrics import PrecisionRecallDisplay, RocCurveDisplay
fig, ax = plt.subplots(figsize=(5.5, 5))RocCurveDisplay.from_predictions(y_test, p_test, name="logistic regression", ax=ax)RocCurveDisplay.from_predictions( y_test, best_proba, name=best_name, ax=ax, plot_chance_level=True)ax.set_title("ROC curves on the test set")plt.show()
Both curves rise steeply at first: the customers with the highest scores are mostly churners. The legend shows each area under the curve. A curve closer to the top-left corner ranks better.
Step 2 — Plot the precision–recall curves
Section titled “Step 2 — Plot the precision–recall curves”fig, ax = plt.subplots(figsize=(5.5, 5))PrecisionRecallDisplay.from_predictions( y_test, p_test, name="logistic regression", ax=ax)PrecisionRecallDisplay.from_predictions( y_test, best_proba, name=best_name, ax=ax, plot_chance_level=True)ax.set_title("Precision–recall curves on the test set")plt.show()
Precision starts high for the few most risky customers and falls as the model reaches for more churners. The dashed line is the no-skill level at the churn rate. This plot makes the cost of high recall visible; the ROC plot hides it.
Step 3 — Read one operating point
Section titled “Step 3 — Read one operating point”from sklearn.metrics import precision_recall_curve
for label, proba in [("logistic regression", p_test), (best_name, best_proba)]: prec, rec, _ = precision_recall_curve(y_test, proba) at_least = rec >= 0.6 print(f"{label:<20} best precision at recall >= 0.6: {prec[at_least].max():.3f}")logistic regression best precision at recall >= 0.6: 0.463XGBoost best precision at recall >= 0.6: 0.604Suppose the team wants to find 60% of churners. With XGBoost, 60% of the called customers really churn; with logistic regression, only 46% do. At this operating point the gap is far larger than the 0.025 gap in ROC-AUC suggests. precision_recall_curve returns one precision and recall per threshold (plus a final point at recall 0). Masking with rec >= 0.6 keeps the thresholds that reach the recall target.
Common mistakes:
- Plotting curves from
predictlabels. A label gives one point, not a curve. - Reading the ROC curve alone on rare positives. A low false positive rate of 0.1 is still 101 false alarms among 1,009 stayers.
- Choosing a threshold from these test-set curves. They are for reporting. Choose thresholds on validation data (Example 4).
Example 4 — Choose a threshold by business cost
Section titled “Example 4 — Choose a threshold by business cost”Goal: A retention offer costs USD 50 per contacted customer. A lost churner costs USD 300. Find the threshold with the lowest total cost on the validation set, then report the cost on the test set once.
Step 1 — Write the cost function
Section titled “Step 1 — Write the cost function”COST_OFFER, COST_LOSS = 50, 300
def campaign_cost(y_true, flagged) -> int: """Pay an offer for every flagged customer and the loss for every missed churner.""" tn, fp, fn, tp = confusion_matrix(y_true, flagged, labels=[0, 1]).ravel() return int(COST_OFFER * (tp + fp) + COST_LOSS * fn)
print(f"theoretical threshold: {COST_OFFER / COST_LOSS:.3f}")print(f"validation, call nobody: {campaign_cost(y_val, np.zeros(len(y_val))):,}")print(f"validation, call all: {campaign_cost(y_val, np.ones(len(y_val))):,}")theoretical threshold: 0.167validation, call nobody: 54,300validation, call all: 46,900labels=[0, 1] keeps the matrix 2 × 2 even when one class is never predicted, as in the “call nobody” plan. The two trivial plans set the range that a model must beat.
Step 2 — Score every threshold on the validation set
Section titled “Step 2 — Score every threshold on the validation set”thresholds = np.round(np.arange(0.05, 0.80, 0.01), 2)costs = np.array([campaign_cost(y_val, p_val >= t) for t in thresholds])best_t = thresholds[costs.argmin()]print(f"best validation threshold: {best_t:.2f}, cost {costs.min():,}")print(f"validation cost at 0.50: {costs[thresholds == 0.5][0]:,}")best validation threshold: 0.16, cost 29,950validation cost at 0.50: 44,500p_val comes from logreg_fit, the model trained on X_fit only. The validation optimum, 0.16, sits right at the theoretical 1/6. That agreement is a sign that the logistic probabilities are well calibrated.
Step 3 — Plot the cost curve
Section titled “Step 3 — Plot the cost curve”fig, ax = plt.subplots(figsize=(6.5, 3.5))ax.plot(thresholds, costs / 1000)ax.axvline(best_t, color="gray", ls="--", lw=1)ax.annotate(f"minimum at {best_t:.2f}", (best_t, costs.min() / 1000), xytext=(0.3, costs.min() / 1000 + 2), arrowprops={"arrowstyle": "->"})ax.set_xlabel("decision threshold")ax.set_ylabel("campaign cost (USD thousands)")ax.set_title("Validation cost by threshold")plt.show()
To the left of the minimum, the team pays for many offers to customers who would stay. To the right, it loses churners it could have kept. The curve is flat near the minimum, so any threshold between about 0.13 and 0.20 costs almost the same.
Step 4 — Report the test cost once
Section titled “Step 4 — Report the test cost once”p_test_fit = logreg_fit.predict_proba(X_test)[:, 1]for label, t in [("default 0.50", 0.5), (f"chosen {best_t:.2f}", best_t)]: flagged = p_test_fit >= t print( f"{label:<13} flagged {flagged.sum():>4}" f" recall {recall_score(y_test, flagged):.3f}" f" cost {campaign_cost(y_test, flagged):,}" )print(f"call nobody cost {campaign_cost(y_test, np.zeros(len(y_test))):,}")default 0.50 flagged 102 recall 0.286 cost 56,700chosen 0.16 flagged 561 recall 0.809 cost 41,850call nobody cost 72,300On new customers, the chosen threshold cuts the campaign cost by about a quarter compared with 0.5. It flags five times more customers and finds 81% of churners instead of 29%. The threshold was fixed before the test set was opened, so this saving is an honest estimate.
Step 5 — Compare the confusion matrices
Section titled “Step 5 — Compare the confusion matrices”from sklearn.metrics import ConfusionMatrixDisplay
fig, axes = plt.subplots(1, 2, figsize=(9, 4))for ax, t in zip(axes, [0.5, best_t]): ConfusionMatrixDisplay.from_predictions( y_test, (p_test_fit >= t).astype(int), display_labels=["stays", "churns"], ax=ax, colorbar=False, ) ax.set_title(f"threshold {t:.2f}")plt.tight_layout()plt.show()
The bottom row is the churners. At 0.16, most of them move from “missed” to “found”. The price is in the top right: 366 stayers get an offer they did not need. At USD 50 per offer and USD 300 per lost customer, that trade pays.
Step 6 — Let scikit-learn tune the threshold with cross-validation
Section titled “Step 6 — Let scikit-learn tune the threshold with cross-validation”from sklearn.metrics import make_scorerfrom sklearn.model_selection import StratifiedKFold, TunedThresholdClassifierCV
cost_scorer = make_scorer(campaign_cost, greater_is_better=False)tuned = TunedThresholdClassifierCV( make_pipeline(make_preprocess(), LogisticRegression(max_iter=1000)), scoring=cost_scorer, cv=StratifiedKFold(n_splits=5, shuffle=True, random_state=42),).fit(X_train, y_train)print(f"tuned threshold: {tuned.best_threshold_:.3f}")print(f"test cost: {campaign_cost(y_test, tuned.predict(X_test)):,}")tuned threshold: 0.195test cost: 41,400TunedThresholdClassifierCV repeats Steps 2–4 inside the training data: it scores many thresholds on each validation fold, keeps the one with the lowest mean cost, then refits the model on all training rows. predict then applies the tuned threshold. Its threshold need not equal the manual 0.16: it averages five different folds instead of one validation set, and the cost curve is so flat near its minimum that small differences in the data move the optimum. The test cost is what matters, and it is close to the manual result. Use this tool when you have no spare rows for a fixed validation set.
Common mistakes:
- Tuning the threshold on the test set. The test cost then looks better than it will be in production.
- Using the default 0.5 because it “looks neutral”. It is neutral only when both errors cost the same.
- Applying to an uncalibrated model. The formula assumes that 0.2 means a 20% risk. Check calibration first (Example 5).
Example 5 — Calibrate churn probabilities
Section titled “Example 5 — Calibrate churn probabilities”Goal: The finance team wants to multiply each churn probability by the customer’s revenue. Check which models give trustworthy probabilities, fix naive Bayes, and get probabilities from the SVM without probability=True. Every choice uses the validation set of the threshold section; the test set is read once, in the last step.
Step 1 — Draw calibration curves on the validation set
Section titled “Step 1 — Draw calibration curves on the validation set”from sklearn.calibration import CalibrationDisplay
forest_fit = make_pipeline( make_tree_preprocess(), RandomForestClassifier( n_estimators=300, min_samples_leaf=5, n_jobs=-1, random_state=42 ),).fit(X_fit, y_fit)nb_fit = make_pipeline(make_preprocess(), GaussianNB()).fit(X_fit, y_fit)fig, ax = plt.subplots(figsize=(5.5, 5))for label, proba in [ ("logistic regression", p_val), ("random forest", forest_fit.predict_proba(X_val)[:, 1]), ("Gaussian naive Bayes", nb_fit.predict_proba(X_val)[:, 1]),]: CalibrationDisplay.from_predictions( y_val, proba, n_bins=6, strategy="quantile", name=label, ax=ax )ax.set_title("Calibration curves on the validation set")plt.show()
All three models trained on X_fit only. strategy="quantile" puts the same number of customers in each bin, so every point rests on about 156 validation customers. Logistic regression and the forest follow the diagonal. Naive Bayes sits far below it: when it says 80%, far fewer customers churn. So naive Bayes needs calibration, and the other two do not.
Step 2 — Choose a calibration method for naive Bayes
Section titled “Step 2 — Choose a calibration method for naive Bayes”from sklearn.calibration import CalibratedClassifierCV
print(f"{'naive Bayes':<20} {'Brier':>6} {'log loss':>8} {'ROC-AUC':>8} {'mean p':>7}")val_brier = {}for label, model_nb in [ ("raw", nb_fit), ("sigmoid", CalibratedClassifierCV( make_pipeline(make_preprocess(), GaussianNB()), method="sigmoid", cv=5)), ("isotonic", CalibratedClassifierCV( make_pipeline(make_preprocess(), GaussianNB()), method="isotonic", cv=5)),]: proba = model_nb.fit(X_fit, y_fit).predict_proba(X_val)[:, 1] val_brier[label] = brier_score_loss(y_val, proba) print( f"{label:<20} {val_brier[label]:>6.3f}" f" {log_loss(y_val, proba):>8.3f} {roc_auc_score(y_val, proba):>8.3f}" f" {proba.mean():>7.3f}" )best_method = min(["sigmoid", "isotonic"], key=val_brier.get)print("chosen on validation:", best_method)naive Bayes Brier log loss ROC-AUC mean praw 0.179 0.653 0.796 0.326sigmoid 0.125 0.404 0.796 0.186isotonic 0.120 0.390 0.796 0.183chosen on validation: isotonicBoth calibrators cut the Brier score by about a third and the log loss by a third or more. The mean prediction drops to about the true churn rate of 0.19. ROC-AUC barely moves, because calibration keeps the order of the customers. With cv=5, each calibrator learns from one fold of X_fit, about 560 calibration rows (training rows ÷ cv). That is below the 1,000 rows that isotonic regression likes, yet the two methods score almost the same here. The validation Brier score makes the choice.
Step 3 — Get probabilities from an SVM
Section titled “Step 3 — Get probabilities from an SVM”svm_churn = make_pipeline(make_preprocess(), SVC()).fit(X_fit, y_fit)svm_cal = CalibratedClassifierCV( make_pipeline(make_preprocess(), SVC()), ensemble=False, cv=5).fit(X_fit, y_fit)svm_proba = svm_cal.predict_proba(X_val)[:, 1]print(f"ROC-AUC from decision_function: " f"{roc_auc_score(y_val, svm_churn.decision_function(X_val)):.3f}")print(f"ROC-AUC from calibrated proba: {roc_auc_score(y_val, svm_proba):.3f}")print(f"Brier {brier_score_loss(y_val, svm_proba):.3f}, mean p {svm_proba.mean():.3f}")ROC-AUC from decision_function: 0.798ROC-AUC from calibrated proba: 0.798Brier 0.128, mean p 0.189ensemble=False fits one SVM on all its training rows and one sigmoid calibrator on out-of-fold scores. This is the documented replacement for SVC(probability=True). The ranking stays the same, and the SVM now gives probabilities with a reasonable Brier score.
Step 4 — Forecast churners and lost revenue on the test set
Section titled “Step 4 — Forecast churners and lost revenue on the test set”nb_cal = CalibratedClassifierCV( make_pipeline(make_preprocess(), GaussianNB()), method=best_method, cv=5).fit(X_train, y_train)charges = X_test["monthly_charges"].to_numpy()print(f"{'':<22} {'churners':>8} {'lost revenue':>13}")print(f"{'actual':<22} {y_test.sum():>8} {charges[is_churner].sum():>13,.0f}")for label, proba in [ ("raw naive Bayes", nb_proba), ("calibrated naive Bayes", nb_cal.predict_proba(X_test)[:, 1]), ("logistic regression", p_test),]: print(f"{label:<22} {proba.sum():>8.0f} {(proba * charges).sum():>13,.0f}") churners lost revenueactual 241 16,258raw naive Bayes 431 27,621calibrated naive Bayes 252 16,466logistic regression 250 16,531The method was chosen on validation data, so the final models are refitted on all training rows and the test set is read once. The sum of the probabilities is the expected number of churners, and the probability times the monthly charge is the expected lost revenue. The raw naive Bayes forecast is far too high, so a budget built on it would be wrong. After calibration, the forecast is close to the truth, and so is the logistic forecast. A ranking metric would never reveal this problem: it sits entirely in the size of the probabilities.
Common mistakes:
- Calibrating on the training rows that fitted the model. The calibrator then learns from overconfident training scores.
CalibratedClassifierCVuses cross-validation to avoid this. - Expecting calibration to raise ROC-AUC. It fixes the size of the probabilities, not their order.
- Using isotonic calibration on a few hundred calibration rows. The step function overfits; use
method="sigmoid". - Choosing the calibration method on the test set. Compare methods on validation data, then report once.
Example 6 — Classify wines into three cultivars
Section titled “Example 6 — Classify wines into three cultivars”Goal: A lab measures only two cheap features of a wine, the alcohol and the flavanoid content. Predict which of three cultivars (grape varieties) it comes from, and report per-class results.
Step 1 — Load the wine data
Section titled “Step 1 — Load the wine data”from sklearn.datasets import load_wine
wine = load_wine(as_frame=True)wine_X = wine.data[["alcohol", "flavanoids"]]wine_y = wine.targetprint(wine_y.value_counts().sort_index().to_dict())Xw_train, Xw_test, yw_train, yw_test = train_test_split( wine_X, wine_y, test_size=0.3, stratify=wine_y, random_state=42)print(Xw_train.shape, Xw_test.shape){0: 59, 1: 71, 2: 48}(124, 2) (54, 2)The 178 wines are split over three classes of 48 to 71 wines. The classes are close to balanced.
Step 2 — Fit a multinomial logistic regression
Section titled “Step 2 — Fit a multinomial logistic regression”wine_lr = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))wine_lr.fit(Xw_train, yw_train)proba_w = wine_lr.predict_proba(Xw_test.iloc[:3])print(proba_w.round(3))print("row sums:", proba_w.sum(axis=1).round(6))print("predict: ", wine_lr.predict(Xw_test.iloc[:3]))print("coef shape:", wine_lr[-1].coef_.shape)[[0.792 0.206 0.002] [0.011 0.953 0.036] [0.998 0.002 0. ]]row sums: [1. 1. 1.]predict: [0 1 0]coef shape: (3, 2)With three classes, LogisticRegression fits one multinomial model: one weight vector per class (coef_ has 3 rows) and the softmax on top. Each row of probabilities adds up to 1, and predict picks the largest.
Step 3 — Compare with one-vs-rest
Section titled “Step 3 — Compare with one-vs-rest”from sklearn.multiclass import OneVsRestClassifier
wine_ovr = make_pipeline( StandardScaler(), OneVsRestClassifier(LogisticRegression(max_iter=1000))).fit(Xw_train, yw_train)print("binary models:", len(wine_ovr[-1].estimators_))print(wine_ovr.predict_proba(Xw_test.iloc[:3]).round(3))for label, model_w in [("multinomial", wine_lr), ("one-vs-rest", wine_ovr)]: print(f"{label:<12} accuracy {model_w.score(Xw_test, yw_test):.3f}")binary models: 3[[0.642 0.356 0.001] [0.011 0.928 0.06 ] [0.962 0.037 0.001]]multinomial accuracy 0.889one-vs-rest accuracy 0.889One-vs-rest trains three independent “this class or not” models and rescales their outputs to add up to 1. The probabilities differ from the multinomial ones, but here the decisions and the accuracy are the same. Multinomial is the default because it fits all classes jointly; OvR is the way to make any binary-only model multiclass.
Step 4 — Read the classification report
Section titled “Step 4 — Read the classification report”yw_pred = wine_lr.predict(Xw_test)print(classification_report(yw_test, yw_pred, target_names=wine.target_names, digits=3)) precision recall f1-score support
class_0 0.941 0.889 0.914 18 class_1 0.895 0.810 0.850 21 class_2 0.833 1.000 0.909 15
accuracy 0.889 54 macro avg 0.890 0.899 0.891 54weighted avg 0.893 0.889 0.888 54Every class 2 wine is found (recall 1.000), but three class 1 wines are also called class 2, so its precision is only 0.833. Class 1 has the lowest recall: 81% of its wines are found. Macro and weighted averages are close, because the classes have similar support. The accuracy row equals the micro average.
Step 5 — Plot the confusion matrix
Section titled “Step 5 — Plot the confusion matrix”fig, ax = plt.subplots(figsize=(4.8, 4.2))ConfusionMatrixDisplay.from_predictions( yw_test, yw_pred, display_labels=wine.target_names, ax=ax, colorbar=False)ax.set_title("Wine cultivars, test set")plt.show()
Rows are the true cultivars and columns the predictions. Every off-diagonal cell is one kind of mistake. A 3 × 3 matrix shows which classes the model mixes up, which no single number can.
Step 6 — Score the probabilities with multiclass ROC-AUC
Section titled “Step 6 — Score the probabilities with multiclass ROC-AUC”proba_test_w = wine_lr.predict_proba(Xw_test)for average in ["macro", "weighted"]: auc_w = roc_auc_score(yw_test, proba_test_w, multi_class="ovr", average=average) print(f"ROC-AUC one-vs-rest, {average:<8}: {auc_w:.3f}")print(f"log loss: {log_loss(yw_test, proba_test_w):.3f}")ROC-AUC one-vs-rest, macro : 0.980ROC-AUC one-vs-rest, weighted: 0.978log loss: 0.271For multiclass ROC-AUC, pass the full probability matrix and multi_class="ovr". scikit-learn then computes one “this class vs the rest” AUC per class and averages them. Log loss works on the probability matrix directly.
Common mistakes:
- Passing only one probability column to a multiclass metric. Multiclass ROC-AUC and log loss need the full
(n, K)matrix. - Reporting the weighted average alone when classes are imbalanced. It hides a weak small class; show the macro average or the per-class rows.
- Forgetting
stratifyon small multiclass data. A rare class can then vanish from the test set.
Example 7 — Screen biopsies at high recall with an SVM
Section titled “Example 7 — Screen biopsies at high recall with an SVM”Goal: A screening tool must find at least 97% of malignant tumors, even at the cost of false alarms. Use the scaled SVM from the concepts, choose the score threshold on out-of-fold predictions, and check the recall on the test set.
Step 1 — Make malignant the positive class
Section titled “Step 1 — Make malignant the positive class”yb_train_m = (yb_train == 0).astype(int) # 1 = malignantyb_test_m = (yb_test == 0).astype(int)print(f"malignant share: train {yb_train_m.mean():.3f}, test {yb_test_m.mean():.3f}")malignant share: train 0.373, test 0.371In load_breast_cancer, class 1 is benign. The class to find must be the positive class, or recall measures the wrong thing. Recoding the target is the clearest fix; pos_label=0 in each metric is the alternative.
Step 2 — Get out-of-fold scores on the training set
Section titled “Step 2 — Get out-of-fold scores on the training set”from sklearn.model_selection import cross_val_predict
screen = make_pipeline(StandardScaler(), SVC())oof_scores = cross_val_predict( screen, Xb_train, yb_train_m, cv=StratifiedKFold(5, shuffle=True, random_state=42), method="decision_function",)print(f"out-of-fold ROC-AUC {roc_auc_score(yb_train_m, oof_scores):.3f}")out-of-fold ROC-AUC 0.994cross_val_predict returns, for each training row, the score of the model that did not see that row. These out-of-fold scores act like a validation set that covers all 426 training rows.
Step 3 — Pick the highest threshold that meets the recall target
Section titled “Step 3 — Pick the highest threshold that meets the recall target”prec_b, rec_b, thr_b = precision_recall_curve(yb_train_m, oof_scores)meets = rec_b[:-1] >= 0.97 # the last point has no thresholdscreen_t = thr_b[meets].max()print(f"score threshold: {screen_t:.3f}")print(f"out-of-fold recall {rec_b[:-1][meets][-1]:.3f}, " f"precision {prec_b[:-1][meets][-1]:.3f}")default_recall = recall_score(yb_train_m, oof_scores >= 0)print(f"out-of-fold recall at the default 0: {default_recall:.3f}")score threshold: -0.281out-of-fold recall 0.975, precision 0.945out-of-fold recall at the default 0: 0.943A higher threshold means fewer false alarms, so take the highest one that still reaches 97% recall. At the default threshold of 0, the SVM finds only 94.3% of the malignant training cases: it would fail the requirement. The tuned threshold is below 0, so the screening tool also flags some borderline cases that the plain SVM would call benign.
Step 4 — Check the test set once
Section titled “Step 4 — Check the test set once”screen.fit(Xb_train, yb_train_m)test_scores = screen.decision_function(Xb_test)for label, t in [("default 0", 0.0), (f"tuned {screen_t:.2f}", screen_t)]: flagged = (test_scores >= t).astype(int) print( f"{label:<12} recall {recall_score(yb_test_m, flagged):.3f}" f" precision {precision_score(yb_test_m, flagged):.3f}" f" missed {((flagged == 0) & (yb_test_m == 1)).sum()}" )default 0 recall 0.981 precision 0.963 missed 1tuned -0.28 recall 0.981 precision 0.912 missed 1On this test set, both thresholds miss one of 53 malignant tumors; the tuned one pays with more false alarms. Does that make tuning useless? No. With 53 positives, one tumor is almost 2 points of recall, so the test set is too small to tell the two thresholds apart. The decision rests on the 159 malignant out-of-fold cases, where the default missed 9 and failed the target. A small test set confirms a choice; it cannot make one.
Common mistakes:
- Leaving benign as the positive class. “Recall 0.99” then describes benign cases, not tumors.
- Using a probability threshold such as 0.3 on SVM scores.
decision_functionvalues are scores on their own scale, not probabilities; choose the threshold on the score scale. - Choosing the threshold on the 143 test rows. Out-of-fold scores give 426 rows for the decision and keep the test honest.
Pitfalls
Section titled “Pitfalls”| Mistake | Symptom | Fix |
|---|---|---|
| Judging a churn model by accuracy | 0.84 looks great, but the always-”stays” baseline scores 0.81 | Report precision, recall, PR-AUC and the baseline |
roc_auc_score(y, model.predict(X)) |
ROC-AUC far below the real value | Pass predict_proba(X)[:, 1] or decision_function(X) |
confusion_matrix(y_pred, y_true) |
Precision and recall swap | The true labels come first: confusion_matrix(y_true, y_pred) |
Wrong positive class (load_breast_cancer: 1 = benign) |
Recall describes the wrong class | Recode the target or pass pos_label |
| Choosing the threshold on the test set | Production results are worse than reported | Choose on a validation split or out-of-fold predictions |
| Keeping the 0.5 threshold | Few churners found when a miss costs more than an offer | Use or tune on validation |
SVC(probability=True) |
FutureWarning, slow fit, predict_proba disagrees with predict |
decision_function, or CalibratedClassifierCV(SVC(), ensemble=False) |
| No scaling for KNN, SVM or logistic regression | Lower scores; one large column decides | StandardScaler in a pipeline |
| Trusting naive Bayes probabilities | Mean prediction far above the churn rate | CalibratedClassifierCV |
Unlimited DecisionTreeClassifier |
Train ROC-AUC 1.000, poor test score | max_depth, min_samples_leaf, or a forest |
| Category dtypes built separately for each split | Splits disagree on their level lists; an unseen test level becomes a new category | Build CategoricalDtype from the training data and apply it to every split |
precision_score when nothing is flagged |
UndefinedMetricWarning |
zero_division=0 |
| Only the weighted average on imbalanced classes | The weak rare class is hidden | Show the macro average and the per-class rows |
| Odds ratio read as a probability ratio | “55% more churn” when the odds rose 55% | Talk about odds, or compute probabilities for real profiles |
Where this is used beyond data science
Section titled “Where this is used beyond data science”- Email and web: spam filters and content moderation are classifiers. Their teams tune the threshold for precision, because a real email in the spam folder costs more than a missed spam.
- Monitoring and operations: an alert rule is a classifier on metrics. “Too many pages at night” is low precision; “the outage we missed” is low recall. On-call teams tune alert thresholds with the same trade-off.
- Search and recommendations: precision and recall come from information retrieval. “Precision at 10” measures the share of good results on the first page.
- Testing and CI tooling: a flaky-test detector or a code-review bot is judged by its confusion matrix: false alarms annoy developers, misses let bugs through.
Summary
Section titled “Summary”- A classifier gives labels (
predict), probabilities (predict_proba) or scores (decision_function). Metrics for ranking and probabilities need the scores, not the labels. - Logistic regression is a weighted sum turned into a probability by the sigmoid. Its coefficients are log-odds; is the odds ratio per unit of the feature.
- KNN, SVMs and logistic regression need scaled features. Trees, forests and boosting do not. Gradient boosting (HistGradientBoosting, XGBoost, LightGBM) is usually the strongest on tables like the churn data; logistic regression is close and easy to explain.
- Accuracy misleads on imbalanced data: always-”stays” scores 0.807 on churn. Use the confusion matrix, precision, recall, F1, ROC-AUC and, for rare positives, average precision.
- Log loss and the Brier score judge probabilities. A calibration curve shows whether 30% means 30%;
CalibratedClassifierCVfixes it without changing the ranking. - Choose the threshold from costs on validation data, never on the test set. For calibrated probabilities, the cost-optimal threshold is .
- Multiclass models use one-vs-rest, one-vs-one or a multinomial softmax. Macro averages weigh classes equally; weighted averages follow class sizes.
Self-check questions
Section titled “Self-check questions”Q1. 80.7% of the test customers stay. A model has an accuracy of 0.82. Is it a good churn model?
Answer
You cannot tell from accuracy. Predicting “stays” for everyone already gives 0.807, so the model adds 1.3 points at most. Look at recall and precision for the churn class, and at ROC-AUC or average precision, and compare each with the baseline.
Q2. A logistic regression has a coefficient of 0.69 for support_tickets (in tickets, not scaled). What is the odds ratio, and what does it mean?
Answer
. Each extra support ticket doubles the odds of churn when all other features stay fixed. It does not double the probability: a 10% risk (odds 1/9) becomes odds 2/9, a probability of about 18%.
Q3. Why does roc_auc_score(y_test, model.predict(X_test)) give a misleading value?
Answer
predict returns 0/1 labels at one threshold. ROC-AUC measures a ranking over all thresholds, so it needs scores. With labels, the curve has only one corner point and the area is much lower than the model’s real ranking quality. Use predict_proba(X_test)[:, 1] or decision_function(X_test).
Q4. Which of these models need scaled features: logistic regression, KNN, SVM, decision tree, random forest, HistGradientBoosting?
Answer
Logistic regression (because the penalty treats all weights alike), KNN and SVM (because they use distances) need scaling. Trees, forests and gradient boosting split one feature at a time at a threshold, so scaling changes nothing.
Q5. A model has ROC-AUC 0.83 and average precision 0.58 on churn. A colleague says “0.58 is barely better than a coin flip”. Is that right?
Answer
No. A random ranking has an average precision equal to the share of positives, 0.19, not 0.5. An AP of 0.58 is about three times the no-skill level.
Q6. A missed fraud costs USD 500 and a manual check costs USD 25. With calibrated probabilities, above which fraud probability should a transaction be checked?
Answer
Check when , so . The threshold is far below 0.5 because a miss costs 20 times more than a check.
Q7. Why must you not choose the threshold on the test set? What do you use instead?
Answer
Every choice made on the test set fits the test set a little, so the test score becomes optimistic and stops being an honest estimate for new data. Use a validation split of the training data, out-of-fold predictions from cross_val_predict, or TunedThresholdClassifierCV.
Q8. Calibration improved a model’s Brier score from 0.18 to 0.12. Why did its ROC-AUC hardly change?
Answer
Calibration maps each probability through an increasing function. It keeps the order of the customers, and ROC-AUC depends only on that order. The Brier score depends on the size of the probabilities, which calibration fixes.
Q9. What replaces SVC(probability=True) in scikit-learn 1.9, and when do you not need probabilities from an SVM at all?
Answer
CalibratedClassifierCV(SVC(), ensemble=False). For ROC-AUC, average precision and score thresholds you need no probabilities: use decision_function.
Q10. A ticket classifier has three classes with 900, 80 and 20 tickets. Its F1 scores per class are 0.95, 0.60 and 0.20. Which is larger, the macro or the weighted F1? Which do you report?
Answer
Macro F1 = (0.95 + 0.60 + 0.20) / 3 ≈ 0.58. Weighted F1 = (900 × 0.95 + 80 × 0.60 + 20 × 0.20) / 1000 ≈ 0.91. The weighted average hides the weak rare classes. Report the macro average and the per-class rows, especially when the rare classes matter.
Q11. How does a random forest differ from a single decision tree, and why is it usually better?
Answer
A forest trains many deep trees, each on a bootstrap sample of the rows and with a random subset of features at each split, and averages their probabilities. Single deep trees overfit in different ways; averaging cancels much of that variance, so the forest generalizes better.
Track your progress
Section titled “Track your progress”Next steps
Section titled “Next steps”- Exercises: 28 exercises on metrics, thresholds, calibration, the nine models and multiclass reports.
- Mini-project: build a churn early-warning model with a cost-based call list.
- Cheat sheet: every classifier, metric and threshold tool of this module on one page.
- Next module: 37. Model evaluation and tuning diagnoses over- and underfitting, compares cross-validation schemes, tunes hyperparameters and handles imbalanced data.