Code files
NameKindSizeUpdated
Process 01: Audit and prepare RapidMiner process 6.2 KB Oct 19, 2026
Process 02: Partition RapidMiner process 2.8 KB Oct 18, 2026
Process 03: Baseline and logistic regression RapidMiner process 21.7 KB Oct 19, 2026
Process 04: Tournament of k-NN, naive Bayes, tree, forest and boosting RapidMiner process 42.0 KB Oct 19, 2026
Process 05: Neural network RapidMiner process 10.5 KB Oct 19, 2026
Process 06: Chosen model, costs and holdout RapidMiner process 11.0 KB Oct 19, 2026
Process 07: Score a new applicant RapidMiner process 3.4 KB Oct 19, 2026
Tournament notebook (Python supplement) Notebook 800.8 KB Oct 19, 2026
tournament.py Code 33.5 KB Oct 19, 2026

Tournament notebook (Python supplement)

Notebook Download

The notebook repeats the data, the attributes set aside, the partition, the folds, the families, the cost table and the cutoff in scikit-learn, cell by cell, executed with its outputs and figures. Started in the notebooks folder, it reads ../data and writes ../results and ../figures. This run produced results.json and every number in sections 1 to 7 and in Appendices A to D of the report, apart from Tables A3 to A9. The notebook is a supplement to the processes.

Notebook, python: 28 cells.

The German Credit tournament, cell by cell

This notebook is the Python supplement to the RapidMiner processes, for an example from the book (case 23.2). It uses the same data, the same attributes set aside, the same 80 / 20 partition and five folds (seed 2026), the same model families and the same cost table and cutoff. It produced results/results.json, the source of every number in sections 1 to 7 of the report and in Appendices A to D apart from Tables A3 to A9, which with section 8 come from AI Studio's own runs (rm_results.json).

Run it from the package's notebooks/ folder (pinned versions in notebooks/requirements.txt). The outputs below are those of the recorded run.

In [1]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
"""The German Credit model tournament. This is an example from the book, case 23.2
of Shmueli, Bruce, Deokar and Patel, Machine Learning for Business Analytics (RapidMiner
edition), extended to the full spine of the CSBU 5420 final project.

  1. Define the business problem      accept or reject a credit applicant; the book's cost table
  2. Obtain and audit the data        1,000 past applicants, 30 attributes, RESPONSE 1 = good credit
  3. Explore, clean, prepare          protected attributes set aside (ECOA), codes kept as the book keeps them
  4. Partition                        800 for modeling / 200 holdout, stratified, seed 2026;
                                       five fold cross validation on the 800 selects the model
  5. Choose candidate methods         baseline, logistic, k-NN, naive Bayes, tree, forest, boosting, network
  6. Train and tune                   settings swept by cross validation; the kept setting is recorded here
  7. Evaluate honestly                the book's cost table sets the cutoff; the holdout is used once
  8. Recommend, deploy, monitor       the chosen model, the cutoff, the monitoring plan

The script lives in notebooks/ and reads ../data/GermanCredit.csv. It writes results.json,
leaderboard.csv and leaderboard.md to ../results and the charts to ../figures. Run it from the
package folder with  python notebooks/tournament.py  (requirements in notebooks/requirements.txt).
"""
import json
import os
import time
import warnings

import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import HistGradientBoostingClassifier, RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score, roc_curve
from sklearn.model_selection import StratifiedKFold, cross_val_predict, train_test_split
from sklearn.naive_bayes import CategoricalNB
from sklearn.neighbors import KNeighborsClassifier
from sklearn.neural_network import MLPClassifier
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import KBinsDiscretizer, OneHotEncoder, StandardScaler
from sklearn.tree import DecisionTreeClassifier

warnings.filterwarnings("ignore")
HERE = os.path.abspath("")      # a notebook has no __file__; Jupyter runs it from the folder it sits in, notebooks/
assert os.path.exists(os.path.join(HERE, "..", "data", "GermanCredit.csv")), (
    f"Start Jupyter so this notebook runs from the package's notebooks/ folder (the working folder is {HERE})")
DATA = os.path.join(HERE, "..", "data", "GermanCredit.csv")
RESULTS = os.path.join(HERE, "..", "results")
FIGURES = os.path.join(HERE, "..", "figures")
assert os.path.exists(DATA), f"GermanCredit.csv not found at {os.path.abspath(DATA)}; keep the package folders together"
os.makedirs(RESULTS, exist_ok=True)
os.makedirs(FIGURES, exist_ok=True)

SEED = 2026
GAIN_GOOD = 100.0      # DM, the average net profit of a loan to a good credit (book, Table 23.5)
LOSS_BAD = 500.0       # DM, the average net loss of a loan to a bad credit
CUTOFF = LOSS_BAD / (GAIN_GOOD + LOSS_BAD)   # accept when p(good) x 100 > (1 - p) x 500: p > 5/6
PER = 1000             # expected value per 1,000 applicants
RULE_DM = 5000.0       # the charter's price of a readable equation, per 1,000 applicants

t0 = time.time()
df = pd.read_csv(DATA)
assert df.shape == (1000, 32), df.shape
# the leakage audit: OBS# is a row identifier, so it must carry no signal about the outcome before it is set aside
obs_check = {"obs_auc": float(roc_auc_score(df["RESPONSE"], df["OBS#"])),
             "obs_quartile_good_rates": [float(v) for v in df.groupby(pd.qcut(df["OBS#"], 4, labels=False))["RESPONSE"].mean()]}
df = df.drop(columns=["OBS#"])

2. audit

In [2]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
# ---- 2. audit ---------------------------------------------------------------------------
audit = {
    "rows": int(len(df)), "attributes": int(df.shape[1] - 1),
    "good_rate": float(df["RESPONSE"].mean()), "good": int(df["RESPONSE"].sum()), "bad": int((1 - df["RESPONSE"]).sum()),
    "duplicates": int(df.duplicated().sum()), "missing": int(df.isna().sum().sum()),
    "amount_range": [int(df["AMOUNT"].min()), int(df["AMOUNT"].max())], "duration_range": [int(df["DURATION"].min()), int(df["DURATION"].max())],
    "age_range": [int(df["AGE"].min()), int(df["AGE"].max())],
    "good_by_chk": {str(k): float(v) for k, v in df.groupby("CHK_ACCT")["RESPONSE"].mean().items()},
    "good_by_history": {str(k): float(v) for k, v in df.groupby("HISTORY")["RESPONSE"].mean().items()},
    "purpose_rows": {c: int(df[c].sum()) for c in ["NEW_CAR", "USED_CAR", "FURNITURE", "RADIO/TV", "EDUCATION", "RETRAINING"]},
    "foreign_share": float(df["FOREIGN"].mean()),
    "leakage_obs": obs_check,
}
# the book asks why a critical credit history scores as the best risk
# (set after the partition, from the 800 modeling records only)

