All projects

Machine Learning & MLOps

Credit Risk Scoring & Monitoring

Case study: A consumer lender

A lender has seconds to decide on a loan: the model estimates the risk that the applicant won't repay and shows what drove that score.

Try a loan application
Real model output
The model's risk score for three real test applications, against the 0.53 decision threshold.

The problem

Case study: a consumer lender serves people with little or no credit history. It needs a model that estimates, from an application, the chance that the person will not repay, and that turns this into a grant or refuse decision. The two possible mistakes do not cost the same. Lending to someone who defaults loses the capital; refusing someone who would have repaid only loses the interest margin. The brief puts the first mistake at 10 times the cost of the second.

The model is only half of the job. It also has to run as a service: an API, automated tests and deployment, and monitoring that raises a flag when the applications coming in stop looking like the ones the model learned from.

What the demo does

You fill in a short loan application with about ten sliders (amount, income, age, years in employment, external credit scores...) or start from a ready-made profile: safe, borderline or risky. The model behind it uses 795 features; the ones not shown are set to typical (median) values.

You get the estimated probability of default, the decision, and the factors that pushed the score up or down for this application.

A second slider moves the decision threshold. You see how many good customers get refused and how many defaults slip through, and what that costs the lender at the 10-to-1 ratio.

The production side shows the drift report in plain language: which input features have shifted compared with the training data.

Try a loan application

Results

0.785AUC on 61,502 test applications
Take one applicant who defaulted and one who repaid: 78.5% of the time, the model gives the defaulter the higher risk score. 0.5 would be a coin flip.
2 in 3Defaults caught (recall 0.67)
At the chosen threshold the model flags about two out of three applicants who will default. The price: only about 1 in 5 refused applicants would really have defaulted (precision 0.20).
147×Faster predictions with ONNX
Serving the model with ONNX Runtime instead of the original Python pipeline cut the prediction time from 12.7 ms to 0.09 ms, with the same scores.

The data is the public Home Credit Default Risk dataset from Kaggle: 307,507 anonymized applications, of which 8.1% defaulted. I kept 20% aside as a test set (61,502 applications) and tuned everything else with 5-fold cross validation.

On the test set, at the 0.53 threshold:

  • AUC 0.785: the model ranks risky applicants above safe ones far better than chance.
  • Recall 0.67: about two thirds of the defaults are caught.
  • Precision 0.20: about one refused applicant in five would really have defaulted. That is the trade-off a 10-to-1 cost ratio produces, since a missed default costs ten refusals.

The threshold was chosen by sweeping every value from 0.01 to 0.99 and keeping the one with the lowest business cost. At the 10-to-1 ratio it gains less than 1% over the default 0.5, because class weighting during training already corrects most of the imbalance. Its real value shows when the policy changes: with a 5-to-1 ratio the best threshold moves to 0.68, with 20-to-1 to 0.36. The lender can adapt in a second without retraining.

Limits:

  • A plain logistic regression reached 0.773 AUC against 0.785 for LightGBM. Most of the signal comes from the features, and a simpler model would be a reasonable choice where explanations matter more than the last point of AUC.
  • The 10-to-1 ratio is an assumption from the brief, not a measured figure.
  • The drift check was tested on simulated traffic. I sent a batch of applications with incomes cut by 40% and applicants made younger, to mimic a recession. The monitoring flagged exactly those two features (income and age) and left the 9 other monitored features alone.

How it's built

Architecture, stack and technical choices.
Architecture

Training

POST /predict

logged after the response

7 tables of applications and credit history

795 features

4 models, grid search on business cost

LightGBM + threshold 0.53

MLflow registry

ONNX export

FastAPI + ONNX Runtime

Client app

PostgreSQL

Streamlit dashboard: drift, latency, errors

GitHub Actions: tests, Docker build, deploy

Diagram as text
flowchart LR
    subgraph Training["Training"]
        A["7 tables of applications and credit history"] --> B["795 features"] --> C["4 models, grid search on business cost"] --> D["LightGBM + threshold 0.53"] --> E[("MLflow registry")]
    end
    E --> F["ONNX export"] --> G["FastAPI + ONNX Runtime"]
    U["Client app"] -->|"POST /predict"| G
    G -->|"logged after the response"| H[("PostgreSQL")]
    H --> I["Streamlit dashboard: drift, latency, errors"]
    J["GitHub Actions: tests, Docker build, deploy"] --> G

Stack

  • Python
  • pandas
  • scikit-learn
  • LightGBM
  • SHAP
  • MLflow
  • FastAPI
  • ONNX Runtime
  • PostgreSQL
  • Docker
  • GitHub Actions
  • Evidently
  • Streamlit
  • Pytest

Modeling:

  • Features: the main application table joined with credit bureau history, previous applications, card balances and instalment payments, aggregated per applicant. I adapted a well-known public Kaggle notebook for this step and added business ratios. The top feature is one of those ratios: the annuity divided by the loan amount.
  • Four model families compared (logistic regression, random forest, XGBoost, LightGBM), each with a grid search scored directly on the business cost, 48 combinations in total. All runs are tracked in MLflow, and the final model is registered with a production alias.
  • Imbalance handled with class weighting (scale_pos_weight ≈ 11.4), imputation done inside the scikit-learn pipeline so cross validation does not leak.
  • Explanations: global feature importance, plus SHAP values for individual applicants (a clear default, a clear repayer, a borderline case at exactly 0.53).

Production:

  • FastAPI exposes /predict and /health. Each prediction (inputs, score, latency) is stored in PostgreSQL for monitoring.
  • Profiling with cProfile showed that the database write took 45 ms of a 54 ms response. Moving it to a background task brought the response down to about 9 ms. Converting the model to ONNX then made inference 147 times faster with identical scores (differences below 1e-7), and halved the Docker image (1.11 GB to 479 MB) since mlflow, LightGBM, scikit-learn and pandas are no longer needed at runtime.
  • CI on GitHub Actions runs the Pytest suite with coverage, then builds the Docker image. CD redeploys on every push to main. The original deployment ran on Render (API, database and dashboard, described in render.yaml), with secrets kept in GitHub, never in the code.
  • Monitoring: a Streamlit dashboard compares production inputs with a sample of the training data (Kolmogorov-Smirnov test per feature, through Evidently) and tracks call volume, error rate and latency (mean and 95th percentile).

Next steps

  • Drop the applicant's gender from the features. The model uses it (it ranks among the 15 most important features), and a real lender should not make credit decisions on that basis. I would remove it and check that results stay similar across groups.
  • Calibrate the scores. Class weighting pushes them up, so a score of 0.53 does not mean a 53% chance of default. Calibrated probabilities are easier to explain to a credit officer and to the applicant.
  • Get the cost ratio from real figures (average loss on a default, margin on a good loan) instead of a fixed 10-to-1.
  • Monitor the outcome as well as the inputs. Input drift is a proxy; the real test is whether actual defaults, which arrive months later, match the predicted risk. I would also set alert thresholds and a retraining rule rather than only a dashboard.

Code and notebooks

Portfolio assistant AI

Answers are written by an AI from the content of this site. They can be wrong: check the sources it links. Questions are kept 90 days to improve the assistant, without your IP address. How it works