36. Classification — Cheat sheet
The essentials of module 36 on one page. Every runnable block on this page is checked against its output. The blocks use a small synthetic dataset with 20% positives, so they run in a second.
Quick lookup
Section titled “Quick lookup”| I want to… | Use… | Example |
|---|---|---|
| predict labels | model.predict(X) |
array([0, 1, 0]) |
| get P(class 1) | model.predict_proba(X)[:, 1] |
column 1 = positive class |
| get a ranking score without probabilities | model.decision_function(X) |
SVMs, linear models |
| a baseline to beat | DummyClassifier(strategy="most_frequent") |
accuracy = majority share |
| a first, explainable model | LogisticRegression(max_iter=1000) after StandardScaler |
coefficients = log-odds |
| odds ratios | np.exp(model.coef_[0]) |
per unit of each scaled input |
| the strongest tabular model | HistGradientBoostingClassifier, XGBClassifier, LGBMClassifier |
native categories and NaN |
| count TP, FP, FN, TN | confusion_matrix(y_true, y_pred).ravel() |
order: TN, FP, FN, TP |
| plot the confusion matrix | ConfusionMatrixDisplay.from_predictions(y, pred) |
then plt.show() |
| precision, recall, F1 per class | classification_report(y, pred, digits=3) |
with macro and weighted rows |
| a ranking metric | roc_auc_score(y, proba) |
0.5 random, 1.0 perfect |
| a rare-positive ranking metric | average_precision_score(y, proba) |
random = positive share |
| judge probabilities | log_loss(y, proba), brier_score_loss(y, proba) |
lower is better |
| the precision–recall trade-off | precision_recall_curve(y, proba) |
one point per threshold |
| a custom threshold | (proba >= t).astype(int) or FixedThresholdClassifier(model, threshold=t) |
|
| tune the threshold for a cost | TunedThresholdClassifierCV(model, scoring=make_scorer(cost, greater_is_better=False)) |
CV inside the training set |
| the cost-optimal threshold for calibrated probabilities | c_flag / c_miss when every flag costs c_flag; c_fp / (c_fp + c_fn) when correct flags are free and only false alarms and misses cost |
50 / 300 = 0.167 |
| check calibration | calibration_curve(y, proba, n_bins=10, strategy="quantile") |
or CalibrationDisplay |
| fix calibration | CalibratedClassifierCV(model, method="sigmoid", cv=5) |
"isotonic" with 1,000+ calibration rows (training rows ÷ cv) |
| probabilities from an SVM | CalibratedClassifierCV(SVC(), ensemble=False) |
not probability=True |
| make a binary model multiclass | OneVsRestClassifier(model), OneVsOneClassifier(model) |
|
| multiclass ROC-AUC | roc_auc_score(y, proba_matrix, multi_class="ovr") |
full (n, K) matrix |
| out-of-fold scores for threshold choice | cross_val_predict(model, X, y, method="predict_proba") |
Setup for this page
Section titled “Setup for this page”import numpy as npfrom sklearn.datasets import make_classificationfrom sklearn.linear_model import LogisticRegressionfrom sklearn.model_selection import train_test_splitfrom sklearn.pipeline import make_pipelinefrom sklearn.preprocessing import StandardScaler
X, y = make_classification( n_samples=2000, n_features=8, n_informative=4, weights=[0.8], random_state=42)X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.25, stratify=y, random_state=42)model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))model.fit(X_train, y_train)proba = model.predict_proba(X_test)[:, 1] # P(class 1)pred = model.predict(X_test) # 1 when P(class 1) > 0.5print(f"positives: {y.mean():.3f}, test rows: {len(y_test)}")positives: 0.202, test rows: 500Classifier outputs
Section titled “Classifier outputs”| Method | Returns | Use for |
|---|---|---|
predict(X) |
labels: 1 when the probability is above 0.5 (score above 0); a tie goes to class 0 | accuracy, precision, recall, F1, confusion matrix |
predict_proba(X) |
(n, K) probabilities, rows sum to 1; column order = model.classes_ |
ROC-AUC, AP, log loss, Brier, thresholds, costs |
decision_function(X) |
(n,) scores (binary) or (n, K); any real number |
ROC-AUC, AP, score thresholds |
score(X, y) |
accuracy | quick check only |
Models
Section titled “Models”| Model | Class | Scale? | predict_proba? |
Key hyperparameters | Strengths | Weaknesses |
|---|---|---|---|---|---|---|
| Logistic regression | LogisticRegression |
yes | yes, usually calibrated | C (smaller = stronger L2), l1_ratio, class_weight |
fast, explainable odds ratios | only linear log-odds unless you add features |
| k-nearest neighbors | KNeighborsClassifier |
yes | yes, steps of 1/k | n_neighbors, weights |
no training, local patterns | slow predictions, weak in many dimensions |
| Gaussian naive Bayes | GaussianNB |
no | yes, poorly calibrated | var_smoothing |
milliseconds, tiny data | assumes independent normal features |
| SVM | SVC |
yes | no; use CalibratedClassifierCV |
C, kernel, gamma |
strong on small, clean data | slow above ~20,000 rows; no native probabilities |
| Decision tree | DecisionTreeClassifier |
no | yes, leaf shares | max_depth, min_samples_leaf, ccp_alpha |
readable rules, NaN support | overfits, unstable |
| Random forest | RandomForestClassifier |
no | yes | n_estimators, max_features, min_samples_leaf |
strong default, little tuning | large, slower predictions |
| Hist. gradient boosting | HistGradientBoostingClassifier |
no | yes | learning_rate, max_iter, max_leaf_nodes, l2_regularization |
fast, native categories and NaN | needs tuning for the best score |
| XGBoost | xgboost.XGBClassifier |
no | yes | n_estimators, learning_rate, max_depth, subsample |
top accuracy, GPU support | many parameters |
| LightGBM | lightgbm.LGBMClassifier |
no | yes | n_estimators, learning_rate, num_leaves, min_child_samples |
very fast on large data | leaf-wise trees overfit small data |
Logistic regression and odds ratios
Section titled “Logistic regression and odds ratios”lr = model[-1]odds_ratios = np.exp(lr.coef_[0]) # odds multiplier per +1 sd of each inputprint(odds_ratios.round(2))log_odds = model[:-1].transform(X_test[:2]) @ lr.coef_[0] + lr.intercept_[0]print(np.allclose(1 / (1 + np.exp(-log_odds)), proba[:2])) # sigmoid = predict_proba[1.33 0.94 0.9 1.67 1.19 1.04 1.91 0.8 ]True| Coefficient | Odds ratio | Meaning per unit |
|---|---|---|
| 0 | 1.00 | no effect |
| 0.69 | 2.00 | odds double |
| −0.69 | 0.50 | odds halve |
| 0.10 | 1.11 | odds +11% |
An odds ratio is not a probability ratio: odds × 2 takes 10% to 18%, and 50% to 67%.
Metrics
Section titled “Metrics”| Metric | Formula | Range | Function |
|---|---|---|---|
| Accuracy | 0–1 | accuracy_score |
|
| Precision | 0–1 | precision_score |
|
| Recall (TPR, sensitivity) | 0–1 | recall_score |
|
| Specificity | 0–1 | recall_score(..., pos_label=0) |
|
| F1 | 0–1 | f1_score |
|
| FPR | 0–1 | from roc_curve |
|
| ROC-AUC | area under TPR vs FPR | 0.5 random – 1 | roc_auc_score |
| Average precision (PR-AUC) | positive share – 1 | average_precision_score |
|
| Log loss | 0 – ∞ | log_loss |
|
| Brier score | 0–1 | brier_score_loss |
|
| Balanced accuracy | mean of the recalls per class | 0.5 random – 1 | balanced_accuracy_score |
from sklearn.metrics import ( accuracy_score, average_precision_score, brier_score_loss, confusion_matrix, f1_score, log_loss, precision_score, recall_score, roc_auc_score,)
tn, fp, fn, tp = confusion_matrix(y_test, pred).ravel() # true labels firstprint(f"TN {tn} FP {fp} FN {fn} TP {tp}")print(f"acc {accuracy_score(y_test, pred):.3f}" f" prec {precision_score(y_test, pred):.3f}" f" rec {recall_score(y_test, pred):.3f} F1 {f1_score(y_test, pred):.3f}")print(f"ROC-AUC {roc_auc_score(y_test, proba):.3f}" # scores, never labels f" AP {average_precision_score(y_test, proba):.3f}" f" log loss {log_loss(y_test, proba):.3f}" f" Brier {brier_score_loss(y_test, proba):.3f}")TN 389 FP 10 FN 81 TP 20acc 0.818 prec 0.667 rec 0.198 F1 0.305ROC-AUC 0.759 AP 0.519 log loss 0.424 Brier 0.132Which metric when
Section titled “Which metric when”| Situation | Report | Avoid |
|---|---|---|
| Balanced classes, equal error costs | accuracy, F1 | — |
| Rare positives (churn, fraud, disease) | average precision, recall at a fixed precision, the baseline | accuracy alone |
| Ranking for a campaign of unknown size | ROC-AUC, gains table, precision at k | metrics at 0.5 |
| Fixed capacity (call 500 people) | precision and recall in the top k | ROC-AUC alone |
| Probabilities feed money or a forecast | Brier, log loss, calibration curve | ranking metrics alone |
| Known costs of FP and FN | total cost at the chosen threshold | F1 |
| Multiclass, every class matters | macro F1, per-class report | weighted average alone |
| Comparing models | cross-validated mean ± std on the training set | repeated test-set looks |
Curves and plots
Section titled “Curves and plots”import matplotlib.pyplot as pltfrom sklearn.calibration import CalibrationDisplayfrom sklearn.metrics import ( ConfusionMatrixDisplay, PrecisionRecallDisplay, RocCurveDisplay,)
fig, axes = plt.subplots(1, 4, figsize=(16, 4))ConfusionMatrixDisplay.from_predictions(y_test, pred, ax=axes[0], colorbar=False)RocCurveDisplay.from_predictions(y_test, proba, ax=axes[1], plot_chance_level=True)PrecisionRecallDisplay.from_predictions( y_test, proba, ax=axes[2], plot_chance_level=True)CalibrationDisplay.from_predictions( y_test, proba, n_bins=8, strategy="quantile", ax=axes[3])plt.tight_layout()plt.show()
Thresholds
Section titled “Thresholds”from sklearn.metrics import precision_recall_curve
prec, rec, thr = precision_recall_curve(y_test, proba) # len(thr) = len(prec) - 1for t in [0.2, 0.5]: flag = proba >= t # at or above = positive, like FixedThresholdClassifier print(f"t={t}: flagged {flag.sum()}, recall {recall_score(y_test, flag):.3f}")best_for_recall = thr[rec[:-1] >= 0.9].max() # highest t with recall >= 0.9print(f"highest threshold with recall >= 0.9: {best_for_recall:.3f}")t=0.2: flagged 171, recall 0.634t=0.5: flagged 30, recall 0.198highest threshold with recall >= 0.9: 0.084Choose thresholds on a validation split or out-of-fold predictions; the test set above only shows the API.
| Goal | Rule |
|---|---|
| minimize cost, calibrated probabilities, every flag costs , every miss | flag when |
| minimize cost, calibrated probabilities, only false alarms () and misses () cost | flag when |
| minimize cost, any model | search thresholds on validation data, or TunedThresholdClassifierCV |
| reach a recall target | highest threshold with validation recall ≥ target |
| fixed capacity k | sort by probability, take the top k |
from sklearn.metrics import make_scorerfrom sklearn.model_selection import FixedThresholdClassifier, TunedThresholdClassifierCV
fixed = FixedThresholdClassifier(model, threshold=0.2).fit(X_train, y_train)tuned = TunedThresholdClassifierCV( model, scoring=make_scorer(cost_fn, greater_is_better=False), cv=5).fit(X_train, y_train)tuned.best_threshold_ # chosen by cross-validation on the training dataCalibration
Section titled “Calibration”from sklearn.calibration import CalibratedClassifierCV, calibration_curvefrom sklearn.naive_bayes import GaussianNB
for name, clf in [ ("raw NB", GaussianNB()), ("sigmoid NB", CalibratedClassifierCV(GaussianNB(), method="sigmoid", cv=5)),]: p = clf.fit(X_train, y_train).predict_proba(X_test)[:, 1] observed, predicted = calibration_curve(y_test, p, n_bins=4, strategy="quantile") print(f"{name:<10} Brier {brier_score_loss(y_test, p):.3f}" f" predicted {predicted.round(2)} observed {observed.round(2)}")raw NB Brier 0.120 predicted [0.03 0.06 0.13 0.58] observed [0.08 0.11 0.12 0.5 ]sigmoid NB Brier 0.117 predicted [0.11 0.11 0.14 0.45] observed [0.08 0.11 0.12 0.5 ]method= |
Fits | Use when |
|---|---|---|
"sigmoid" |
Platt scaling: logistic regression on the score | small data, S-shaped distortion, SVMs |
"isotonic" |
increasing step function | 1,000+ calibration rows (training rows ÷ cv), any monotonic distortion |
"temperature" |
one divisor for the multiclass log-odds | multiclass models |
| Option | Effect |
|---|---|
cv=5 (the default None also means 5 folds) |
5 model + calibrator pairs; predictions average them |
ensemble=False |
one model on all rows + one calibrator on out-of-fold scores |
FrozenEstimator(fitted) + held-out rows |
calibrate an already fitted model on new data |
Multiclass
Section titled “Multiclass”| Strategy | Models for K classes | scikit-learn |
|---|---|---|
| native multiclass | 1 | LogisticRegression and boosting (softmax over K scores), trees and forests (class shares in leaves) |
| one-vs-rest | K | OneVsRestClassifier(model) |
| one-vs-one | K(K−1)/2 | OneVsOneClassifier(model), SVC internally |
| Average | Computes | Effect |
|---|---|---|
macro |
plain mean over classes | rare classes count fully |
weighted |
mean weighted by support | dominated by large classes |
micro |
pools TP, FP, FN over classes | equals accuracy for single-label multiclass |
None |
one value per class | the honest view |
from sklearn.datasets import load_irisfrom sklearn.metrics import classification_report
iris = load_iris()Xi_train, Xi_test, yi_train, yi_test = train_test_split( iris.data[:, :2], iris.target, test_size=0.3, stratify=iris.target, random_state=42)clf = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))clf.fit(Xi_train, yi_train)print(classification_report(yi_test, clf.predict(Xi_test), digits=2, target_names=iris.target_names))pi = clf.predict_proba(Xi_test) # (n, 3), rows sum to 1print(f"ROC-AUC ovr macro {roc_auc_score(yi_test, pi, multi_class='ovr'):.3f}") precision recall f1-score support
setosa 1.00 1.00 1.00 15 versicolor 0.60 0.60 0.60 15 virginica 0.60 0.60 0.60 15
accuracy 0.73 45 macro avg 0.73 0.73 0.73 45weighted avg 0.73 0.73 0.73 45
ROC-AUC ovr macro 0.882XGBoost and LightGBM
Section titled “XGBoost and LightGBM”| Idea | scikit-learn HGB | XGBoost | LightGBM |
|---|---|---|---|
| trees | max_iter |
n_estimators |
n_estimators |
| step size | learning_rate |
learning_rate |
learning_rate |
| tree size | max_leaf_nodes, max_depth |
max_depth |
num_leaves, max_depth |
| min rows per leaf | min_samples_leaf |
min_child_weight (hessian) |
min_child_samples |
| row sampling | — | subsample |
subsample + subsample_freq |
| column sampling | max_features |
colsample_bytree |
colsample_bytree |
| L2 penalty | l2_regularization |
reg_lambda |
reg_lambda |
| categories | category dtype (default "from_dtype") |
enable_categorical=True |
category dtype, automatic |
| class imbalance | class_weight |
scale_pos_weight |
class_weight, scale_pos_weight |
| early stopping | early_stopping=True |
early_stopping_rounds= + fit(eval_set=...) |
fit(eval_X=..., eval_y=..., callbacks=[lightgbm.early_stopping(n)]) |
| reproducible, quiet | random_state=42 |
random_state=42, n_jobs=4 |
random_state=42, n_jobs=4, verbose=-1 |
cat_dtypes = {c: pd.CategoricalDtype(sorted(X_train[c].unique())) for c in cat_cols}X_train_cat, X_test_cat = X_train.astype(cat_dtypes), X_test.astype(cat_dtypes)
xgb = XGBClassifier(n_estimators=200, learning_rate=0.05, max_depth=4, enable_categorical=True, n_jobs=4, random_state=42)lgbm = LGBMClassifier(n_estimators=200, learning_rate=0.05, num_leaves=15, n_jobs=4, verbose=-1, random_state=42)Gotchas
Section titled “Gotchas”- Accuracy on imbalanced data. With 80% negatives, “always negative” scores 0.80. Always print the
DummyClassifierbaseline next to your score. - Labels in ranking metrics.
roc_auc_score(y, model.predict(X))measures one threshold, not the ranking. Passpredict_proba(X)[:, 1]ordecision_function(X). - Argument order. Every metric takes
(y_true, y_pred). Swapping them inconfusion_matrixswaps precision and recall. - The positive class. Metrics treat label 1 as positive. In
load_breast_cancer, 1 is benign; recode or passpos_label=0. - Column order of
predict_proba. It followsmodel.classes_(sorted labels). With string labels, checkclasses_before you take[:, 1]. - Thresholds on the test set. Tuning anything on the test set makes its score optimistic. Use validation data, out-of-fold predictions or
TunedThresholdClassifierCV. SVC(probability=True)is deprecated in scikit-learn 1.9, slow, and its probabilities can contradictpredict. Usedecision_functionorCalibratedClassifierCV(SVC(), ensemble=False).LogisticRegression(penalty=...)is deprecated since 1.8. Usel1_ratio(0 = L2, 1 = L1) andC=np.inffor no penalty.- No scaling for KNN, SVM and logistic regression. Distances and penalties then follow the column with the largest units.
- Calibration does not improve ranking. It fixes probability sizes; ROC-AUC stays about the same.
- Undefined precision. When nothing is flagged, precision is 0/0. Pass
zero_division=0to silence the warning on purpose. - Category schema. Build
CategoricalDtypefrom the training data and reuse it for every split. All splits then share one level list, and a level never seen in training becomes NaN instead of a silent new category. (XGBoost 3.4, LightGBM 4.7 andHistGradientBoostingClassifierre-map categories by value, so the codes themselves are not the risk.) - LightGBM 4.7
eval_setis deprecated infit; useeval_X=andeval_y=. Silence the training log withverbose=-1. - Multiclass metrics. Multiclass ROC-AUC and log loss need the whole
(n, K)probability matrix, not one column.