3. prepare

In [3]
1
2
3
4
5
6
7
8
# ---- 3. prepare -------------------------------------------------------------------------
PROTECTED = ["MALE_DIV", "MALE_SINGLE", "MALE_MAR_or_WID", "FOREIGN"]   # sex and marital status, foreign worker status
ALL = [c for c in df.columns if c != "RESPONSE"]
FEATS = [c for c in ALL if c not in PROTECTED]
CONT = ["DURATION", "AMOUNT", "AGE"]        # the continuous ones; everything else is a code or a flag, kept as the book keeps them
CODES = ["CHK_ACCT", "HISTORY", "SAV_ACCT", "EMPLOYMENT", "JOB"]   # the multi-level codes that the one-hot variant treats as categories
y = df["RESPONSE"].values
X = df[ALL]

4. partition into 800 for modeling and 200 held out, before anything is fitted

In [4]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# ---- 4. partition into 800 for modeling and 200 held out, before anything is fitted ---------------
X_m, X_ho, y_m, y_ho = train_test_split(X, y, test_size=0.20, stratify=y, random_state=SEED)
partition = {"modeling": int(len(X_m)), "holdout": int(len(X_ho)), "folds": 5,
             "good_rate_modeling": float(y_m.mean()), "good_rate_holdout": float(y_ho.mean())}
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=SEED)
# the good credit rate by code on the modeling records, the check behind keeping the codes as ordered numbers (data/README.md)
code_good_rates = {c: {str(k): {"good_rate": round(float(v.mean()), 4), "n": int(len(v))} for k, v in pd.Series(y_m, index=X_m.index).groupby(X_m[c])}
                   for c in CODES}
# the book asks why a critical credit history scores as the best risk; rates on the 800 modeling records only
audit["history_surprise"] = {"critical_account_good_rate": code_good_rates["HISTORY"]["4"]["good_rate"], "no_credits_good_rate": code_good_rates["HISTORY"]["0"]["good_rate"],
                             "records": "the 800 modeling records"}


def prep_scaled(cols):
    return ColumnTransformer([("num", StandardScaler(), cols)])


def prep_nb(cols):
    cont = [c for c in cols if c in CONT]
    codes = [c for c in cols if c not in CONT]
    return ColumnTransformer([("bins", KBinsDiscretizer(n_bins=5, encode="ordinal", strategy="quantile", quantile_method="averaged_inverted_cdf"), cont),
                              ("codes", "passthrough", codes)])


def prep_onehot(cols):
    """The codes in CODES become one indicator per level; everything is then standardized, so the L2 penalty treats every column alike."""
    codes = [c for c in cols if c in CODES]
    rest = [c for c in cols if c not in CODES]
    return Pipeline([("ct", ColumnTransformer([("onehot", OneHotEncoder(handle_unknown="ignore", sparse_output=False), codes), ("num", "passthrough", rest)])),
                     ("scale", StandardScaler())])


def prep_pass(cols):
    return ColumnTransformer([("num", "passthrough", cols)])

7. the business metric, the book's net profit table

In [5]
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
# ---- 7. the business metric, the book's net profit table ----------------------------------
def profit_per_1000(y_true, p, cutoff=CUTOFF, gain=GAIN_GOOD, loss=LOSS_BAD):
    accept = p >= cutoff
    n = len(y_true)
    tp = int((accept & (y_true == 1)).sum()); fp = int((accept & (y_true == 0)).sum())
    fn = int((~accept & (y_true == 1)).sum()); tn = int((~accept & (y_true == 0)).sum())
    profit = (tp * gain - fp * loss) / n * PER
    return {"profit_per_1000": round(float(profit), 1), "accepted_per_1000": round(float(accept.mean() * PER), 1),
            "tp": tp, "fp": fp, "fn": fn, "tn": tn,
            "precision": round(tp / (tp + fp), 4) if tp + fp else 0.0, "recall": round(tp / (tp + fn), 4) if tp + fn else 0.0,
            "accuracy": round((tp + tn) / n, 4)}


def profit_lift(y_true, p, bins=10):
    """The book's question 4: sort by confidence(good), accumulate net profit, find the peak."""
    order = np.argsort(-p)
    ys = y_true[order]
    n = len(ys)
    rows, cum = [], 0.0
    for d in range(bins):
        lo, hi = int(d * n / bins), int((d + 1) * n / bins)
        seg = ys[lo:hi]
        seg_profit = float(seg.sum() * GAIN_GOOD - (len(seg) - seg.sum()) * LOSS_BAD)
        cum += seg_profit
        rows.append({"decile": d + 1, "applicants": int(hi - lo), "good": int(seg.sum()), "bad": int(len(seg) - seg.sum()),
                     "profit": round(seg_profit, 0), "cumulative_profit": round(cum, 0), "min_p_in_decile": round(float(p[order][hi - 1]), 4)})
    return rows


def evaluate_cv(name, make, grid=None, label=str):
    """Out of fold probabilities on the 800 for every setting; keep the best CV profit, tie break AUC.
    label(g) names the setting with its parameter, such as C = 0.01."""
    best, trials = None, []
    for g in (grid or [None]):
        t = time.time()
        m = make(g)
        p = cross_val_predict(m, X_m, y_m, cv=cv, method="predict_proba")[:, 1]
        r = {"model": name, "setting": label(g) if g is not None else "default", "auc": round(float(roc_auc_score(y_m, p)), 4),
             "accuracy_at_half": round(float(((p >= 0.5).astype(int) == y_m).mean()), 4), "fit_seconds": round(time.time() - t, 1)}
        r.update(profit_per_1000(y_m, p))
        trials.append({k: r[k] for k in ("setting", "auc", "profit_per_1000", "accepted_per_1000", "fit_seconds")})
        print(f"  {name:22s} {r['setting']:34s} auc {r['auc']:.4f} profit {r['profit_per_1000']:9.1f} accepted {r['accepted_per_1000']:6.1f} ({r['fit_seconds']}s)", flush=True)
        if best is None or (r["profit_per_1000"], r["auc"]) > (best[0]["profit_per_1000"], best[0]["auc"]):
            best = (r, p, m)
    return best, trials


# the charter's monitoring thresholds, kept here so every number the report states comes from this file
POLICY = {"retrain_bad_rate": 0.15, "retrain_min_quarter_loans": 200, "drift_points_no_checking": 10}
results = {"seed": SEED, "gain_good": GAIN_GOOD, "loss_bad": LOSS_BAD, "cutoff": round(CUTOFF, 4), "rule_dm": RULE_DM, "policy": POLICY,
           "audit": audit, "partition": partition, "features": {"used": FEATS, "protected_set_aside": PROTECTED, "continuous": CONT},
           "leaderboard": [], "tuning": {}, "code_good_rates": code_good_rates}
