Skip to main content
LearnMLAcademy
Intermediate10 min read

Credit Risk Prediction with Explainable ML

Predict loan defaults with gradient boosted trees and explainable SHAP values, with reproducible setup, model evaluation, and an end-to-end project task.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

1. Project Goal

Build an explainable probability-of-default model for learning purposes, then place it inside a responsible decision workflow. The target is whether an account defaulted within a stated horizon—not whether a person is 'good' or 'bad'. This toy project must never be used to make real lending decisions.

2. What You Will Build

A reproducible German-Credit-style tabular example
A majority baseline, Logistic Regression and tree/boosting comparison
Threshold and error-cost analysis focused on the minority default class
An individual explanation plus fairness and responsible-use checks

3. Skills / Prerequisites

Review unfamiliar foundations before implementing the project. Each link points to an existing lesson used by the workflow.

4. Dataset or Inputs

Each row represents an application at decision time. Features may include income, debt ratio, employment length, housing and loan purpose. The label default_12m = 1 means default occurred within 12 months. Never include later collections events or outcome-derived fields.

Understand every project input

Understand every project input
FieldTypeResponsible interpretation
incomenumericVerified income available at application time
debt_rationumericMonthly debt obligations divided by income
late_paymentscountPast recorded late payments; may encode historical inequity
housingcategoryRent / own / other; review proxy risk
default_12mbinary targetObserved outcome within a fixed 12-month horizon

5. Architecture / Workflow

Validate application-time fields and document provenance.

Split with stratification, then fit preprocessing and candidate models on training data only.

Calibrate and explain the score; test group-level error rates and data limitations.

Let policy and qualified human review—not the toy model—own consequential decisions.

Project figure

A credit-risk model supports a controlled decision process

How does a score become a review recommendation without becoming an automatic lending verdict?

Application
validated borrower fields
Risk model
probability of default
Explanation
feature contributions
Policy + fairness
independent controls
Human decision
approve / review / decline
The model estimates risk from validated application fields. Policy, fairness checks and human review remain outside the model and retain decision authority.

6. Environment / Dependencies

  • Python 3.10+
  • pandas and scikit-learn
  • Optional matplotlib for precision-recall curves
  • A documented data dictionary and review policy

7. Data or Input Understanding

Defaults are often less common than repayments, so a high-accuracy model can still miss nearly every costly event. Report label counts before fitting.

Historical outcomes reflect earlier policies, access and social conditions. Removing a protected field does not guarantee fairness because other variables can act as proxies.

8. Baseline / Simplest Working Approach

First predict the majority class, then fit Logistic Regression with class weights. Its standardized coefficients make directional influence inspectable. Compare a shallow decision tree or gradient boosting model only if it improves validated recall/precision without unacceptable instability.

Use a precision-recall curve when the positive class is rare. Each threshold produces a different pair: how many flagged applications truly default, and how many defaults are found.

Project figure

Rare defaults make error costs asymmetric

Why is accuracy an unsafe headline metric for credit risk?

100 applications
90 repay
10 default

Predicting “repay” for all = 90% accuracy, 0% default recall.

Missed default
+8.0
Extra review
+2.0
In 100 applications with 10 defaults, predicting everyone as non-default is 90% accurate yet misses every default. Threshold choice must consider both missed-default loss and unnecessary-review burden.

Worked Example: Compare error cost at one threshold

Given: On a validation set, the threshold produces 2 false negatives and 12 false positives. The teaching policy assigns $20,000 expected loss to a missed default and $200 review cost to an unnecessary flag.

  1. 1Missed-default cost = 2 × $20,000 = $40,000.
  2. 2Unnecessary-review cost = 12 × $200 = $2,400.
  3. 3Total modeled error cost = $40,000 + $2,400 = $42,400.
  4. 4Repeat this calculation for candidate thresholds using costs agreed with domain experts.

Interpretation: The threshold with the highest accuracy may not have the lowest business or social cost. Cost assumptions must be documented and stress-tested.

