WORKINGAICHAPTER 15

Gradient-boosted credit models and explaining a decline to the customer

A boosted model can find patterns a points table cannot. It has to beat the table on loans it never saw, and it still owes every declined customer a reason that is true

60 MINLENDING AND CREDITUPDATED 2026-11-14
PREDICT

In the lab you train a simple logistic regression and a gradient-boosted model on the same 465 finished loans from January to March, with the same 11 features, and test both on the 2,110 finished loans applied for from April to June. Boosted models are the usual winners in credit modelling competitions. How does the boosted model's test AUC compare with the logistic regression's?

A gradient-boosted model is a way of building a prediction out of many small decision trees. A decision tree asks a series of yes-or-no questions about an applicant (“bureau score above 640?”, “more than two enquiries?”) and ends in a leaf that holds a number. This chapter has two jobs. The first is to measure what such a model adds to a scorecard on Owoleaf’s loan book, and to be honest about the answer when it adds little. The second is to explain a decline, which every credit model, readable or not, has to be able to do. How a points table is built is the job of the credit scoring chapter that comes earlier in this module, so the lab here builds only a simple logistic baseline. It uses the same split date (applications before 1 April train, later ones test) but a different target, described below, so its figures do not match that chapter’s. On this loan book the boosted model does not win.

What boosting does

Start with a prediction that is the same for everyone: the share of loans that go bad. Look at where it is wrong. Fit a small tree to those errors and add a fraction of its answer to the prediction. Fit another tree to what is still wrong, add a fraction of it, and repeat. After a hundred rounds the prediction is a sum of a hundred small corrections. “Gradient” refers to how each tree is aimed: at the direction in which the model’s loss falls fastest. The knobs matter more, because each one trades fit for stability.

Knob What it does Too far
Number of trees (max_iter) More rounds of correction Memorises the training loans
Learning rate How much of each tree is added Large steps overfit quickly; small steps need more trees
Depth (max_depth) How many questions a tree may chain; depth 2 allows one pair of questions together Deep trees fit interactions that exist only by chance
Leaf size (min_samples_leaf) The fewest loans a leaf may hold Tiny leaves describe single borrowers
L2 regularisation A penalty on large leaf values Too much and the model predicts the average

The model in the lab is scikit-learn’s HistGradientBoostingClassifier. It sorts each feature into at most 255 bins before it searches for splits, which makes it fast, and it reads a missing value as information. That suits a credit file: a thin file has no bureau score, and the model can learn that “no score” is a group of its own, where a logistic regression needs a stand-in value and a flag.

What “better” means

You met AUC in the module 1 AI chapter: the chance that a random bad borrower scores worse than a random good one. On the test loans there are 284 bad and 1,826 good, so 284 × 1,826 = 518,584 pairs, and the AUC is the share of those pairs the model puts in the right order. Three more measures help.

KS (Kolmogorov-Smirnov) walks down the scores from riskiest to safest and tracks two running totals: the share of all bad loans seen and the share of all good loans seen. KS is the biggest gap between them. Scorecard teams like it because it shows where the score separates the groups most.

Calibration asks whether the numbers mean what they say. Sort the loans by predicted risk into equal bands. In each band, compare the average prediction with the share that really went bad. A model can rank well and still be badly calibrated: it says 4% when the truth is 6%. That matters as soon as you price from the number, which the chapter on decisions and pricing does.

Lift is a band’s bad rate divided by the overall bad rate. A riskiest band with a lift of 1.34 has a bad rate 34% above average.

Every one of these must be computed on out-of-time loans: applications later than anything the model was trained on. A random split mixes months and lets the model learn the lender’s habits from neighbours of the loan it is tested on. The data-leakage lesson shows why, and the fraud-scoring chapter in Payments uses the same split for the same reason.

Which loans count, and why that is a choice

The loan book is observed until 2026-10-28. A loan can only be labelled once its story is finished. A salary advance has one repayment 30 days after disbursement, so by the cut-off you know whether it was paid. A twelve-month personal loan disbursed in May has about seven instalments still to fall due. If you labelled it good because it is current, you would be guessing. If you left out every open loan, you would keep the defaulters (a loan that has stopped is already in default) and drop the good borrowers (their loans are still open), so a long loan would look as if it always ends badly. That is a bias, and the lab avoids it.

The lab uses one rule. A loan is finished when its last instalment fell due at least 90 days before the cut-off, that is, by 2026-07-30. By then it is closed or it is in default: bad means 90 or more days past due, or written off. Of the 3,645 loans, 2,575 are finished and 343 of them (13.3%) are bad. The other 1,070 are left out. The price is that long personal loans and six-month SME loans nearly vanish from the sample, and loans applied for in May and June are mostly salary advances and buy-now-pay-later. The mix of products changes over the test months, and that is one of the reasons the results move from month to month. The credit scoring chapter instead asks whether a loan went 90 days past due within 120 days of disbursement, which keeps more loans and sees fewer late failures.

The split is by application date. Loans applied for before 2026-04-01 train the models: 465 loans, 59 of them bad. Loans from April to June test them: 2,110 loans, 284 bad. Fifty-nine bad loans is small for a flexible model, which is the position most lenders are in when they first try one.

Overfitting, and what the lab shows

Boosting overfits because it keeps going. Each round fits what is left, and after enough rounds what is left is noise. The lab trains three models and prints the training AUC next to the test AUC. The gap is the overfit.

Model Train AUC Test AUC Test KS
Logistic regression 0.717 0.599 0.171
Boosted, shallow trees, 100 rounds 0.819 0.579 0.163
Boosted, deep trees, 300 rounds 1.000 0.542 0.084

The last row has memorised every training loan, so its training AUC is perfect and its test AUC is the worst. A vendor’s headline AUC is often a training or random-split figure, so ask which.

The first two rows are close, so is the gap real? Resample the 2,110 test loans 500 times with replacement and recompute both AUCs each time. The boosted model’s AUC minus the logistic regression’s runs from -0.040 to -0.002 across the middle 95% of resamples, and it is ahead in 2% of them. So it is a little behind. That test ignores the chance in the 465 training loans, which would widen the range. Refitting each model on ten resamples of the training loans moves the test AUC from 0.571 to 0.612 for the logistic regression and from 0.553 to 0.604 for the boosted model. The two ranges overlap almost completely. You cannot pick a winner on the strength of one fit.

Does more history help? Test only on June’s 806 loans and train on everything earlier. With 465 training loans the AUCs are 0.624 for the logistic regression and 0.613 for the boosted model; with 993 they are 0.644 and 0.635; with 1,769 they are 0.652 and 0.635. Both improve, and the boosted model does not catch up. Do not generalise. The data here is generated and its hidden risk is close to additive, which favours a model that adds. A real book can have interactions that a boosted model finds and a logistic regression misses; the lab shows how to find out, and does not predict your result.

Calibration shows another weakness the AUC hides. The logistic regression’s safest fifth of test loans is predicted at 3.6% bad and is actually 5.9%. Its riskiest fifth is predicted at 25.2% and is actually 18.0%. Both models are over-confident: the predictions spread wider than the outcomes. The riskiest band’s bad rate is about three times the safest band’s (18.0% against 5.9%), so the models rank, but the numbers must be recalibrated before they price anything.

Monotonic constraints

A scorecard cannot say that a higher bureau score means more risk, because its points go one way by construction. A free boosted model can. With 347 hits in training, a tree may split on the score at 640, find by chance that the loans slightly above it did a little worse, and put a bump in the curve. The lab steps each feature to its next safer value for every test loan and counts how often the predicted risk goes up:

  • bureau score +10 points: 196 of 1,523 loans in the free boosted model;
  • monthly wallet inflow up by about a quarter (+0.1 on the log10 scale, a factor of 1.26): 494 of 2,110;
  • one more year of credit history: 95 of 2,110;
  • one fewer enquiry in 90 days: 566 of 2,110.

A monotonic constraint (monotonic_cst in scikit-learn) tells each tree that it may not split in a way that breaks the stated direction. With constraints the counts are 0 everywhere, and the test AUC moves from 0.579 to 0.584, a small gain and not a loss. Constraints also make the model something you can defend: improving a feature cannot be punished.

The logistic regression is not clean either. Its step counts are 2,110 of 2,110 for inflow and for enquiries, because the fitted coefficients have the wrong sign: more wallet inflow raises the predicted risk and fewer enquiries raise it too. Selection (only applicants who passed the rule are in the data) and chance (59 bad loans) are both plausible, and the lab does not separate them. A scorecard builder fixes this by binning and checking each bin’s trend, as the credit scoring chapter does. A wrong sign is a stop condition for customer reasons too: step 7 checks the signs before it generates any, and refuses to issue reasons from a model that fails.