gm = float(y_m.mean())
results["baselines"] = {
    "accept_everyone": {"accuracy": round(gm, 4), "profit_per_1000": round((gm * GAIN_GOOD - (1 - gm) * LOSS_BAD) * PER, 1), "accepted_per_1000": float(PER),
                        "note": "Accepting every applicant loses money on the book's cost table."},
    "reject_everyone": {"accuracy": round(1 - gm, 4), "profit_per_1000": 0.0, "accepted_per_1000": 0.0,
                        "note": "Rejecting every applicant earns and loses nothing, and the bank makes no loans."},
}
print("modeling good rate", gm, "accept everyone", results["baselines"]["accept_everyone"]["profit_per_1000"], "cutoff", CUTOFF, flush=True)

probs, fitted = {}, {}


def contend(name, make, grid=None, label=str):
    best, trials = evaluate_cv(name, make, grid, label)
    if grid:
        results["tuning"][name] = trials
    results["leaderboard"].append(best[0]); probs[name] = best[1]; fitted[name] = best[2]


print("five fold cross validation on the 800 modeling records", flush=True)
C_GRID = [0.003, 0.01, 0.03, 0.1, 1.0, 10.0]
c_label = lambda g: f"C = {g:g}"
contend("Logistic regression", lambda g: Pipeline([("prep", prep_scaled(FEATS)), ("m", LogisticRegression(C=g, max_iter=5000))]), C_GRID, c_label)
contend("k-nearest neighbors", lambda g: Pipeline([("prep", prep_scaled(FEATS)), ("m", KNeighborsClassifier(n_neighbors=g))]), [5, 11, 21, 41, 61, 81],
        lambda g: f"n_neighbors = {g}")
contend("Naive Bayes", lambda g: Pipeline([("prep", prep_nb(FEATS)), ("m", CategoricalNB(alpha=g, min_categories=6))]), [0.25, 0.5, 1.0, 3.0],
        lambda g: f"alpha = {g:g}")
contend("Decision tree", lambda g: Pipeline([("prep", prep_pass(FEATS)), ("m", DecisionTreeClassifier(max_depth=g, min_samples_leaf=20, random_state=SEED))]), [2, 3, 4, 5, 6],
        lambda g: f"max_depth = {g}")
contend("Random forest", lambda g: Pipeline([("prep", prep_pass(FEATS)), ("m", RandomForestClassifier(n_estimators=300, min_samples_leaf=g, max_features="sqrt", n_jobs=8, random_state=SEED))]),
        [1, 5, 10], lambda g: f"min_samples_leaf = {g}")
contend("Gradient boosted trees", lambda g: Pipeline([("prep", prep_pass(FEATS)), ("m", HistGradientBoostingClassifier(learning_rate=g[0], max_depth=g[1], max_iter=200, random_state=SEED))]),
        [(0.03, 2), (0.05, 3), (0.1, 2), (0.2, 2), (0.1, 3)], lambda g: f"learning_rate = {g[0]:g}, max_depth = {g[1]}")
contend("Neural network", lambda g: Pipeline([("prep", prep_scaled(FEATS)), ("m", MLPClassifier(hidden_layer_sizes=g[0], alpha=g[1], learning_rate_init=g[2], early_stopping=True, validation_fraction=0.15, max_iter=600, random_state=SEED))]),
        [(h, a, lr) for h in [(8,), (16,), (16, 8)] for a in (1e-4, 1e-3, 1e-2, 1e-1) for lr in (0.001, 0.01)],
        lambda g: f"hidden_layer_sizes = {g[0]}, alpha = {g[1]:g}, learning_rate_init = {g[2]:g}")

# the one-hot variant of the logistic model: the five multi-level codes as categories, the same C grid, kept the same way
best_oh, trials_oh = evaluate_cv("Logistic regression, codes one-hot", lambda g: Pipeline([("prep", prep_onehot(FEATS)), ("m", LogisticRegression(C=g, max_iter=5000))]), C_GRID, c_label)
results["onehot_variant"] = {**best_oh[0], "codes_one_hot": CODES}
results["onehot_tuning"] = trials_oh

# the disclosed comparison is the same logistic model WITH the protected attributes (not deployable, measured so the cost of fairness is known)
# fitted over the same C grid as the deployed model and kept the same way (best CV profit, tie break AUC)
best_all, trials_all = evaluate_cv("Logistic regression with protected attributes", lambda g: Pipeline([("prep", prep_scaled(ALL)), ("m", LogisticRegression(C=g, max_iter=5000))]), C_GRID, c_label)
results["with_protected"] = best_all[0]
results["with_protected_tuning"] = trials_all

sens = {}
for name in ("Logistic regression", results["leaderboard"][0]["model"]):
    sens[name] = [{"cutoff": c, **{k: v for k, v in profit_per_1000(y_m, probs[name], c).items() if k in ("profit_per_1000", "accepted_per_1000", "precision", "recall")}}
                  for c in (0.5, 0.6, 0.7, 0.75, 0.8, 0.8333, 0.85, 0.9, 0.95)]