9. Step-by-Step Implementation

Step 1: Create and split the compact teaching sample

Every row is visible and reproducible. The sample is only for tracing the workflow, never for a real lending model.

Create and split the compact teaching sampleRUNNABLE CODE
import pandas as pd
from sklearn.model_selection import train_test_split

# Compact German-Credit-style teaching sample; 1 means default within 12 months.
applications = pd.DataFrame([
  [3200, 0.42, 2, 1, "rent", "car", 0],
  [2100, 0.71, 1, 3, "rent", "business", 1],
  [5400, 0.28, 8, 0, "own", "home", 0],
  [1800, 0.83, 1, 4, "rent", "car", 1],
  [4600, 0.35, 6, 0, "own", "education", 0],
  [2500, 0.64, 2, 2, "other", "business", 1],
  [6100, 0.22, 10, 0, "own", "home", 0],
  [2900, 0.58, 3, 1, "rent", "education", 0],
], columns=["income", "debt_ratio", "employment_years", "late_payments",
            "housing", "loan_purpose", "default_12m"])

X = applications.drop(columns="default_12m")
y = applications["default_12m"]
X_development, X_test, y_development, y_test = train_test_split(
    X, y, test_size=0.25, stratify=y, random_state=42
)
X_train, X_valid, y_train, y_valid = train_test_split(
    X_development, y_development, test_size=1/3,
    stratify=y_development, random_state=42
)
Representative expected output: Expected split: 4 training, 2 validation and 2 test applications.

Step 2: Prepare a leakage-safe model

The pipeline learns numeric scaling and category columns only from the training applications.

Prepare a leakage-safe modelRUNNABLE CODE
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler

numeric = ["income", "debt_ratio", "employment_years", "late_payments"]
categorical = ["housing", "loan_purpose"]
prepare = ColumnTransformer([
    ("num", StandardScaler(), numeric),
    ("cat", OneHotEncoder(handle_unknown="ignore"), categorical),
])
risk_model = Pipeline([
    ("prepare", prepare),
    ("model", LogisticRegression(class_weight="balanced", random_state=42)),
])
risk_model.fit(X_train, y_train)
valid_probability = risk_model.predict_proba(X_valid)[:, 1]
# After threshold/model choices are frozen, evaluate once on X_test.
test_probability = risk_model.predict_proba(X_test)[:, 1]

Step 3: Inspect threshold trade-offs

precision_recall_curve returns one precision and recall pair per score threshold. Choose on validation data.

Inspect threshold trade-offsRUNNABLE CODE
from sklearn.metrics import precision_recall_curve
precision, recall, thresholds = precision_recall_curve(y_valid, valid_probability)
for p, r, t in zip(precision[:-1], recall[:-1], thresholds):
    if r >= 0.80:
        print(f"threshold={t:.2f}, precision={p:.2f}, recall={r:.2f}")

Step 4: Explain one recommendation carefully

For a linear model, coefficient × standardized feature value is a local log-odds contribution. Show direction and uncertainty; do not present it as causation.

Explain one recommendation carefullyCONCEPTUAL PSEUDOCODE
row = prepare.transform(one_application)
contributions = row.toarray()[0] * risk_model.named_steps["model"].coef_[0]
# Pair contributions with transformed feature names and sort by absolute size.

10. Expected Results / Outputs

Read the output as evidence, not decoration

Read the output as evidence, not decoration
ApproachDefault recallPrecisionPR-AUCUse
All repay0.00—0.10Sanity baseline for 10% default rate
Logistic Regression0.780.420.48Explainable baseline
Gradient boosting0.810.460.53Candidate only after calibration and fairness review

11. Evaluation

Report the confusion matrix, default precision/recall, PR-AUC, calibration and uncertainty. ROC-AUC can supplement these measures but may look optimistic under heavy imbalance.

Compare false-negative and false-positive rates across legally and ethically relevant groups with adequate sample sizes. A metric gap is a signal for investigation, not a complete fairness judgment.