A model that has never seen the people it declines

The models are trained on loans, and loans exist only for applicants the lender approved. The lowest bureau score among the training loans is 561. Among all 8,386 applicants it is 300. The most enquiries in 90 days among loans is 6, and among applicants 8. The lender’s rule keeps these people out, so a model trained on loans has nothing to say about them and is asked to say something anyway.

The lab prints the predicted chance of going bad for a typical applicant as only the score varies. The logistic regression gives 38.3% at 480 and 24.0% at 560, extending its straight line. The boosted model gives 22.8% at every score from 480 to 600, since a tree cannot extrapolate: below the lowest score it saw, it repeats its last answer. Both are guesses, about 15 percentage points apart at 480. Credit people call the repair reject inference, estimating how declined applicants would have behaved. It is an estimate, and module 3 treats it.

Explaining a decline

A declined customer asks why. A boosted model does not hand over a table of points, so you have to construct an answer. Three kinds of answer are in use, and each says something different.

Reason codes from a scorecard. Every row’s points are known. A customer’s reasons are the rows where they lost most against a reference, such as the best or the average in that attribute. The answer is exact because the model is the table.

Local attributions. For one applicant, how much did each feature push the score above or below a background of typical applicants? The standard tool is the Shapley value, from game theory. Treat the features as players who together produce the gap between this applicant’s score and the average score. A feature’s Shapley value is its average marginal contribution over every order in which the features could join. With nine groups of features there are 2⁹ = 512 coalitions, small enough to compute exactly by brute force, which the lab does. The result adds up: the average score plus every share equals the model’s own output for the applicant. The lab checks that, and the largest gap across ten explanations is 1.6e-15, rounding error. For a logistic regression the Shapley value of a feature is its coefficient times how far the applicant sits from the average, so the same code gives the scorecard’s answer. Libraries such as SHAP compute such values faster for big models; the lab uses none.

Counterfactuals. What is the smallest change that would have flipped the decision? “You would have been approved with a bureau score of 643 or more.” Wachter, Mittelstadt and Russell argue that this kind of statement tells the person something they can act on without opening the model. It has a catch the lab shows: the answer belongs to the model, not to the person.

Each says something different, and none says everything. An attribution says what the model’s number is made of. It does not say what happens if you change the feature, because a boosted model’s response is not a straight line. A counterfactual says what would flip the decision. It does not say whether the person can do it. A customer cannot raise a bureau score by 88 points on request.

The lab explains five applicants whom the lender’s current rule declined between April and June: application 12 and application 20 for a score below the cut-off, 226 for recent delinquency, 1911 for too many enquiries, and 7 for insufficient income evidence. It does that for both the logistic regression and the constrained boosted model, refitted on every finished loan as you would before going live.

  • The models agree where the signal is strong. For applications 12, 20 and 1911 both models name the bureau score first.
  • They disagree on the counterfactual. For application 12, with a score of 555, the logistic regression needs 643 (+88) and the boosted model needs 691 (+136). The boosted model’s curve is a staircase, and for this applicant its answer jumps at 691. Two honest models, two instructions.
  • Some declines are not the model’s. Application 226 has a score of 759 and was declined for delinquency. Both models rate it as safe: predicted risk 7.3% and 9.8%, below the 13.3% average. Asked for reasons anyway, they return a ranking of small positive numbers. That ranking is noise. Over 20 refits on resampled loans, the logistic regression’s top reason for 226 is the same in 12 and the boosted model’s in 9; for application 7, 6 and 10. For the declines the models make themselves, the top reason holds in 19 or 20 of 20 refits. So give reasons only for decisions the model made, and treat a list of weak reasons as a sign that the rule, and not the model, declined the person.
  • The rule’s reason and the model’s reason differ. Application 1911 was declined for too many enquiries. Neither model’s top reason is enquiries: the bureau score is. The models were trained only on applicants with 6 enquiries or fewer, so they have nothing to say about 7.

What the customer is owed

This section states what the sources support and where they stop. A lender’s counsel decides what applies to a particular lender and product; this chapter does not.

In Nigeria, section 37 of the Nigeria Data Protection Act 2023 gives a person the right not to be subject to a decision based solely on automated processing of personal data, including profiling, where it has a legal or similarly significant effect, with exceptions that commentators describe in slightly different words (the person’s consent, a legal requirement, a contract, or a written law with safeguards), and with safeguards where an automated decision is allowed: a way to ask for human involvement, to give a view and to contest the decisionas of 2026-11. It rests on commentary and a copy of the Act hosted by Nigeria’s national CERT, not on the Gazette text. Whether a loan decision has a significant effect, and what counts as human involvement, are legal questions. A search for the Nigeria Data Protection Commission’s 2025 implementing directive found a paper saying it took effect on 19 September 2025, but nothing that states what it requires for automated decisions, so this chapter does not say.

For digital lenders, the Federal Competition and Consumer Protection Commission’s Digital, Electronic, Online, or Non-Traditional Consumer Lending Regulations 2025 require digital lenders to register with the Commission, and, according to law-firm summaries, to disclose lending rates, charges and terms clearly before a transaction, with limits on access to a borrower’s contacts and call logsas of 2026-11. Sources differ on the commencement date: some give 21 July 2025 and one gives 3 September 2025. This chapter could not open the Commission’s PDF from the build environment, and the search results mention no provision on automated decisions or on reasons for a declined application. Do not assume there is one, and do not assume there is not. Read the text, and the consumer protection chapter later in this module returns to these Regulations.

In the United States, the Consumer Financial Protection Bureau’s Circular 2022-03 says that lenders using complex algorithms, including machine learning, must still give a notice stating the specific principal reasons for an adverse action, and that complexity does not excuse a creditor who cannotas of 2026-11. It is a 2022 document, and this chapter could not confirm from search whether the Bureau still treats it as current guidance, so check its status. It does not bind a Nigerian lender. It is useful because it states the test a regulator might apply to a boosted model: can you give the reason that was true?

Whatever the law requires, Owoleaf can set a standard it can defend. The reasons a customer is given are drawn from the model’s real drivers. The list of reason names is approved in advance by credit risk. The reasons are given only for decisions the model made, and only from a model that passes a sign check: a model whose predicted risk rises when a feature moves the safer way issues no reasons. The customer is told a model was used and how to ask a person to look again. The statement of reasons does not promise that a change will produce an approval.

Owoleaf and the boosted model

Back to Idongesit and Oritsejafor. The boosted model does not beat the logistic baseline, both models are over-confident, and the free version has a bump in its score curve. Oritsejafor adds monotonic constraints, which cost nothing in AUC. Idongesit asks for the five declined applicants to be explained by both models, and sees what the lab shows: for the strong declines, the same top reason; for the weak ones, noise. The rule they agree is that the model may decide only where its reasons are stable, and a person reviews the rest. They add a second rule: no reason goes to a customer from a model whose signs fail the check. The logistic regression fails it, so the reasons come from the constrained boosted model.

What they do not do is switch the boosted model on. They keep the scorecard deciding. The boosted model runs silently beside it, as the module 1 AI chapter described, until it has enough finished loans of its own.

  1. What did you train on? Approved loans only; the scores under 561 and enquiries over 6 are guesses.
  2. How was it tested? Out of time, with a range around the number and its bad count.
  3. Does it hold when a feature moves? Monotonic constraints, and a count of violations.
  4. Do the reasons hold? Additive to the model’s output, stable across refits, given only for decisions the model made, and drawn only from a model that passes the sign check.
  5. Who owns it? A named person who can switch it off. The module 3 chapter on model risk covers the rest.