results["cutoff_sensitivity"] = sens
modeling good rate 0.7 accept everyone -80000.0 cutoff 0.8333333333333334
five fold cross validation on the 800 modeling records
  Logistic regression    C = 0.003                          auc 0.7944 profit    4125.0 accepted   48.8 (0.0s)
  Logistic regression    C = 0.01                           auc 0.7950 profit   15750.0 accepted  232.5 (0.0s)
  Logistic regression    C = 0.03                           auc 0.7922 profit   15000.0 accepted  330.0 (0.0s)
  Logistic regression    C = 0.1                            auc 0.7874 profit   14375.0 accepted  383.8 (0.0s)
  Logistic regression    C = 1                              auc 0.7821 profit   11125.0 accepted  418.8 (0.0s)
  Logistic regression    C = 10                             auc 0.7809 profit   11125.0 accepted  426.2 (0.0s)
  k-nearest neighbors    n_neighbors = 5                    auc 0.7171 profit    5500.0 accepted  310.0 (0.0s)
  k-nearest neighbors    n_neighbors = 11                   auc 0.7410 profit    9500.0 accepted  260.0 (0.0s)
  k-nearest neighbors    n_neighbors = 21                   auc 0.7466 profit   11250.0 accepted  255.0 (0.0s)
  k-nearest neighbors    n_neighbors = 41                   auc 0.7699 profit   11375.0 accepted  173.8 (0.0s)
  k-nearest neighbors    n_neighbors = 61                   auc 0.7760 profit   13750.0 accepted  175.0 (0.0s)
  k-nearest neighbors    n_neighbors = 81                   auc 0.7762 profit   10500.0 accepted  135.0 (0.0s)
  Naive Bayes            alpha = 0.25                       auc 0.7759 profit   15625.0 accepted  463.8 (0.0s)
  Naive Bayes            alpha = 0.5                        auc 0.7762 profit   16250.0 accepted  470.0 (0.0s)
  Naive Bayes            alpha = 1                          auc 0.7764 profit   16125.0 accepted  483.8 (0.0s)
  Naive Bayes            alpha = 3                          auc 0.7758 profit   12625.0 accepted  553.8 (0.0s)
  Decision tree          max_depth = 2                      auc 0.6835 profit    6875.0 accepted  376.2 (0.0s)
  Decision tree          max_depth = 3                      auc 0.7133 profit    7500.0 accepted  360.0 (0.0s)
  Decision tree          max_depth = 4                      auc 0.7215 profit    5500.0 accepted  377.5 (0.0s)
  Decision tree          max_depth = 5                      auc 0.7119 profit    5625.0 accepted  371.2 (0.0s)
  Decision tree          max_depth = 6                      auc 0.7166 profit    5750.0 accepted  417.5 (0.0s)
  Random forest          min_samples_leaf = 1               auc 0.7935 profit   16375.0 accepted  298.8 (0.9s)
  Random forest          min_samples_leaf = 5               auc 0.7926 profit   16875.0 accepted  273.8 (0.9s)
  Random forest          min_samples_leaf = 10              auc 0.7889 profit   14125.0 accepted  238.8 (0.9s)
  Gradient boosted trees learning_rate = 0.03, max_depth = 2 auc 0.7819 profit   13375.0 accepted  351.2 (0.2s)
  Gradient boosted trees learning_rate = 0.05, max_depth = 3 auc 0.7882 profit   14375.0 accepted  428.8 (0.3s)
  Gradient boosted trees learning_rate = 0.1, max_depth = 2 auc 0.7909 profit   15000.0 accepted  450.0 (0.2s)
  Gradient boosted trees learning_rate = 0.2, max_depth = 2 auc 0.7799 profit   12125.0 accepted  481.2 (0.2s)
  Gradient boosted trees learning_rate = 0.1, max_depth = 3 auc 0.7808 profit   12125.0 accepted  481.2 (0.3s)
  Neural network         hidden_layer_sizes = (8,), alpha = 0.0001, learning_rate_init = 0.001 auc 0.6811 profit    3125.0 accepted   53.8 (0.2s)
  Neural network         hidden_layer_sizes = (8,), alpha = 0.0001, learning_rate_init = 0.01 auc 0.7633 profit   14000.0 accepted  335.0 (0.1s)
  Neural network         hidden_layer_sizes = (8,), alpha = 0.001, learning_rate_init = 0.001 auc 0.6811 profit    3125.0 accepted   53.8 (0.2s)
  Neural network         hidden_layer_sizes = (8,), alpha = 0.001, learning_rate_init = 0.01 auc 0.7633 profit   14000.0 accepted  335.0 (0.1s)
  Neural network         hidden_layer_sizes = (8,), alpha = 0.01, learning_rate_init = 0.001 auc 0.6870 profit    4125.0 accepted   63.8 (0.2s)
  Neural network         hidden_layer_sizes = (8,), alpha = 0.01, learning_rate_init = 0.01 auc 0.7632 profit   13875.0 accepted  333.8 (0.1s)
  Neural network         hidden_layer_sizes = (8,), alpha = 0.1, learning_rate_init = 0.001 auc 0.6872 profit    4125.0 accepted   63.8 (0.2s)
  Neural network         hidden_layer_sizes = (8,), alpha = 0.1, learning_rate_init = 0.01 auc 0.7633 profit   13875.0 accepted  333.8 (0.1s)
  Neural network         hidden_layer_sizes = (16,), alpha = 0.0001, learning_rate_init = 0.001 auc 0.7573 profit   13625.0 accepted  286.2 (0.1s)
  Neural network         hidden_layer_sizes = (16,), alpha = 0.0001, learning_rate_init = 0.01 auc 0.7647 profit   15625.0 accepted  366.2 (0.1s)
  Neural network         hidden_layer_sizes = (16,), alpha = 0.001, learning_rate_init = 0.001 auc 0.7572 profit   13625.0 accepted  286.2 (0.1s)
  Neural network         hidden_layer_sizes = (16,), alpha = 0.001, learning_rate_init = 0.01 auc 0.7648 profit   15750.0 accepted  367.5 (0.1s)
  Neural network         hidden_layer_sizes = (16,), alpha = 0.01, learning_rate_init = 0.001 auc 0.7573 profit   13500.0 accepted  285.0 (0.1s)
  Neural network         hidden_layer_sizes = (16,), alpha = 0.01, learning_rate_init = 0.01 auc 0.7649 profit   15625.0 accepted  366.2 (0.1s)
  Neural network         hidden_layer_sizes = (16,), alpha = 0.1, learning_rate_init = 0.001 auc 0.7573 profit   13500.0 accepted  285.0 (0.2s)
  Neural network         hidden_layer_sizes = (16,), alpha = 0.1, learning_rate_init = 0.01 auc 0.7650 profit   15500.0 accepted  365.0 (0.1s)
  Neural network         hidden_layer_sizes = (16, 8), alpha = 0.0001, learning_rate_init = 0.001 auc 0.6887 profit    2750.0 accepted   35.0 (0.1s)
  Neural network         hidden_layer_sizes = (16, 8), alpha = 0.0001, learning_rate_init = 0.01 auc 0.7604 profit   13750.0 accepted  415.0 (0.1s)
  Neural network         hidden_layer_sizes = (16, 8), alpha = 0.001, learning_rate_init = 0.001 auc 0.6887 profit    2750.0 accepted   35.0 (0.1s)
  Neural network         hidden_layer_sizes = (16, 8), alpha = 0.001, learning_rate_init = 0.01 auc 0.7559 profit   14500.0 accepted  385.0 (0.1s)
  Neural network         hidden_layer_sizes = (16, 8), alpha = 0.01, learning_rate_init = 0.001 auc 0.6887 profit    2750.0 accepted   35.0 (0.1s)
  Neural network         hidden_layer_sizes = (16, 8), alpha = 0.01, learning_rate_init = 0.01 auc 0.7541 profit   14000.0 accepted  387.5 (0.1s)
  Neural network         hidden_layer_sizes = (16, 8), alpha = 0.1, learning_rate_init = 0.001 auc 0.6890 profit    2750.0 accepted   35.0 (0.1s)
  Neural network         hidden_layer_sizes = (16, 8), alpha = 0.1, learning_rate_init = 0.01 auc 0.7628 profit   14000.0 accepted  395.0 (0.1s)
  Logistic regression, codes one-hot C = 0.003                          auc 0.7903 profit    6875.0 accepted   98.8 (0.0s)
  Logistic regression, codes one-hot C = 0.01                           auc 0.7868 profit   15750.0 accepted  277.5 (0.0s)
  Logistic regression, codes one-hot C = 0.03                           auc 0.7811 profit   15125.0 accepted  361.2 (0.0s)
  Logistic regression, codes one-hot C = 0.1                            auc 0.7738 profit   12875.0 accepted  413.8 (0.0s)
  Logistic regression, codes one-hot C = 1                              auc 0.7666 profit   11625.0 accepted  438.8 (0.0s)
  Logistic regression, codes one-hot C = 10                             auc 0.7650 profit   11750.0 accepted  440.0 (0.0s)
  Logistic regression with protected attributes C = 0.003                          auc 0.8003 profit    5125.0 accepted   58.8 (0.0s)
  Logistic regression with protected attributes C = 0.01                           auc 0.8029 profit   15750.0 accepted  232.5 (0.0s)
  Logistic regression with protected attributes C = 0.03                           auc 0.8013 profit   14500.0 accepted  340.0 (0.0s)
  Logistic regression with protected attributes C = 0.1                            auc 0.7982 profit   16375.0 accepted  396.2 (0.0s)
  Logistic regression with protected attributes C = 1                              auc 0.7924 profit   17375.0 accepted  428.8 (0.0s)
  Logistic regression with protected attributes C = 10                             auc 0.7896 profit   15625.0 accepted  433.8 (0.0s)

