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
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
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?
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?
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.
- 1Missed-default cost = 2 × $20,000 = $40,000.
- 2Unnecessary-review cost = 12 × $200 = $2,400.
- 3Total modeled error cost = $40,000 + $2,400 = $42,400.
- 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.
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
)Step 2: Prepare a leakage-safe model
The pipeline learns numeric scaling and category columns only from the training applications.
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.
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.
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
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?
12. Failure Analysis
Failure mode → diagnosis → response
13. Improve the Project
14. Production Considerations
What changes beyond the notebook
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.