LAB Boosted model against a logistic baseline, then explain five declines ~60 MIN
YOU NEEDPython 3.11 or later (scikit-learn 1.9.1 needs it), with scikit-learn (installed in the lab's own virtual environment: pip install scikit-learn)labs/finance/data1: the scale 1 loan book, built by the README's commandoptional: any free AI chat assistant, for step 7

You compare a boosted model with a logistic regression on the loan book, out of time, and then explain five declines with both. Work in labs/finance. Every figure and amount is illustrative, and every number below comes from scikit-learn 1.9.1 on Python 3.13: another version may differ in the third decimal. Nothing here opens data1/answers/loans_truth.csv or trains on it.

1. Build data1, install scikit-learn and make the modelling table. If data1/ does not exist, build it with the README’s commands (about 40 seconds and 720 MB), and check it. Then make a virtual environment for the chapter.

python3 generate.py --scale 1 --out data1 && python3 loans.py --out data1 \
  && python3 cards.py --out data1 && python3 collect.py --out data1
python3 check.py --db data1/finance.sqlite
python3 -m venv .venv
.venv/bin/pip install scikit-learn

The check ends with the line below, after the loan book, card book and collections lines (it takes about 30 seconds on data1):

OK: all invariants hold

pip prints the packages it installs, scikit-learn among them, and no error. If you already have data1, run only check.py and the two venv lines.

Save this as gbm_data.py. It builds one row per application from features known on the day of the decision: the bureau report, the application, the customer and the wallet’s inflows in the 90 days before the application, never after. It labels a loan only when its story is finished (the rule in the text).

"""Shared by the chapter's scripts: one row per application, features known at the
moment of the decision, and the outcome for loans whose story is finished."""
import sqlite3
import numpy as np

DB = "data1/finance.sqlite"
LAST_MATURITY = "2026-07-30"   # the cut-off, 2026-10-28, less 90 days
CUT = "2026-04-01"          # train: applied before this date; test: on or after it

# Every feature is known when the application arrives. Money is integer kobo in the
# database; the model sees naira on a log scale, which is a unit for the model, not money.
FEATURES = [
    "score", "thin_file", "delinquent_12m", "worst_dpd_24m", "enquiries_90d", "history_years",
    "open_loans", "log_outstanding", "log_requested", "instalments", "log_monthly_inflow",
    "n_inflows_90d", "days_active", "kyc_tier", "is_merchant",
    "prod_SAL", "prod_PL", "prod_BNPL", "prod_SME", "ch_app", "ch_ussd", "ch_checkout",
]

SQL = """
SELECT a.id, a.applied_at, a.decision, a.decline_reason, a.product, a.channel,
       a.requested_kobo, a.instalments,
       b.hit, b.score, b.open_loans, b.outstanding_kobo, b.delinquent_12m, b.worst_dpd_24m,
       b.enquiries_90d, b.history_years,
       c.kyc_tier, c.kind, c.signup_at,
       (SELECT COALESCE(SUM(t.amount_kobo), 0) FROM transactions t
         WHERE t.customer_id = a.customer_id AND t.status = 'succeeded'
           AND t.kind IN ('funding_transfer', 'funding_card')
           AND t.created_at < a.applied_at AND t.created_at >= date(a.applied_at, '-90 day')),
       (SELECT COUNT(*) FROM transactions t
         WHERE t.customer_id = a.customer_id AND t.status = 'succeeded'
           AND t.kind IN ('funding_transfer', 'funding_card')
           AND t.created_at < a.applied_at AND t.created_at >= date(a.applied_at, '-90 day')),
       l.status, l.maturity_date
FROM applications a
JOIN bureau_reports b ON b.id = a.bureau_report_id
JOIN customers c ON c.id = a.customer_id
LEFT JOIN loans l ON l.application_id = a.id
ORDER BY a.id"""


def load(db_path=DB):
    db = sqlite3.connect(db_path)
    X, meta = [], []
    for (aid, applied, decision, reason, product, channel, req, n, hit, score, open_loans,
         outstanding, delinq, worst, enq, hist, tier, kind, signup, inflow, n_in, status, maturity) in db.execute(SQL):
        days_active = max(7, (np.datetime64(applied) - np.datetime64(signup[:10])).astype(int))
        monthly = inflow * 30 / min(90, days_active) / 100          # naira a month
        X.append([score if hit else np.nan, 0 if hit else 1, delinq, worst, enq, hist, open_loans,
                  np.log10(1 + outstanding / 100), np.log10(1 + req / 100), n,
                  np.log10(1 + monthly), n_in, days_active, tier, int(kind == "merchant"),
                  int(product == "SAL"), int(product == "PL"), int(product == "BNPL"), int(product == "SME"),
                  int(channel == "app"), int(channel == "ussd"), int(channel == "merchant_checkout")])
        # Outcome: bad = 90+ days past due or written off at the cut-off. A loan's story is
        # finished only if its last instalment fell due 90 or more days before the cut-off:
        # by then it is either closed or in default. Any other loan is labelled -1 and left out.
        if maturity is not None and maturity <= LAST_MATURITY:
            y = 1 if status in ("default", "written_off") else 0
        else:
            y = -1
        meta.append(dict(id=aid, applied=applied, decision=decision, reason=reason, product=product,
                         requested_kobo=req, status=status, y=y, monthly_naira=monthly))
    X = np.array(X, dtype=float)
    y = np.array([m["y"] for m in meta])
    applied = np.array([m["applied"] for m in meta])
    return X, y, applied, meta

# The eleven features both models use. The other eleven in FEATURES are loaded too, so you
# can try them, but they added nothing in the checks the chapter ran.
MODEL = ["score", "thin_file", "kyc_tier", "log_monthly_inflow", "history_years", "delinquent_12m",
         "enquiries_90d", "is_merchant", "prod_SAL", "prod_BNPL", "log_requested"]
# Which way a safer applicant moves each feature, for the monotonic constraints:
# -1 means a higher value must never raise the risk, +1 that it must never lower it, 0 is free.
DIRECTION = {"score": -1, "kyc_tier": -1, "log_monthly_inflow": -1, "history_years": -1,
             "delinquent_12m": 1, "enquiries_90d": 1}


def cols(names):
    return [FEATURES.index(n) for n in names]


if __name__ == "__main__":
    X, y, applied, meta = load()
    j = FEATURES.index("score")
    loans = [m for m in meta if m["status"] is not None]
    print(f"{len(meta):,} applications, {len(loans):,} loans")
    print(f"finished stories (last instalment due by {LAST_MATURITY}): {(y >= 0).sum():,} loans, "
          f"{y[y == 1].sum():,} bad ({y[y >= 0].mean():.1%})")
    print(f"left out, story not finished: {sum(m['y'] == -1 for m in loans):,} loans")
    train, test = (y >= 0) & (applied < CUT), (y >= 0) & (applied >= CUT)
    print(f"train, applied before {CUT}: {train.sum()} loans, {y[train].sum()} bad")
    print(f"test, applied on or after:   {test.sum()} loans, {y[test].sum()} bad")
    print(f"lowest bureau score among training loans: {np.nanmin(X[train, j]):.0f}; "
          f"among all applicants: {np.nanmin(X[:, j]):.0f}")
    print(f"most enquiries in 90 days among training loans: {X[train, FEATURES.index('enquiries_90d')].max():.0f}; "
          f"among all applicants: {X[:, FEATURES.index('enquiries_90d')].max():.0f}")
.venv/bin/python gbm_data.py
8,386 applications, 3,645 loans
finished stories (last instalment due by 2026-07-30): 2,575 loans, 343 bad (13.3%)
left out, story not finished: 1,070 loans
train, applied before 2026-04-01: 465 loans, 59 bad
test, applied on or after:   2110 loans, 284 bad
lowest bureau score among training loans: 561; among all applicants: 300
most enquiries in 90 days among training loans: 6; among all applicants: 8

3,645 loans, of which 2,575 have finished stories and 1,070 are left out. The training loans start at a score of 561 and no more than 6 enquiries; some applicants have scores down to 300 and 8 enquiries. Keep that gap in mind for step 5.

2. Fit the logistic baseline and the boosted model, and compare them out of time. Save this as gbm_models.py. The logistic model standardises its features and gives a thin file the median score with a flag. The boosted model reads a missing score as a value of its own.

"""The two models, built the same way everywhere in the chapter."""
import numpy as np
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from gbm_data import MODEL, DIRECTION, cols


class Logistic:
    """Standardised logistic regression. A thin file has no score: it gets the training
    median score and the thin_file flag carries the difference."""
    def __init__(self, names=MODEL, C=0.3):
        self.names, self.C, self.j = list(names), C, cols(names)

    def _z(self, X):
        Z = X[:, self.j].copy()
        if "score" in self.names:
            k = self.names.index("score")
            Z[np.isnan(Z[:, k]), k] = self.median
        return Z

    def fit(self, X, y):
        if "score" in self.names:
            self.median = np.nanmedian(X[:, self.j][:, self.names.index("score")])
        self.sc = StandardScaler().fit(self._z(X))
        self.m = LogisticRegression(C=self.C, max_iter=2000).fit(self.sc.transform(self._z(X)), y)
        return self

    def logit(self, X):                      # log-odds of bad
        return self.m.decision_function(self.sc.transform(self._z(X)))

    def prob(self, X):
        return 1 / (1 + np.exp(-self.logit(X)))


class Boosted:
    """HistGradientBoostingClassifier. It reads missing scores itself. Conservative
    settings for a few hundred loans: shallow trees, a small step, a floor on leaf size."""
    def __init__(self, names=MODEL, monotone=False, seed=0, **kw):
        self.names, self.j = list(names), cols(names)
        params = dict(max_iter=100, learning_rate=0.05, max_depth=2, min_samples_leaf=30,
                      l2_regularization=1.0, random_state=seed)
        params.update(kw)
        if monotone:
            params["monotonic_cst"] = [DIRECTION.get(n, 0) for n in self.names]
        self.m = HistGradientBoostingClassifier(**params)

    def fit(self, X, y):
        self.m.fit(X[:, self.j], y)
        return self

    def logit(self, X):
        return self.m.decision_function(X[:, self.j])

    def prob(self, X):
        return self.m.predict_proba(X[:, self.j])[:, 1]

Save this as gbm_compare.py. It reports AUC on the training loans and on the test months, KS, and a five-band calibration table.

import numpy as np
from sklearn.metrics import roc_auc_score, roc_curve
from gbm_data import load, CUT
from gbm_models import Logistic, Boosted

X, y, applied, meta = load()
mature = y >= 0
train, test = mature & (applied < CUT), mature & (applied >= CUT)
print(f"train {train.sum()} loans, {y[train].sum()} bad ({y[train].mean():.1%}) | "
      f"test {test.sum()} loans, {y[test].sum()} bad ({y[test].mean():.1%})")


def ks(y_true, p):
    fpr, tpr, _ = roc_curve(y_true, p)
    return (tpr - fpr).max()


models = {
    "logistic": Logistic().fit(X[train], y[train]),
    "boosted": Boosted().fit(X[train], y[train]),
    "boosted, overfit": Boosted(max_iter=300, learning_rate=0.2, max_depth=None, max_leaf_nodes=31,
                                min_samples_leaf=5, l2_regularization=0.0).fit(X[train], y[train]),
}
print(f"\n{'model':<18}{'train AUC':>10}{'test AUC':>10}{'test KS':>9}")
for name, m in models.items():
    print(f"{name:<18}{roc_auc_score(y[train], m.prob(X[train])):>10.3f}"
          f"{roc_auc_score(y[test], m.prob(X[test])):>10.3f}{ks(y[test], m.prob(X[test])):>9.3f}")

print("\ncalibration on the test months: five bands of equal size, riskiest last")
for name in ("logistic", "boosted"):
    p = models[name].prob(X[test])
    order = np.argsort(p)
    print(f"{name}\n  band  loans  mean predicted  actual bad rate  lift")
    for b, idx in enumerate(np.array_split(order, 5), 1):
        actual = y[test][idx].mean()
        print(f"  {b:>4}{len(idx):>7}{p[idx].mean():>16.1%}{actual:>17.1%}{actual / y[test].mean():>7.2f}")
.venv/bin/python gbm_compare.py
train 465 loans, 59 bad (12.7%) | test 2110 loans, 284 bad (13.5%)

model              train AUC  test AUC  test KS
logistic               0.717     0.599    0.171
boosted                0.819     0.579    0.163
boosted, overfit       1.000     0.542    0.084

calibration on the test months: five bands of equal size, riskiest last
logistic
  band  loans  mean predicted  actual bad rate  lift
     1    422            3.6%             5.9%   0.44
     2    422            7.7%            11.6%   0.86
     3    422           12.5%            15.6%   1.16
     4    422           18.8%            16.1%   1.20
     5    422           25.2%            18.0%   1.34
boosted
  band  loans  mean predicted  actual bad rate  lift
     1    422            2.4%             5.7%   0.42
     2    422            8.4%            15.2%   1.13
     3    422           14.4%            14.2%   1.06
     4    422           19.1%            15.6%   1.16
     5    422           24.5%            16.6%   1.23

The overfit model scores a perfect 1.000 on loans it has seen and 0.542 on the test months. The shallow boosted model trails the logistic regression, 0.579 against 0.599. In the calibration bands, the logistic regression’s safest fifth is predicted at 3.6% and is actually 5.9%, and its riskiest fifth is predicted at 25.2% and is actually 18.0%. Both models rank but are over-confident.

3. Check what happens when a feature moves. Save this as gbm_monotone.py. It fits a constrained boosted model, steps each feature to its next safer value for every test loan and counts how often the predicted risk rises. Then it prints the predicted risk of a typical applicant as only the bureau score varies.

import numpy as np
from sklearn.metrics import roc_auc_score
from gbm_data import load, CUT, FEATURES, MODEL, DIRECTION
from gbm_models import Logistic, Boosted

X, y, applied, meta = load()
mature = y >= 0
train, test = mature & (applied < CUT), mature & (applied >= CUT)
models = {"logistic": Logistic().fit(X[train], y[train]),
          "boosted": Boosted().fit(X[train], y[train]),
          "boosted, constrained": Boosted(monotone=True).fit(X[train], y[train])}
for name, m in models.items():
    print(f"{name:<22} test AUC {roc_auc_score(y[test], m.prob(X[test])):.3f}")

print("\nStep each feature to its next safer value for every test loan. How often does the risk go UP?")
steps = {"score": 10, "kyc_tier": 1, "log_monthly_inflow": 0.1, "history_years": 1,
         "delinquent_12m": -1, "enquiries_90d": -1}      # the safer direction
print(f"{'feature':<22}" + "".join(f"{n:>22}" for n in models))
for f, step in steps.items():
    k = FEATURES.index(f)
    rows = test & ~np.isnan(X[:, k])
    a = X[rows].copy()
    b = a.copy()
    b[:, k] = a[:, k] + step
    cells = []
    for m in models.values():
        up = (m.logit(b) - m.logit(a)) > 1e-12
        cells.append(f"{up.sum():>5} of {rows.sum()}")
    print(f"{f + ' (' + format(step, '+g') + ')':<22}" + "".join(f"{c:>22}" for c in cells))

print("\nPredicted chance of going bad, one typical applicant, bureau score varied:")
S = FEATURES.index("score")
typical = np.nanmedian(X[train], axis=0)
typical[FEATURES.index("thin_file")] = 0
scores = [480, 520, 560, 600, 640, 680, 720, 760, 800]
grid = np.tile(typical, (len(scores), 1))
grid[:, S] = scores
print(f"{'score':<22}" + "".join(f"{s:>7}" for s in scores))
for name, m in models.items():
    print(f"{name:<22}" + "".join(f"{p:>7.1%}" for p in m.prob(grid)))
print("lowest score in the training loans:", int(np.nanmin(X[train, S])))
.venv/bin/python gbm_monotone.py
logistic               test AUC 0.599
boosted                test AUC 0.579
boosted, constrained   test AUC 0.584

Step each feature to its next safer value for every test loan. How often does the risk go UP?
feature                             logistic               boosted  boosted, constrained
score (+10)                        0 of 1523           196 of 1523             0 of 1523
kyc_tier (+1)                      0 of 2110             0 of 2110             0 of 2110
log_monthly_inflow (+0.1)          2110 of 2110           494 of 2110             0 of 2110
history_years (+1)                 0 of 2110            95 of 2110             0 of 2110
delinquent_12m (-1)                0 of 2110             0 of 2110             0 of 2110
enquiries_90d (-1)              2110 of 2110           566 of 2110             0 of 2110

Predicted chance of going bad, one typical applicant, bureau score varied:
score                     480    520    560    600    640    680    720    760    800
logistic                38.3%  30.7%  24.0%  18.4%  13.9%  10.3%   7.6%   5.5%   4.0%
boosted                 22.8%  22.8%  22.8%  22.8%  16.3%  17.6%  17.6%   3.3%   1.7%
boosted, constrained    22.4%  22.4%  22.4%  22.4%  16.5%  16.5%  16.5%   3.8%   1.8%
lowest score in the training loans: 561

The free boosted model raises its prediction when the score rises in 196 of 1,523 loans, and when inflow rises in 494 of 2,110. The constrained model does it in none. The logistic regression has two wrong-signed coefficients (inflow and enquiries): all 2,110 loans move the wrong way. In the last table the boosted model is flat at 22.8% from 480 to 600, below its lowest training score of 561 and a little above, while the logistic regression keeps extending its line.

4. Ask how sure you can be. Save this as gbm_stability.py. It resamples the test loans, looks month by month, refits on resampled training loans and grows the training window.

import numpy as np
from sklearn.metrics import roc_auc_score
from gbm_data import load, CUT
from gbm_models import Logistic, Boosted

X, y, applied, meta = load()
mature = y >= 0
train, test = mature & (applied < CUT), mature & (applied >= CUT)
lr = Logistic().fit(X[train], y[train])
gb = Boosted().fit(X[train], y[train])
pl, pg, yt = lr.prob(X[test]), gb.prob(X[test]), y[test]

print("1. How sure is the gap? 500 resamples of the 2,110 test loans")
rng = np.random.default_rng(0)
al, ag, diff = [], [], []
for _ in range(500):
    i = rng.integers(0, len(yt), len(yt))
    a, b = roc_auc_score(yt[i], pl[i]), roc_auc_score(yt[i], pg[i])
    al.append(a); ag.append(b); diff.append(b - a)
lo = lambda v: np.percentile(v, 2.5)
hi = lambda v: np.percentile(v, 97.5)
print(f"  logistic AUC {roc_auc_score(yt, pl):.3f} (95% range {lo(al):.3f} to {hi(al):.3f})")
print(f"  boosted  AUC {roc_auc_score(yt, pg):.3f} (95% range {lo(ag):.3f} to {hi(ag):.3f})")
print(f"  boosted minus logistic: {lo(diff):+.3f} to {hi(diff):+.3f}; boosted ahead in {np.mean(np.array(diff) > 0):.0%} of resamples")

print("\n2. Month by month on the test loans")
for month in ("2026-04", "2026-05", "2026-06"):
    mk = test & np.array([a.startswith(month) for a in applied])
    print(f"  {month}: {mk.sum():>4} loans, {y[mk].sum():>3} bad  logistic {roc_auc_score(y[mk], lr.prob(X[mk])):.3f}  "
          f"boosted {roc_auc_score(y[mk], gb.prob(X[mk])):.3f}")

print("\n3. Ten refits, each on a resample of the training loans (the boosted seed changes too)")
for name, make in (("logistic", lambda s: Logistic()), ("boosted", lambda s: Boosted(seed=s))):
    aucs = []
    for s in range(10):
        pick = np.random.default_rng(s).choice(np.where(train)[0], train.sum())
        aucs.append(roc_auc_score(yt, make(s).fit(X[pick], y[pick]).prob(X[test])))
    print(f"  {name:<9} test AUC from {min(aucs):.3f} to {max(aucs):.3f}")

print("\n4. Does more history help? Test on June's loans only; train on everything before a date")
june = mature & (applied >= "2026-06-01")
print(f"  June: {june.sum()} loans, {y[june].sum()} bad")
for cut in ("2026-04-01", "2026-05-01", "2026-06-01"):
    tr = mature & (applied < cut)
    a = roc_auc_score(y[june], Logistic().fit(X[tr], y[tr]).prob(X[june]))
    b = roc_auc_score(y[june], Boosted().fit(X[tr], y[tr]).prob(X[june]))
    print(f"  trained before {cut}: {tr.sum():>4} loans, {y[tr].sum():>3} bad   logistic {a:.3f}  boosted {b:.3f}")
.venv/bin/python gbm_stability.py
1. How sure is the gap? 500 resamples of the 2,110 test loans
  logistic AUC 0.599 (95% range 0.567 to 0.631)
  boosted  AUC 0.579 (95% range 0.546 to 0.613)
  boosted minus logistic: -0.040 to -0.002; boosted ahead in 2% of resamples

2. Month by month on the test loans
  2026-04:  528 loans,  73 bad  logistic 0.605  boosted 0.561
  2026-05:  776 loans, 100 bad  logistic 0.565  boosted 0.555
  2026-06:  806 loans, 111 bad  logistic 0.624  boosted 0.613

3. Ten refits, each on a resample of the training loans (the boosted seed changes too)
  logistic  test AUC from 0.571 to 0.612
  boosted   test AUC from 0.553 to 0.604

4. Does more history help? Test on June's loans only; train on everything before a date
  June: 806 loans, 111 bad
  trained before 2026-04-01:  465 loans,  59 bad   logistic 0.624  boosted 0.613
  trained before 2026-05-01:  993 loans, 132 bad   logistic 0.644  boosted 0.635
  trained before 2026-06-01: 1769 loans, 232 bad   logistic 0.652  boosted 0.635

The boosted model is a little behind, with a 95% range of -0.040 to -0.002 for the gap, and its rank in the months changes (April 0.561, May 0.555, June 0.613). Refits overlap. More history lifts both; the boosted model does not catch up in this book. The ranges are from the test loans only, and a real validation would add the training sample’s uncertainty.

5. Explain five declines. Save this as gbm_explain.py. It computes exact Shapley values by brute force over nine groups of features: 512 coalitions, each scored against 100 background loans.

"""Local attributions by brute force: exact Shapley values over groups of features."""
import itertools
import math
import numpy as np
from gbm_data import MODEL, cols

# One reason code per group. The score and the thin-file flag are one fact (what the bureau
# says), and the two product flags are one fact (which product), so they move together.
GROUPS = {
    "bureau score": ["score", "thin_file"],
    "wallet verification level": ["kyc_tier"],
    "monthly wallet inflow": ["log_monthly_inflow"],
    "years of credit history": ["history_years"],
    "delinquencies in 12 months": ["delinquent_12m"],
    "enquiries in 90 days": ["enquiries_90d"],
    "merchant account": ["is_merchant"],
    "product": ["prod_SAL", "prod_BNPL"],
    "amount asked": ["log_requested"],
}


def shapley(logit, x, background):
    """logit: function from a matrix to log-odds of bad. x: one applicant (a row of all
    FEATURES). background: rows to compare with. Returns (base, {group: value}) so that
    base + sum(values) equals logit(x) exactly. Cost: 2**len(GROUPS) subsets."""
    names = list(GROUPS)
    n = len(names)
    gcols = [cols(GROUPS[g]) for g in names]
    m = len(background)
    subsets = list(itertools.product([0, 1], repeat=n))
    big = np.repeat(background[None, :, :], len(subsets), axis=0)          # subsets x m x features
    for s, mask in enumerate(subsets):
        for g, on in enumerate(mask):
            if on:
                big[s][:, gcols[g]] = x[gcols[g]]
    v = logit(big.reshape(-1, background.shape[1])).reshape(len(subsets), m).mean(axis=1)
    value = {mask: v[s] for s, mask in enumerate(subsets)}
    phi = {}
    for g, name in enumerate(names):
        total = 0.0
        for mask in subsets:
            if mask[g] == 0:
                k = sum(mask)
                w = math.factorial(k) * math.factorial(n - k - 1) / math.factorial(n)
                on = list(mask); on[g] = 1
                total += w * (value[tuple(on)] - value[mask])
        phi[name] = total
    return value[(0,) * n], phi


def reasons(phi, top=3):
    """The groups that push the risk up, largest first."""
    ranked = sorted(phi.items(), key=lambda kv: -kv[1])
    return [(k, v) for k, v in ranked[:top] if v > 0]

Save this as gbm_reasons.py. It refits both models on every finished loan, as you would before going live, and explains five applications the lender’s rule declined, using the same background of 100 loans.

import numpy as np
from gbm_data import load, CUT, FEATURES, MODEL, cols
from gbm_models import Logistic, Boosted
from gbm_explain import shapley, reasons

X, y, applied, meta = load()
mature = y >= 0
train = mature                       # refit on every finished loan, as you would before going live
logistic = Logistic().fit(X[train], y[train])
boosted = Boosted(monotone=True).fit(X[train], y[train])

# Five applicants the lender's rule declined in April to June, one per recorded reason
# (two for the score), chosen by application id so everyone gets the same five.
FIVE = [12, 20, 226, 1911, 7]
ids = np.array([m["id"] for m in meta])
bg = X[train][np.random.default_rng(0).choice(train.sum(), 100, replace=False)]   # 100 loans the models learned from
print("pd = predicted chance the loan goes bad; the book's average is "
      f"{y[train].mean():.1%} (training loans)\n")
worst_gap = 0.0
for app in FIVE:
    i = int(np.where(ids == app)[0][0])
    m = meta[i]
    print(f"application {app}: {m['product']}, ₦{m['requested_kobo'] // 100:,}, the rule declined it: {m['reason']}")
    for name, model in (("logistic", logistic), ("boosted ", boosted)):
        base, phi = shapley(model.logit, X[i], bg)
        gap = abs(base + sum(phi.values()) - model.logit(X[i:i + 1])[0])
        worst_gap = max(worst_gap, gap)
        text = "; ".join(f"{k} ({v:+.2f})" for k, v in reasons(phi))
        print(f"  {name} pd {model.prob(X[i:i + 1])[0]:5.1%}  reasons: {text}")
print(f"\nlargest gap between base + attributions and the model's own log-odds: {worst_gap:.1e}")
.venv/bin/python gbm_reasons.py
pd = predicted chance the loan goes bad; the book's average is 13.3% (training loans)

application 12: SAL, ₦39,000, the rule declined it: score_below_cutoff
  logistic pd 29.6%  reasons: bureau score (+0.93); wallet verification level (+0.18); delinquencies in 12 months (+0.07)
  boosted  pd 23.1%  reasons: bureau score (+0.56); monthly wallet inflow (+0.21); wallet verification level (+0.07)
application 20: SAL, ₦73,000, the rule declined it: score_below_cutoff
  logistic pd 37.2%  reasons: bureau score (+1.21); delinquencies in 12 months (+0.16); years of credit history (+0.12)
  boosted  pd 24.0%  reasons: bureau score (+0.58); monthly wallet inflow (+0.21); enquiries in 90 days (+0.12)
application 226: SAL, ₦28,000, the rule declined it: recent_delinquency
  logistic pd  7.3%  reasons: delinquencies in 12 months (+0.16); product (+0.05); amount asked (+0.03)
  boosted  pd  9.8%  reasons: enquiries in 90 days (+0.09); product (+0.02); amount asked (+0.02)
application 1911: SAL, ₦72,000, the rule declined it: too_many_recent_enquiries
  logistic pd 19.7%  reasons: bureau score (+0.59); product (+0.05); monthly wallet inflow (+0.04)
  boosted  pd 24.0%  reasons: bureau score (+0.58); monthly wallet inflow (+0.21); enquiries in 90 days (+0.12)
application 7: SAL, ₦23,000, the rule declined it: insufficient_income_evidence
  logistic pd 13.3%  reasons: wallet verification level (+0.18); years of credit history (+0.17); product (+0.05)
  boosted  pd 11.3%  reasons: monthly wallet inflow (+0.11); enquiries in 90 days (+0.09); wallet verification level (+0.08)

largest gap between base + attributions and the model's own log-odds: 1.6e-15

The last line is the additivity check: base plus attributions equals the model’s own log-odds to within rounding. Applications 12, 20 and 1911 name the bureau score first in both models. Applications 226 and 7 have predicted risks below the 13.3% average in both models, so what the models list there are small positive numbers and not reasons for a decline. Application 1911 was declined by the rule for enquiries, and neither model puts enquiries first. Applications 20 and 1911 get exactly the same boosted prediction (24.0%) and the same three reasons: a constrained boosted model is a step function, so two applicants who fall on the same step of every tree receive identical outputs even though their scores (516 and 602) differ.

6. Check that the explanations hold. Save this as gbm_checks.py. It finds the model’s own decline line (the riskiest fifth of the finished loans), the smallest score rise that would turn each decline round, and how often the top reason survives 20 refits on resampled loans.

import numpy as np
from gbm_data import load, FEATURES, cols
from gbm_models import Logistic, Boosted
from gbm_explain import GROUPS, shapley, reasons

X, y, applied, meta = load()
train = y >= 0                                   # every finished loan, as in gbm_reasons.py
ids = np.array([m["id"] for m in meta])
FIVE = [12, 20, 226, 1911, 7]
rows = {a: int(np.where(ids == a)[0][0]) for a in FIVE}
bg = X[train][np.random.default_rng(0).choice(train.sum(), 100, replace=False)]
S = FEATURES.index("score")
models = {"logistic": Logistic().fit(X[train], y[train]),
          "boosted": Boosted(monotone=True).fit(X[train], y[train])}

print("1. Would the model decline, and what score would turn it round?")
print("   (the model declines the riskiest fifth of the loans it was trained on)")
for name, model in models.items():
    cut = np.percentile(model.prob(X[train]), 80)
    print(f"  {name}: decline at pd {cut:.1%} or more")
    for a, i in rows.items():
        p0 = model.prob(X[i:i + 1])[0]
        if p0 < cut:
            print(f"    application {a}: pd {p0:5.1%}  the model would approve")
            continue
        need = next((s for s in range(int(X[i, S]) + 1, 851)
                     if model.prob(np.where(np.arange(X.shape[1]) == S, s, X[i])[None, :])[0] < cut), None)
        print(f"    application {a}: pd {p0:5.1%}  declined; score {X[i, S]:.0f} would need to reach {need} "
              f"(+{need - X[i, S]:.0f})")

print("\n2. Does the top reason survive a refit? 20 refits, each on a resample of the finished loans")
tops = {}
for name in models:
    tops[name] = {a: [] for a in FIVE}
for b in range(20):
    pick = np.random.default_rng(100 + b).choice(np.where(train)[0], train.sum())
    refit = {"logistic": Logistic().fit(X[pick], y[pick]), "boosted": Boosted(monotone=True, seed=b).fit(X[pick], y[pick])}
    for name, model in refit.items():
        for a, i in rows.items():
            _, phi = shapley(model.logit, X[i], bg)
            tops[name][a].append(max(phi, key=phi.get))
for name, model in models.items():
    print(f"  {name}")
    for a, i in rows.items():
        _, phi = shapley(model.logit, X[i], bg)
        main = max(phi, key=phi.get)
        same = sum(t == main for t in tops[name][a])
        print(f"    application {a}: top reason '{main}' in the full model; the same in {same} of 20 refits")
.venv/bin/python gbm_checks.py
1. Would the model decline, and what score would turn it round?
   (the model declines the riskiest fifth of the loans it was trained on)
  logistic: decline at pd 18.5% or more
    application 12: pd 29.6%  declined; score 555 would need to reach 643 (+88)
    application 20: pd 37.2%  declined; score 516 would need to reach 652 (+136)
    application 226: pd  7.3%  the model would approve
    application 1911: pd 19.7%  declined; score 602 would need to reach 614 (+12)
    application 7: pd 13.3%  the model would approve
  boosted: decline at pd 18.2% or more
    application 12: pd 23.1%  declined; score 555 would need to reach 691 (+136)
    application 20: pd 24.0%  declined; score 516 would need to reach 691 (+175)
    application 226: pd  9.8%  the model would approve
    application 1911: pd 24.0%  declined; score 602 would need to reach 691 (+89)
    application 7: pd 11.3%  the model would approve

2. Does the top reason survive a refit? 20 refits, each on a resample of the finished loans
  logistic
    application 12: top reason 'bureau score' in the full model; the same in 20 of 20 refits
    application 20: top reason 'bureau score' in the full model; the same in 20 of 20 refits
    application 226: top reason 'delinquencies in 12 months' in the full model; the same in 12 of 20 refits
    application 1911: top reason 'bureau score' in the full model; the same in 19 of 20 refits
    application 7: top reason 'wallet verification level' in the full model; the same in 6 of 20 refits
  boosted
    application 12: top reason 'bureau score' in the full model; the same in 19 of 20 refits
    application 20: top reason 'bureau score' in the full model; the same in 19 of 20 refits
    application 226: top reason 'enquiries in 90 days' in the full model; the same in 9 of 20 refits
    application 1911: top reason 'bureau score' in the full model; the same in 19 of 20 refits
    application 7: top reason 'monthly wallet inflow' in the full model; the same in 10 of 20 refits

For application 12 (score 555) the logistic regression says 643, +88 points, and the boosted model says 691, +136: the same customer, two instructions. For the declines the models actually make (12, 20, 1911), the top reason holds in 19 or 20 of 20 refits in every case. For applications 226 and 7, which the models would approve, it holds in 6 to 12 of 20. A reason that changes with the refit is not a reason.

7. Word a decline, and check the wording. Save this as gbm_wording.py. Before it generates any reason it runs a sign check: it steps each feature to its safer value for every finished loan, as in step 3, and refuses to issue customer reasons from a model whose predicted risk goes up on any of them, because a reason such as “raise your score” would then be advice the model contradicts. It tries the logistic regression first, then the constrained boosted model, and builds the facts for application 12 from the first that passes. If neither passed, it would stop and issue nothing. Use any first name for the customer: here, Idongesit.

import json
import sys
import numpy as np
from gbm_data import load, FEATURES
from gbm_models import Logistic, Boosted
from gbm_explain import shapley, reasons

APP = 12
name = sys.argv[1] if len(sys.argv) > 1 else "the customer"
X, y, applied, meta = load()
train = y >= 0

# The safer step for each feature, as in step 3. A model may give customers reasons only if
# no finished loan's predicted risk goes UP when one of its features moves the safer way.
STEPS = {"score": 10, "kyc_tier": 1, "log_monthly_inflow": 0.1, "history_years": 1,
         "delinquent_12m": -1, "enquiries_90d": -1}


def wrong_way(model):
    bad = {}
    for f, step in STEPS.items():
        k = FEATURES.index(f)
        a = X[train & ~np.isnan(X[:, k])]
        b = a.copy()
        b[:, k] += step
        up = int(((model.logit(b) - model.logit(a)) > 1e-12).sum())
        if up:
            bad[f] = (up, len(a))
    return bad


candidates = [("logistic regression", Logistic().fit(X[train], y[train])),
              ("constrained boosted model", Boosted(monotone=True).fit(X[train], y[train]))]
chosen = None
for label, model in candidates:
    bad = wrong_way(model)
    if bad:
        print(f"SIGN CHECK FAILED for the {label}: " + "; ".join(
            f"{f} moves the risk the wrong way on {up:,} of {n:,} finished loans" for f, (up, n) in bad.items()))
        print(f"  REFUSED: no reasons are issued from the {label}. A customer told to improve "
              "a feature would be shown a model that rewards the opposite.")
        continue
    print(f"sign check passed for the {label}: no feature moves the risk the wrong way on any finished loan")
    chosen = (label, model)
    break
if chosen is None:
    sys.exit("No model passes the sign check, so no reasons may be issued. Fix the signs first "
             "(bin the features, or add monotonic constraints) and run this again.")

label, model = chosen
bg = X[train][np.random.default_rng(0).choice(train.sum(), 100, replace=False)]
i = [m["id"] for m in meta].index(APP)
_, phi = shapley(model.logit, X[i], bg)
top = [k for k, _ in reasons(phi)]
facts = {"name": name, "product": meta[i]["product"], "amount_kobo": meta[i]["requested_kobo"],
         "score": int(X[i, FEATURES.index("score")]), "reasons": top}
json.dump(facts, open("facts.json", "w"), ensure_ascii=False)
naira = f"₦{facts['amount_kobo'] // 100:,}"             # whole naira, integer arithmetic
text = (f"Customer: {name}. Product: salary advance. Amount asked: {naira}. Decision: declined. "
        f"Bureau score: {facts['score']}. The model's main reasons, in order: " + "; ".join(top) + ".")
print(f"\nreasons come from the {label}\n")
print(text)
print("\nPROMPT TO PASTE INTO AN ASSISTANT:")
print("Write a short, kind message in plain English telling this customer why their application was "
      "declined. Use only these facts. Do not add reasons, figures or advice that are not listed.\n" + text)
.venv/bin/python gbm_wording.py Idongesit
SIGN CHECK FAILED for the logistic regression: history_years moves the risk the wrong way on 2,575 of 2,575 finished loans
  REFUSED: no reasons are issued from the logistic regression. A customer told to improve a feature would be shown a model that rewards the opposite.
sign check passed for the constrained boosted model: no feature moves the risk the wrong way on any finished loan

reasons come from the constrained boosted model

Customer: Idongesit. Product: salary advance. Amount asked: ₦39,000. Decision: declined. Bureau score: 555. The model's main reasons, in order: bureau score; monthly wallet inflow; wallet verification level.

PROMPT TO PASTE INTO AN ASSISTANT:
Write a short, kind message in plain English telling this customer why their application was declined. Use only these facts. Do not add reasons, figures or advice that are not listed.
Customer: Idongesit. Product: salary advance. Amount asked: ₦39,000. Decision: declined. Bureau score: 555. The model's main reasons, in order: bureau score; monthly wallet inflow; wallet verification level.

The logistic regression fails here for a reason that differs from step 3. This script refits on every finished loan, and on that sample the wrong sign is on years of credit history (more history, higher predicted risk, on all 2,575 loans), not on inflow or enquiries. Which coefficient flips depends on the sample, which is the reason to run the check on the exact model that will speak to customers and not to trust an earlier run. The reasons then come from the constrained boosted model, which passes because the constraint forbids a wrong step. Application 12 is one it declines itself (predicted risk 23.1% against its decline line of 18.2% in step 6), so reasons are due. Its reasons are not the logistic regression’s: the logistic list named delinquencies in 12 months third, where the boosted list names monthly wallet inflow second. If you do not want to rely on constraints, the other route is to fix the logistic regression’s signs (bin the features, as the credit scoring chapter does, or constrain the coefficients) and run the check again. Until a model passes, no reasons may be issued from it. The script also saves facts.json, which the checker reads.

Paste the prompt into a free assistant, save its reply as reply.txt and check it. Your reply will differ from anyone else’s. Save this as gbm_check_reply.py. It converts money written the Nigerian ways (₦39,000, N39,000, NGN 39,000, ₦39k, 39k) to integer kobo with Decimal, and compares amounts, other numbers, months and reasons with the facts.

import json
import re
import sys
from decimal import Decimal

facts = json.load(open("facts.json", encoding="utf-8"))
reply = open(sys.argv[1], encoding="utf-8").read()
problems = []

# Money written the Nigerian ways: ₦39,000  N39,000  NGN 39,000  ₦39k  39k. Converted with Decimal to integer kobo.
MONEY = re.compile(r"(?:(?:₦|NGN|N)\s?)(\d[\d,]*(?:\.\d+)?)(\s?k\b)?|\b(\d+(?:\.\d+)?)(k)\b", re.I)
for m in MONEY.finditer(reply):
    digits = m.group(1) or m.group(3)
    thousand = m.group(2) or m.group(4)
    kobo = int(Decimal(digits.replace(",", "")) * (1000 if thousand else 1) * 100)
    ok = kobo == facts["amount_kobo"]
    print(f"money {m.group(0)!r:10} -> {kobo:>9} kobo  {'ok' if ok else 'NOT THE AMOUNT IN THE FACTS'}")
    if not ok:
        problems.append(m.group(0))

rest = MONEY.sub(" ", reply)
for n in sorted(set(re.findall(r"\b\d{2,}\b", rest))):
    if n != str(facts["score"]):
        print(f"number {n}: NOT IN THE FACTS")
        problems.append(n)

for month in re.findall(r"\b(?:January|February|March|April|May|June|July|August|September|October|November|December)\b", reply):
    print(f"date {month}: NOT IN THE FACTS")
    problems.append(month)

# Every reason the lab can produce has words that give it away. A reply may use only this applicant's.
WORDS = {"bureau score": ["score"], "wallet verification level": ["verification", "verified"],
         "monthly wallet inflow": ["inflow", "income", "deposit"], "years of credit history": ["history"],
         "delinquencies in 12 months": ["delinquen", "missed", "late payment", "overdue"],
         "enquiries in 90 days": ["enquir", "inquir"], "merchant account": ["merchant"],
         "product": ["product"], "amount asked": ["amount"]}
low = reply.lower()
for reason, words in WORDS.items():
    if reason not in facts["reasons"] and any(w in low for w in words):
        print(f"mentions a reason that is not in the list: {reason!r}")
        problems.append(reason)
for reason in facts["reasons"]:
    if not any(w in low for w in WORDS[reason]):
        print(f"leaves out a listed reason: {reason!r}")
if facts["name"] != "the customer" and facts["name"] not in reply:
    print(f"the name {facts['name']!r} is not in the reply as given")
    problems.append("name")
print("PASS" if not problems else f"CHECK {len(problems)} problem(s)")

To see both outcomes without an assistant, save these two replies that we wrote to show the checker (they did not come from an assistant). reply_good.txt:

Hello Idongesit, we could not approve your ₦39,000 salary advance this time. Your bureau score of 555 weighed most, and your monthly wallet inflow and wallet verification level also counted.

reply_bad.txt:

Hello Idongesit, we could not approve your N3,900 salary advance. Your score of 555 was low, you missed a payment in March, and your income is too small. Try again with 15k less.
.venv/bin/python gbm_check_reply.py reply_good.txt
.venv/bin/python gbm_check_reply.py reply_bad.txt
.venv/bin/python gbm_check_reply.py reply.txt
money '₦39,000'  ->   3900000 kobo  ok
PASS
---
money 'N3,900'   ->    390000 kobo  NOT THE AMOUNT IN THE FACTS
money '15k'      ->   1500000 kobo  NOT THE AMOUNT IN THE FACTS
date March: NOT IN THE FACTS
mentions a reason that is not in the list: 'delinquencies in 12 months'
leaves out a listed reason: 'wallet verification level'
CHECK 4 problem(s)

The second reply turns ₦39,000 into N3,900 (a tenth of the amount), adds a “15k” that is in no fact, invents March, mentions a missed payment although delinquencies are not among the reasons, and leaves out a listed reason (the wallet verification level). The checker cannot judge tone, or whether the advice is kind. A person reads every message. The third command prints what it finds in your own assistant’s reply.

Edit gbm_data.py: replace the whole MODEL = [...] list with MODEL = FEATURES, so both models use all 22 features, and run gbm_compare.py again. The first lines become:

train 465 loans, 59 bad (12.7%) | test 2110 loans, 284 bad (13.5%)

model              train AUC  test AUC  test KS
logistic               0.741     0.586    0.146
boosted                0.865     0.576    0.155
boosted, overfit       1.000     0.556    0.107

The logistic regression’s test AUC moves from 0.599 to 0.586, the boosted model’s from 0.579 to 0.576, and the overfit model’s from 0.542 to 0.556, while the logistic regression’s training AUC rises from 0.717 to 0.741. More columns made the fit to the 59 bad loans better and the test no better. Do not run gbm_reasons.py with the longer list: its nine groups cover the first eleven features only. Then change the customer name in step 7 to Oritsejafor and watch whether an assistant keeps it spelt as given.

ARTEFACT Write the decline reason-code specification ~50 MIN
YOU PRODUCEA decline reason-code specification

Template

# Decline reason-code specification: <lender>, <product>, version <n>
Written by <analyst or data scientist>. Signed by <head of credit risk>. Wording read by <compliance or counsel>.

## 1. Which declines get reasons
- Model and rule agree: predicted risk at or above the decline line of <pd>, and the model's top reason is the rule's recorded reason. Reasons come from <model, version>.
- Rule declined, model disagrees (a different top reason): the customer is given the rule's own reason; a person reviews.
- Model would have approved: no model reasons; the rule's reason is given and a person looks.

## 2. Reason codes
| Code | Model group | Sentence shown to the customer | Direction (what would help) |
Reason list owned by <role>. Only <role> may add, change or switch off a code.

## 3. The customer notice
Fixed wording: <template>. It says a model took part, how to ask a person to look again, and gives the top <n> reasons in order. It promises no approval.

## 4. What the customer can do next
<ask for a human review; a change they can make themselves; what we will not say, and why>

## 5. Tests for accuracy
| Test | How it is run | Passes when | Run by, how often |
(additivity, stability over refits, sign check, wording check, a person's read)

## 6. How this could be wrong
<one way, and what would show it>

## 7. Decision and sign-off
Decision needed: <what, from whom, by when>. Out of scope: <what this does not cover>.
Written <name, date>. Approved <name, date>.
WORKED EXAMPLE

At Owoleaf, Oritsejafor, the data scientist, writes this document and Idongesit, who runs credit risk, signs it. This is version 1 for salary advances, written 2026-11-20.

Which declines get reasons. The constrained boosted model declines at a predicted risk of 18.2% or more. Model reasons go only where the rule and the model agree on the main reason. Application 12 (₦39,000, score 555) is at 23.1% and both name the score, so it gets reasons. Application 226 is at 9.8%, below the line: the customer is given the rule’s reason, recent delinquency, and a person looks. Application 1911 is at 24.0%, but the rule cited enquiries and the model’s top reason is the bureau score, so the customer gets the rule’s reason and a person reviews the mismatch.

Codes. BUREAU: ‘Your credit bureau score was lower than we need.’ INFLOW: ‘The money you paid into your wallet over the last 90 days was lower than we need.’ VERIFY: ‘Your wallet is not yet verified to a higher level.’ Idongesit owns the list; only the head of credit risk may switch a code off.

Notice and next step. A model took part. You may ask a person to look again. No target score is quoted: for application 12 the logistic regression says 643 (+88) and the boosted model 691 (+136), so any number would belong to one model.

Tests. Attributions add up to the model’s output (largest gap 1.6e-15). The top reason holds in at least 19 of 20 refits (19, 19 and 19 for applications 12, 20 and 1911). The sign check passes (the logistic regression fails it on history_years, on 2,575 of 2,575 loans, so it issues no reasons). Every notice is run through gbm_check_reply.py, then read by a person.

Could be wrong. The model never saw scores below 561, so a reason for a low-score applicant rests on a repeated last answer. A reason that moves between refits would show it.

Decision. Approve the three codes for a pilot, by 2026-12-04 (an assumed date). Out of scope: pricing, and the legal view of section 37.

Now you

You work for an unnamed 30-person digital lender in Abuja that runs the same constrained boosted model on salary advances, with a decline line of 18.2%. Its analyst ran this lab and printed the lines in steps 5 and 6. Four declined applications are in front of you: 20 (₦73,000, score 516, rule: score below the cut-off, model risk 24.0%, reasons bureau score, monthly wallet inflow, enquiries in 90 days, top reason held in 19 of 20 refits), 226 (rule: recent delinquency, model risk 9.8%, top reason held in 9 of 20 refits), 1911 (₦72,000, rule: too many enquiries, model risk 24.0%, top reason bureau score in 19 of 20 refits) and 7 (₦23,000, rule: insufficient income evidence, model risk 11.3%, top reason in 10 of 20 refits). Write the specification: which of the four get model reasons, the notice, what each customer can do next and how reasons are tested. The head of credit reads it and signs, and the decision it supports is whether the notice may go live in a pilot.

Self-check

DECIDE

Owoleaf at 200 people. Oritsejafor's boosted model has a training AUC of 0.82, a test AUC of 0.58 on loans from April to June, and a logistic baseline at 0.60. The model is constrained and can list reasons. Idongesit must decide what it does next. The salary-advance book has far more applicants than the 59 bad training loans suggest, the product team wants a decision this month, and a declined customer may ask why.

READING
  1. DOC
    HistGradientBoostingClassifier

    The estimator the lab uses. Read the parameters on tree depth, leaf size, regularisation, missing values and monotonic_cst (the constraint is on the probability of the positive class); skip the early-stopping options.

  2. DOC
    Nigeria Data Protection Act 2023 Federal Republic of Nigeria (copy via NgCERT), 2023

    A copy of the Act hosted by Nigeria's national CERT. Read section 37 on automated decision-making and compare it with the gazetted text before you cite a subsection; skip the commission's administration.

  3. DOC
    FCCPC Digital, Electronic, Online, or Non-Traditional Consumer Lending Regulations 2025

    The Commission's published Regulations. This chapter could not open it, so read it yourself: registration, disclosure, data use and complaints. Check whether anything touches automated decisions.

  4. DOC
    CFPB Circular 2022-03: adverse action notification requirements and complex algorithms

    A United States interpretation, not Nigerian law. It shows how a regulator can insist on specific reasons from a complex model. Read the short summary and the example; skip the US statutes.

  5. PAPER
    Counterfactual Explanations without Opening the Black Box: Automated Decisions and the GDPR Sandra Wachter, Brent Mittelstadt and Chris Russell, 2017

    The case for explaining a decision by the smallest change that would have flipped it. Read the loan example, then ask what a customer could actually change; skip the GDPR legal analysis unless you work on it. Read: Sections 1 to 3.

  6. PAPER
    A Unified Approach to Interpreting Model Predictions Scott Lundberg and Su-In Lee, 2017

    The paper behind SHAP: attributions that add up to the model's output. Read the introduction and the properties it asks of an attribution; skip the proofs and the neural-network variant. Read: Sections 1 and 2.

  7. BOOK
    Interpretable Machine Learning Christoph Molnar

    A readable account of the attribution methods the lab uses, including what they cannot tell you. Chapter numbers differ between editions, so find them by title. Read: Chapters on Shapley values and counterfactual explanations.

All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: Project: build and validate a scorecard on the loan book →