8. choose the model, then score the holdout once

In [6]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# ---- 8. choose the model, then score the holdout once ----------------------------------
lb = sorted(results["leaderboard"], key=lambda r: (-r["profit_per_1000"], -r["auc"]))
leader = lb[0]["model"]
logit = next(r for r in lb if r["model"] == "Logistic regression")
gap = lb[0]["profit_per_1000"] - logit["profit_per_1000"]
chosen = "Logistic regression" if gap < RULE_DM else leader
results["selection"] = {"leaderboard_winner": leader, "chosen": chosen, "gap_vs_logistic": round(gap, 1),
                        "rule": f"Logistic regression deploys unless another model beats it by at least {RULE_DM:,.0f} DM per 1,000 applicants in cross validation."}
print("leader", leader, "chosen", chosen, "gap", round(gap, 1), flush=True)

m = fitted[chosen]
m.fit(X_m, y_m)
p_ho = m.predict_proba(X_ho)[:, 1]
ho = {"auc": round(float(roc_auc_score(y_ho, p_ho)), 4), **profit_per_1000(y_ho, p_ho)}
gh = float(y_ho.mean())
ho["accept_everyone_profit_per_1000"] = round((gh * GAIN_GOOD - (1 - gh) * LOSS_BAD) * PER, 1)
ho["lift"] = profit_lift(y_ho, p_ho)
peak = max(ho["lift"], key=lambda r: r["cumulative_profit"])
ho["peak_decile"] = peak["decile"]; ho["peak_cumulative_profit"] = peak["cumulative_profit"]
ho["cutoff_sweep"] = [{"cutoff": c, **{k: v for k, v in profit_per_1000(y_ho, p_ho, c).items() if k in ("profit_per_1000", "accepted_per_1000")}} for c in (0.5, 0.6, 0.7, 0.8, 0.8333, 0.9)]
results["holdout"] = ho
print("holdout", {k: v for k, v in ho.items() if k not in ("lift", "cutoff_sweep")}, flush=True)
results["cv_lift"] = {name: profit_lift(y_m, p) for name, p in probs.items()}
leader Random forest chosen Logistic regression gap 1125.0
holdout {'auc': 0.7794, 'profit_per_1000': 14500.0, 'accepted_per_1000': 265.0, 'tp': 49, 'fp': 4, 'fn': 91, 'tn': 56, 'precision': 0.9245, 'recall': 0.35, 'accuracy': 0.525, 'accept_everyone_profit_per_1000': -80000.0, 'peak_decile': 3, 'peak_cumulative_profit': 3600.0}

Calibration, because the cost table's cutoff holds only if the probabilities are calibrated

In [7]
1
2
3
4
5
6
7
8
9
# ---- calibration, because the cost table's cutoff holds only if the probabilities are calibrated ------
def calibration(y_true, p, bins=10):
    order = np.argsort(p); n = len(p); rows = []
    for d in range(bins):
        idx = order[int(d * n / bins):int((d + 1) * n / bins)]
        rows.append({"decile": d + 1, "applicants": int(len(idx)), "p_min": round(float(p[idx].min()), 4), "p_max": round(float(p[idx].max()), 4),
                     "mean_predicted": round(float(p[idx].mean()), 4), "observed_good_rate": round(float(y_true[idx].mean()), 4)})
    return rows
results["calibration_oof"] = calibration(y_m, probs[chosen])

The cost ratio, and what happens to the cutoff and the ranking if a bad loan costs 3 or 9 times a good loan's profit

In [8]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
# ---- the cost ratio, and what happens to the cutoff and the ranking if a bad loan costs 3 or 9 times a good loan's profit ----
ratio_rows = []
for ratio in (3, 5, 9):
    loss = GAIN_GOOD * ratio; c = loss / (GAIN_GOOD + loss)
    per_model = {name: profit_per_1000(y_m, p, c, GAIN_GOOD, loss) for name, p in probs.items()}
    best_name = max(per_model, key=lambda k: per_model[k]["profit_per_1000"])
    lr_ = per_model["Logistic regression"]
    ratio_rows.append({"ratio": ratio, "loss_bad": loss, "cutoff": round(c, 4), "accept_everyone": round((gm * GAIN_GOOD - (1 - gm) * loss) * PER, 1),
                       "logistic_profit_per_1000": lr_["profit_per_1000"], "logistic_accepted_per_1000": lr_["accepted_per_1000"],
                       "best_model": best_name, "best_profit_per_1000": per_model[best_name]["profit_per_1000"],
                       "gap_vs_logistic": round(per_model[best_name]["profit_per_1000"] - lr_["profit_per_1000"], 1)})
results["cost_ratio_sensitivity"] = {"note": "Out of fold on the 800, each model at the setting kept under the book's 5 to 1 table; the cutoff is loss over (gain plus loss).", "rows": ratio_rows}

The chosen model, stated in original units