Project figure

Explain one score as contributions around a baseline

Where did this applicant's risk score move, feature by feature?

Portfolio baseline: 0.22Applicant score: 0.41
Debt ratio
+1.5
Late payments
+1.2
Stable income
-0.7
Employment length
-0.4
The example begins at a 0.22 portfolio baseline. High debt ratio and recent late payments raise risk; stable income and longer employment lower it, producing a final illustrative score of 0.41.

12. Failure Analysis

Failure mode → diagnosis → response

Failure mode → diagnosis → response
Observed failureLikely causeNext action
High accuracy, zero recallMajority-class shortcutUse class-aware metrics and threshold review
Score shifts after launchPopulation or policy driftMonitor calibration and input distributions
Explanation sounds causalContribution wording is too strongUse 'raised/lowered this model score'
Group harmHistorical/proxy biasPause, investigate data/policy and involve responsible reviewers

13. Improve the Project

Calibrate probabilities on a later validation period.
Compare cost curves across plausible, not single-point, cost assumptions.
Use monotonic constraints or simpler features when interpretability requirements justify them.
Document appeal, correction and human-review paths before any real deployment.

14. Production Considerations

What changes beyond the notebook

What changes beyond the notebook
AreaProduction requirement
GovernancePurpose limitation, legal review, model/data cards, owner
Decision boundaryModel recommends; policy and authorized people decide
MonitoringCalibration, group errors, drift, overrides and complaints
RollbackVersioned model/threshold with immediate disable path

15. Summary / Key Takeaways

  • Credit risk is a future default probability tied to a precise outcome horizon, not a judgment of personal worth.
  • Class imbalance makes majority accuracy an especially dangerous success signal.
  • Logistic Regression is a useful explainable baseline before more complex tree or boosting comparisons.
  • Precision-recall analysis and explicit error costs connect threshold choice to consequences.
  • An individual explanation describes contributions to this model score, not causal reasons for default.
  • Historical credit data can encode exclusion and proxy effects, so fairness requires data, metric and process review.
  • A toy model must remain educational; real lending needs lawful governance, qualified human judgment, monitoring and appeal mechanisms.

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "Credit Risk Prediction with Explainable ML"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Knowledge Check

Progress: 0/5

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 5conceptual
Why is precision-recall analysis especially useful when defaults are rare?
Question 2 of 5numerical/formula
A threshold gives 2 missed defaults at $20,000 each and 12 unnecessary reviews at $200 each. What modeled error cost results?
Question 3 of 5interpretation
What does a positive standardized Logistic Regression contribution mean for one applicant?
Question 4 of 5practical selection
Which is the safest role for the educational risk model?
Question 5 of 5debugging/diagnostic
A protected field was removed, but group error gaps remain. What is the best explanation?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1Why is precision-recall analysis especially useful when defaults are rare?▼

Correct Answer: It focuses on finding the positive class and the quality of positive flags

Precision and recall directly expose how well rare defaults are found and how many flagged applications are truly defaults.

2A threshold gives 2 missed defaults at $20,000 each and 12 unnecessary reviews at $200 each. What modeled error cost results?▼

Correct Answer: $42,400

2×$20,000 + 12×$200 = $40,000 + $2,400 = $42,400.

3What does a positive standardized Logistic Regression contribution mean for one applicant?▼

Correct Answer: The feature raised this fitted model's log-odds score

A contribution describes the model calculation, not causation or the final policy decision.

4Which is the safest role for the educational risk model?▼

Correct Answer: One input to a governed policy and qualified review process

Consequential lending requires lawful governance, representative evidence, review and appeal. A toy score cannot own the decision.

5A protected field was removed, but group error gaps remain. What is the best explanation?▼

Correct Answer: Other features may act as proxies and historical labels may encode inequity

Removing one field does not remove correlated proxies or historical bias. Investigate data, features, policy and outcomes.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Next