In [9]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
# ---- the chosen model, stated in original units ---------------------------------------------
if chosen == "Logistic regression":
    scaler = m.named_steps["prep"].named_transformers_["num"]
    lr = m.named_steps["m"]
    intercept = float(lr.intercept_[0]); terms = []
    for j, (f, c) in enumerate(zip(FEATS, lr.coef_[0])):
        c_unit = float(c / scaler.scale_[j]); intercept -= c_unit * float(scaler.mean_[j])
        # full precision: every display rounds once, from these values
        terms.append({"feature": f, "kind": "numeric", "coef_per_unit": c_unit, "odds_multiplier_per_unit": float(np.exp(c_unit)), "std_coef": float(c),
                      "training_mean": float(scaler.mean_[j])})
    results["equation"] = {"intercept": intercept, "terms": terms, "note": "All attributes enter as the book codes them (numeric); coefficients are per unit of the code or the amount. training_mean is the attribute's mean on the 800 modeling records, the reference point for an applicant's reasons."}
    results["top_effects"] = sorted([{"term": t["feature"], "std_coef": t["std_coef"], "odds_multiplier_per_unit": t["odds_multiplier_per_unit"]} for t in terms], key=lambda d: -abs(d["std_coef"]))[:12]

rf = fitted["Random forest"]; rf.fit(X_m, y_m)
results["forest_importance"] = sorted([{"feature": f, "importance": round(float(v), 4)} for f, v in zip(FEATS, rf.named_steps["m"].feature_importances_)], key=lambda d: -d["importance"])

Responsible ML, who gets accepted on the out of fold predictions of the 800

In [10]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# ---- responsible ML, who gets accepted on the out of fold predictions of the 800 ---------------
sel = probs[chosen] >= CUTOFF
def group_table(groups):
    out = []
    for g, idx in groups.items():
        yy, ss = y_m[idx], sel[idx]
        out.append({"group": str(g), "n": int(len(idx)), "good_rate": round(float(yy.mean()), 4), "acceptance_rate": round(float(ss.mean()), 4),
                    "precision": round(float(yy[ss].mean()), 4) if ss.any() else None, "recall": round(float(ss[yy == 1].mean()), 4) if (yy == 1).any() else None})
    return out
band = pd.cut(X_m["AGE"], [0, 24, 39, 59, 200], labels=["under 25", "25 to 39", "40 to 59", "60 and over"])
results["fairness_age"] = group_table(X_m.groupby(band, observed=True).indices)
results["fairness_foreign"] = group_table(X_m.groupby(X_m["FOREIGN"].map({0: "not a foreign worker", 1: "foreign worker"})).indices)
sex = np.where(X_m[["MALE_DIV", "MALE_SINGLE", "MALE_MAR_or_WID"]].sum(axis=1) > 0, "male (any flag)", "no male flag (female or not stated)")
results["fairness_sex"] = group_table(pd.Series(sex, index=X_m.index).groupby(sex).indices)

One new applicant for the live scoring moment

In [11]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# ---- one new applicant for the live scoring moment ------------------------------------------
new = pd.DataFrame([{"CHK_ACCT": 1, "DURATION": 24, "HISTORY": 2, "NEW_CAR": 0, "USED_CAR": 0, "FURNITURE": 0, "RADIO/TV": 1, "EDUCATION": 0, "RETRAINING": 0,
                     "AMOUNT": 3000, "SAV_ACCT": 1, "EMPLOYMENT": 3, "INSTALL_RATE": 3, "MALE_DIV": 0, "MALE_SINGLE": 1, "MALE_MAR_or_WID": 0, "CO-APPLICANT": 0,
                     "GUARANTOR": 0, "PRESENT_RESIDENT": 2, "REAL_ESTATE": 0, "PROP_UNKN_NONE": 0, "AGE": 35, "OTHER_INSTALL": 0, "RENT": 0, "OWN_RES": 1,
                     "NUM_CREDITS": 1, "JOB": 2, "NUM_DEPENDENTS": 1, "TELEPHONE": 1, "FOREIGN": 0}])
p_new = float(m.predict_proba(new)[0, 1])        # stored at full precision; every document rounds it once, to 3 decimals
results["scoring_example"] = {"record": {k: int(v) for k, v in new.iloc[0].items()}, "probability": p_new, "decision": "accept" if p_new >= CUTOFF else "reject"}
# a second applicant that lands on the other side, for the narration
new2 = new.copy(); new2.loc[0, ["CHK_ACCT", "HISTORY", "DURATION", "SAV_ACCT"]] = [3, 4, 12, 4]
p2 = float(m.predict_proba(new2)[0, 1])
results["scoring_example_2"] = {"changes": "checking account: none (3); history: critical (4); duration 12; savings: unknown (4)", "probability": p2, "decision": "accept" if p2 >= CUTOFF else "reject"}

Write

In [12]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
# ---- write ----------------------------------------------------------------------------------
results["leaderboard"] = lb
results["seconds"] = round(time.time() - t0, 1)
json.dump(results, open(os.path.join(RESULTS, "results.json"), "w"), indent=1)
cols = ["model", "setting", "auc", "accuracy_at_half", "profit_per_1000", "accepted_per_1000", "precision", "recall"]
pd.DataFrame(lb)[cols].to_csv(os.path.join(RESULTS, "leaderboard.csv"), index=False)
with open(os.path.join(RESULTS, "leaderboard.md"), "w") as fh:
    fh.write(f"# Leaderboard, five fold cross validation on the {len(X_m)} modeling records\n\n")
    fh.write(f"On the book's net profit table a loan to a good credit earns {GAIN_GOOD:.0f} DM, a loan to a bad credit loses {LOSS_BAD:.0f} DM, and a rejection earns nothing. An applicant is accepted when p(good) is {CUTOFF:.4f} or higher. Profit is expected value per 1,000 applicants. The run uses seed {SEED}.\n\n")
    fh.write("Each row is the best setting of its sweep, scored on the same folds that chose it, so these figures lean optimistic; the holdout line is the check on the chosen model.\n\n")
    fh.write("| Model | Setting kept | AUC | Accuracy at 0.5 | Profit per 1,000 (DM) | Accepted per 1,000 | Precision | Recall |\n|---|---|---|---|---|---|---|---|\n")
    for r in lb:
        fh.write(f"| {r['model']} | {r['setting']} | {r['auc']:.3f} | {r['accuracy_at_half']:.3f} | {r['profit_per_1000']:,.0f} | {r['accepted_per_1000']:.0f} | {r['precision']:.3f} | {r['recall']:.3f} |\n")
    b = results["baselines"]
    fh.write(f"| Accept everyone | none | 0.500 | {b['accept_everyone']['accuracy']:.3f} | {b['accept_everyone']['profit_per_1000']:,.0f} | 1,000 | {gm:.3f} | 1.000 |\n")
    fh.write(f"| Reject everyone | none | 0.500 | {b['reject_everyone']['accuracy']:.3f} | 0 | 0 | 0.000 | 0.000 |\n")
    fh.write(f"\nThe holdout was used once, by the chosen model ({chosen}, refitted on the 800). It scores an AUC of {ho['auc']:.3f} and a profit of {ho['profit_per_1000']:,.0f} DM per 1,000 applicants against {ho['accept_everyone_profit_per_1000']:,.0f} for accepting everyone and 0 for rejecting everyone, and it accepts {ho['accepted_per_1000']:.0f} applicants per 1,000.\n")

Figures, a wide drawing for the report and the page and a narrow portrait one for phones

In [13]
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
# ---- figures, a wide drawing for the report and the page and a narrow portrait one for phones --------
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
INK, ACC, MID, LIGHT = "#1f1a12", "#8a5a00", "#6b6454", "#c9bd9c"
plt.rcParams.update({"font.family": "DejaVu Sans", "axes.edgecolor": INK, "axes.labelcolor": INK, "xtick.color": INK, "ytick.color": INK,
                     "axes.spines.top": False, "axes.spines.right": False})
THOUSANDS = FuncFormatter(lambda v, _: f"{v:,.0f}".replace("-", "−"))
NARROW_W, NARROW_DPI = 4.4, 200      # 880 px wide, about 440 CSS px at 2x


def new_fig(narrow, wide, narrow_h, **kw):
    """The narrow drawing uses constrained layout so a legend or label outside the axes stays inside the 880 px."""
    if narrow:
        return plt.subplots(figsize=(NARROW_W, narrow_h), layout="constrained", **kw)
    return plt.subplots(figsize=wide, **kw)


def save(fig, name, narrow):
    if not narrow:
        fig.tight_layout()
    fig.savefig(os.path.join(FIGURES, f"{name}{'-narrow' if narrow else ''}.png"), dpi=NARROW_DPI if narrow else 160); plt.close(fig)


def fig_roc(narrow):
    fs = 10 if narrow else 8
    fig, ax = new_fig(narrow, (6.4, 5.2), 6.6)
    for name, p in probs.items():
        f_, t_, _ = roc_curve(y_m, p)
        ax.plot(f_, t_, lw=2.2 if name == chosen else 1.0, label=f"{name} ({roc_auc_score(y_m, p):.3f})", color=ACC if name == chosen else None)
    ax.plot([0, 1], [0, 1], ls="--", color=LIGHT, lw=1)
    ax.set_xlabel("False positive rate\n(bad credits accepted)" if narrow else "False positive rate (bad credits accepted)", fontsize=fs + 1)
    ax.set_ylabel("True positive rate (good credits accepted)", fontsize=fs + 1)
    ax.set_title("ROC curves, out of fold on the 800", color=INK, fontsize=fs + 3)
    if narrow:
        fig.legend(fontsize=fs - 1, frameon=False, loc="outside lower center", ncol=1)
    else:
        ax.legend(fontsize=fs, frameon=False, loc="lower right")
    ax.tick_params(labelsize=fs + 1)
    save(fig, "roc-cv", narrow)


def fig_gains(narrow):
    fs = 10 if narrow else 8
    fig, ax = new_fig(narrow, (6.6, 5.0), 6.8)
    for name, rows in results["cv_lift"].items():
        xs = [0] + [r["decile"] * 10 for r in rows]; ys = [0] + [r["cumulative_profit"] / len(X_m) * PER for r in rows]
        ax.plot(xs, ys, marker="o", ms=3, lw=2.2 if name == chosen else 1.0, label=name, color=ACC if name == chosen else None)
    ax.axhline(0, color=LIGHT, lw=1)
    ax.yaxis.set_major_formatter(THOUSANDS)
    ax.set_xlabel("Percent of applicants accepted,\nbest scores first" if narrow else "Percent of applicants accepted, best scores first", fontsize=fs + 1)
    ax.set_ylabel("Cumulative net profit per 1,000 applicants, DM", fontsize=fs + 1)
    ax.set_title("Net profit cumulative gains,\nout of fold (the book's question 4)" if narrow else "Net profit cumulative gains, out of fold (the book's question 4)", color=INK, fontsize=fs + 3)
    if narrow:
        fig.legend(fontsize=fs - 1, frameon=False, loc="outside lower center", ncol=2)
    else:
        ax.legend(fontsize=fs, frameon=False, loc="lower left")
    ax.tick_params(labelsize=fs + 1)
    save(fig, "profit-gains-cv", narrow)


def fig_cutoff(narrow):
    fs = 10 if narrow else 8
    fig, ax = new_fig(narrow, (6.4, 4.2), 5.4)
    for name, rows in sens.items():
        ax.plot([r["cutoff"] for r in rows], [r["profit_per_1000"] for r in rows], marker="o", lw=2, label=name, color=ACC if name == chosen else MID)
    ax.axvline(CUTOFF, color=LIGHT, ls="--"); ax.axhline(0, color=LIGHT, ls=":")
    lo = ax.get_ylim()[0]
    ax.annotate(f"cost table cutoff\n500 / 600 = {CUTOFF:.3f}", xy=(CUTOFF, lo), xytext=(CUTOFF - 0.015, lo + 0.06 * (ax.get_ylim()[1] - lo)),
                ha="right", va="bottom", color=MID, fontsize=fs)
    ax.yaxis.set_major_formatter(THOUSANDS)
    ax.set_xlabel("Cutoff on p(good) for accepting the loan", fontsize=fs + 1); ax.set_ylabel("Profit per 1,000 applicants, DM", fontsize=fs + 1)
    ax.set_title("Where the cost table puts the cutoff,\nlogistic regression, out of fold" if narrow else "Where the cost table puts the cutoff, logistic regression, out of fold", color=INK, fontsize=fs + 3)
    ax.tick_params(labelsize=fs + 1)
    save(fig, "profit-by-cutoff", narrow)


def fig_leaderboard(narrow):
    fs = 10 if narrow else 8
    names = [r["model"] for r in lb] + ["Reject everyone", "Accept everyone"]
    vals = [r["profit_per_1000"] for r in lb] + [0.0, results["baselines"]["accept_everyone"]["profit_per_1000"]]
    if narrow:
        # the models only, each name above its bar so the bars get the full width; the two baselines are stated under the chart
        names, vals = names[:-2], vals[:-2]
        fig, ax = new_fig(True, None, 6.0)
        ys = np.arange(len(names))[::-1] * 1.0
        ax.barh(ys, vals, height=0.42, color=[ACC if n == chosen else MID for n in names])
        for y_, n, v in zip(ys, names, vals):
            ax.text(0, y_ + 0.36, n, ha="left", va="center", fontsize=fs + 1, color=INK, fontweight="bold" if n == chosen else "normal")
            ax.text(v + 250, y_, f"{v:,.0f}", ha="left", va="center", fontsize=fs, color=INK)
        ax.set_yticks([]); ax.spines["left"].set_visible(False)
        ax.set_xlim(0, max(vals) * 1.22); ax.set_ylim(-0.5, len(names) - 0.3)
        ax.xaxis.set_major_formatter(THOUSANDS); ax.set_xticks([0, 5000, 10000, 15000])
        ax.set_xlabel("Profit per 1,000 applicants in cross validation, DM.\nAccept everyone: \u221280,000. Reject everyone: 0.", fontsize=fs)
        ax.set_title("Net profit of every entrant\non the book's cost table", color=INK, fontsize=fs + 3)
        ax.tick_params(labelsize=fs + 1)
        save(fig, "leaderboard", True)
        return
    fig, ax = plt.subplots(figsize=(7.4, 4.4))
    colors = [ACC if n == chosen else (LIGHT if n.endswith("everyone") else MID) for n in names[::-1]]
    ax.barh(names[::-1], vals[::-1], color=colors)
    span = max(vals) - min(vals)
    for i, v in enumerate(vals[::-1]):
        if v < -0.3 * span:     # a long negative bar carries its label inside, clear of the names
            ax.text(v + 0.02 * span, i, f"{v:,.0f}".replace("-", "\u2212"), va="center", ha="left", fontsize=fs, color=INK)
        else:
            ax.text(v + 0.01 * span, i, f"{v:,.0f}", va="center", ha="left", fontsize=fs, color=INK)
    ax.set_xlim(min(vals), max(vals) + 0.16 * span)
    ax.axvline(0, color=INK, lw=0.8)
    ax.xaxis.set_major_formatter(THOUSANDS)
    ax.set_xlabel("Profit per 1,000 applicants in cross validation, DM", fontsize=fs + 1)
    ax.set_title("Net profit of every entrant, on the book's cost table", color=INK, fontsize=fs + 3)
    ax.tick_params(labelsize=fs + 1)
    save(fig, "leaderboard", False)


def fig_importance(narrow):
    fs = 10 if narrow else 8
    fig, ax = new_fig(narrow, (6.4, 4.4), 5.6)
    top = results["forest_importance"][:12]
    ax.barh([t["feature"] for t in top][::-1], [t["importance"] for t in top][::-1], color=MID)
    ax.set_xlabel("Share of impurity reduction\nacross 300 trees" if narrow else "Share of impurity reduction across 300 trees", fontsize=fs + 1)
    ax.set_title("Random forest\nvariable importance" if narrow else "Random forest variable importance", color=INK, fontsize=fs + 3)
    ax.tick_params(labelsize=fs + 1)
    save(fig, "forest-importance", narrow)


def fig_eda(narrow):
    fs = 10 if narrow else 9
    tr = X_m.assign(y=y_m)
    panels = [("Checking account", tr.groupby("CHK_ACCT")["y"].mean() * 100, ["below\n0 DM", "0 to\n200 DM", "above\n200 DM", "no\naccount"]),
              ("Credit history", tr.groupby("HISTORY")["y"].mean() * 100, ["no\ncredits", "all paid\nhere", "paid\nso far", "delays", "critical"]),
              ("Age band", tr.groupby(pd.cut(tr["AGE"], [0, 24, 29, 39, 49, 59, 200], labels=["to 24", "25 to 29", "30s", "40s", "50s", "60 and over"]), observed=True)["y"].mean() * 100,
               ["to 24", "25\nto 29", "30s", "40s", "50s", "60 and\nover"])]
    if narrow:
        fig, axs = new_fig(True, None, 8.6, nrows=3, ncols=1)
    else:
        fig, axs = plt.subplots(1, 3, figsize=(11, 3.9))
    for a, (title, vals, labels) in zip(axs, panels):
        a.bar(labels, vals.values, color=MID)
        for x, v in enumerate(vals.values):
            a.text(x, v + 2, f"{v:.0f}", ha="center", va="bottom", fontsize=fs - 1, color=INK)
        a.set_title(title, fontsize=fs + 2, color=INK); a.set_ylim(0, 105); a.set_yticks([0, 25, 50, 75, 100])
        a.tick_params(axis="x", labelsize=fs - 1); a.tick_params(axis="y", labelsize=fs)
    axs[0].set_ylabel("Good credit, %", fontsize=fs)
    if narrow:
        for a in axs[1:]:
            a.set_ylabel("Good credit, %", fontsize=fs)
    fig.suptitle("Good credit rate, % of applicants,\non the 800 modeling records" if narrow else "Good credit rate, % of applicants, on the 800 modeling records only", color=INK, fontsize=fs + 3)
    save(fig, "eda", narrow)


def fig_confusion(narrow):
    fig, ax = new_fig(narrow, (4.6, 3.6), 4.0)
    cm = np.array([[ho["tp"], ho["fn"]], [ho["fp"], ho["tn"]]])
    ax.imshow(cm, cmap="YlOrBr", vmin=0)
    for i in range(2):
        for j in range(2):
            ax.text(j, i, f"{cm[i, j]:,}", ha="center", va="center", color="white" if cm[i, j] > 0.75 * cm.max() else INK, fontsize=14)  # light digits on the dark cells
    ax.set_xticks([0, 1], ["Accepted", "Rejected"]); ax.set_yticks([0, 1], ["Good credit", "Bad credit"])
    ax.tick_params(labelsize=11 if narrow else 10)
    for sp in ax.spines.values():
        sp.set_visible(False)
    ax.set_title(f"Holdout confusion matrix\nat cutoff {CUTOFF:.3f}" if narrow else f"Holdout confusion matrix at cutoff {CUTOFF:.3f}", color=INK, fontsize=12 if narrow else 10)
    save(fig, "holdout-confusion", narrow)


for draw in (fig_roc, fig_gains, fig_cutoff, fig_leaderboard, fig_importance, fig_eda, fig_confusion):
    draw(False); draw(True)
print("done in", results["seconds"], "s; chosen", chosen, flush=True)
done in 7.8 s; chosen Logistic regression

The charts the run wrote to ../figures

In [14]
1
2
3
from IPython.display import Image, display
for f in ["eda", "leaderboard", "roc-cv", "profit-gains-cv", "profit-by-cutoff", "forest-importance", "holdout-confusion"]:
    display(Image(filename=os.path.join(FIGURES, f + ".png")))
Notebook output image
Notebook output image
Notebook output image
Notebook output image
Notebook output image
Notebook output image
Notebook output image

Licensed CC BY-NC-ND 4.0: share with credit, no commercial use, no changes. The Project Shelf Team, Fall 2026.

Case 23.2, German Credit, from Shmueli, Bruce, Deokar and Patel, Machine Learning for Business Analytics (RapidMiner edition, Wiley, 2023), solved by the course instructor as a worked example.