Build and Compare Credit Risk Models: Logistic vs Tree Ensemble
Machine LearningModel answerLast updated
Develop both a linear baseline and a tree-based classifier for predicting loan defaults, covering feature engineering, validation, calibration, and deployment.
Context
You're developing a binary classifier to identify accounts likely to stop payment within 90 days (default = 1 vs current = 0). Your training set has 500,000 records with roughly 2% positive examples—a significant class imbalance.
Available signals:
- Numeric fields: income-to-debt ratio, credit line usage percentage, account holder age, minimum payment coverage (contains nulls, heavy tails, some extreme values)
- Categorical with many levels: transaction category codes, geographic region
- Ordered categories: risk grade from
A(lowest risk) toG(highest risk)
Your Assignment
Part 1: Feature Preparation and Pipeline Design
Outline the transformations required for a linear model versus a tree-based ensemble. Show how to organize these steps in a scikit-learn pipeline so that fitting, imputation, and encoding happen only on training data during cross-validation.
Part 2: Capturing Complex Patterns
- Explain what a linear model requires to represent curved relationships and variable combinations (such as polynomial expansions, binning, or interaction features).
- Describe how ensemble methods built from decision trees naturally discover these patterns without manual feature construction.
Part 3: Evaluation Setup and Imbalance Handling
- Propose a cross-validation scheme appropriate for time-ordered financial records and heavily skewed classes.
- Compare techniques for addressing imbalance (e.g., class weighting, undersampling, synthetic oversampling) and their effect on probability estimates.
Part 4: Probability Calibration and Decision Boundaries
- Explain why tree ensemble scores often cluster away from 0 and 1, while linear models trained with log-loss tend to be well-calibrated.
- Given a business scenario where missing a default costs $5,000 in unrecovered funds and incorrectly blocking a good account costs $150 in lost revenue, derive the classification threshold that minimizes expected cost (instead of using 0.5).
Part 5: Deployment and Compliance
Compare the two modeling approaches across these operational concerns:
- Response time requirements (99th percentile under 15 milliseconds)
- Explainability obligations under consumer credit regulations
- Model refresh frequency and monitoring for distribution shift
Hints
Hint 1
Fit all transformers inside a pipeline to avoid leaking information from validation folds into training.
Hint 2
Tree ensembles learn interactions automatically through sequential splits; linear models need explicit feature crosses.
Hint 3
Use time-based splits with a gap to prevent label leakage; handle imbalance through reweighting or threshold tuning rather than synthetic data.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Logistic Regression vs Random Forest for Default Prediction
This problem assesses your ability to move a classifier from notebook to production, balancing statistical performance, interpretability, and operational constraints. Strong answers connect preprocessing choices to their downstream effects on probability quality and business decisions.
1. Feature Preparation and Pipeline Design
| Transformation | Linear Model (Logistic Regression) | Tree Ensemble (Random Forest) |
|---|---|---|
| Missing values | Impute with median; add binary indicator columns since missingness often signals risk | Impute or leverage native missing-value handling (scikit-learn ≥1.4); include indicator |
| Skewness and outliers | Cap extreme values at 1st/99th percentiles, then apply log transform to right-skewed ratios | Skip—splits are invariant to monotonic rescaling |
| Feature scaling | Standardize so that regularization penalties apply uniformly across coefficients | Not needed |
| High-cardinality categoricals | Target encode with internal cross-validation, or one-hot the most frequent categories plus an "other" bucket | Use ordinal or target encoding; avoid full one-hot expansion which dilutes splits |
| Ordinal categories | Map A–G to 1–7, or use weight-of-evidence if the risk relationship isn't monotonic | Map to integers 1–7 |
Preventing data leakage: Wrap every fitted transformation in a single Pipeline. When you call cross_validate, scikit-learn refits imputers, scalers, and encoders on each training fold independently. Target encoding is especially dangerous because it depends on y; use TargetEncoder which cross-fits internally. If applying SMOTE, place it inside an imblearn.pipeline.Pipeline so synthetic samples touch only the training side of each split.
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, FunctionTransformer, TargetEncoder, OrdinalEncoder
from sklearn.linear_model import LogisticRegression
import numpy as np
numeric_cols = ["income_debt_ratio", "credit_usage_pct", "age", "min_payment_coverage"]
preprocessor_lr = ColumnTransformer([
("numeric", Pipeline([
("impute", SimpleImputer(strategy="median", add_indicator=True)),
("log", FunctionTransformer(np.log1p)), # assumes prior clipping
("scale", StandardScaler())
]), numeric_cols),
("high_card", TargetEncoder(), ["txn_category", "region"]),
("ordinal", OrdinalEncoder(categories=[list("ABCDEFG")]), ["risk_grade"])
])
model_lr = Pipeline([
("prep", preprocessor_lr),
("classifier", LogisticRegression(penalty="l2", C=0.1, max_iter=2000, solver="lbfgs"))
])
For Random Forest, remove the log transform and scaler from the numeric branch.
2. Capturing Complex Patterns
Logistic Regression models the log-odds as a linear combination: log(p/(1−p)) = β₀ + Σβᵢxᵢ. Anything beyond straight lines requires explicit engineering:
- Splines or binning to capture non-linear effects (e.g., risk accelerates sharply when credit usage exceeds 80%)
- Weight-of-evidence transformation: bin each variable and replace bin membership with
log(fraction_good / fraction_bad). This linearizes the relationship with log-odds, handles nulls as a separate bin, and produces the classic monotonic scorecard. - Interaction terms like
usage × gradeorincome_debt_ratio × payment_coverage, selected from domain expertise. Avoid blind polynomial expansion—it creates too many features and harms interpretability.
Random Forest discovers these structures automatically. Each split conditions on prior splits, so a path like grade ≥ E → usage > 0.8 → payment_coverage < 1 represents a three-way interaction. Piecewise-constant leaf predictions approximate any smooth function. Averaging many decorrelated trees (via bootstrap sampling and random feature subsets) smooths the step functions into flexible decision boundaries.
3. Evaluation Setup and Imbalance Handling
Cross-validation scheme:
- Use time-based splits, not random folds. Train on earlier months and validate on later months using expanding or rolling windows.
- Insert a temporal gap (e.g., 90 days) between train and validation so no training label uses information from the validation period.
- Reserve a final out-of-time holdout from the most recent months, untouched until final evaluation.
- Ensure accounts don't appear in both train and validation within a fold (group by customer ID).
- With 10,000 defaults (2% of 500k), each fold has sufficient positive examples. Report event rate per fold.
Metrics:
- Ranking: PR-AUC, ROC-AUC (or Gini), Kolmogorov-Smirnov statistic
- Calibration: Brier score, log-loss, reliability diagram
Imbalance strategies and their impact on probabilities:
class_weight='balanced'applies a weight of ~49:1 to defaults. For logistic regression, this mainly shifts the intercept bylog(49), inflating all probabilities. Ranking stays similar. Correct afterwards:logit(p_adj) = logit(p_raw) − log(w₁/w₀).- Undersampling negatives at rate β has a similar effect. Correct with
p_corrected = β·p_sample / (β·p_sample + 1 − p_sample). - SMOTE interpolates synthetic points between minority neighbors. With mixed numeric and categorical credit features, this generates implausible records and severely distorts calibration. Rarely justified in this domain.
- Recommended: Train on natural class distribution or reweight and then correct. Address imbalance through threshold tuning rather than distorting the probability estimates.
4. Probability Calibration and Decision Boundaries
Why Random Forest scores are miscalibrated: The predicted probability is the average fraction of positive training examples across terminal leaves. To output extreme values (near 0 or 1), nearly all trees must agree. Bootstrap resampling and feature subsampling introduce variance that prevents unanimity, pulling predictions toward the middle. Additionally, RF optimizes Gini impurity locally per split, not a global proper scoring rule.
Why Logistic Regression is closer to calibrated: It minimizes log-loss, a proper scoring rule. At the optimum, predicted probabilities match observed rates both globally and conditionally on each feature. Calibration holds if the model specification is reasonable, though heavy regularization can shrink probabilities slightly.
Fixing Random Forest calibration: Apply CalibratedClassifierCV on a held-out time slice:
- Isotonic regression works well with 10k+ positives
- Platt scaling (logistic calibration) is more stable for smaller samples
Optimal threshold: Assuming zero cost for correct predictions, flag an account when the expected cost of inaction exceeds the cost of action:
p · Cost_FN > (1 − p) · Cost_FP
p* = Cost_FP / (Cost_FP + Cost_FN) = 150 / 5150 ≈ 0.029
The optimal cutoff is approximately 2.9%, not 50%. At 0.5 you would miss nearly all defaults. This formula assumes calibrated probabilities.
Validate empirically on the out-of-time set by sweeping thresholds t and minimizing total expected cost:
Cost(t) = 5000 × 0.02 × [1 − Recall(t)] + 150 × 0.98 × FPR(t)
= 100[1 − Recall] + 147·FPR
Refinements to mention:
- The intervention (e.g., credit line reduction) typically prevents only partial loss. Use net expected savings.
- Operational capacity constraints (review team size, collection bandwidth) may force a higher threshold than the cost-optimal one.
5. Deployment and Compliance
| Consideration | Logistic Regression | Random Forest |
|---|---|---|
| Latency (p99 < 15ms) | Inner product of ~50 coefficients: sub-millisecond. Can embed directly in SQL or edge services. | 500 deep trees require large memory footprint. Single-row predict in sklearn has overhead. Use n_jobs=1, compile with TreeLite or ONNX, or switch to LightGBM with GPU inference for sub-10ms p99. |
| Explainability (FCRA/ECOA) | Coefficients are adverse-action reasons. "Credit usage 15 points above cutoff" is a legally sufficient explanation. | Global feature importance (Gini or permutation) shows aggregate trends but not per-decision reasons. SHAP values provide local explanations but add computational cost and require careful communication to satisfy regulators. |
| Retraining & drift monitoring | Retrain monthly or quarterly. Monitor coefficient sign flips, intercept drift, and population stability index (PSI) on features. | Retrain on same cadence. Monitor feature importance rankings, PSI, and prediction distribution shifts. Trees are more robust to moderate covariate drift but can overfit to short-term noise. |
| Model governance | Simpler to audit and document. Regulators and internal risk committees expect linear scorecards in consumer credit. | Requires more sophisticated model risk management documentation, especially around feature importance interpretation and local explainability methods. |
Recommendation: Start with Logistic Regression as a strong baseline. It's fast, interpretable, and well-understood by credit risk teams and regulators. Use Random Forest or gradient boosting if the performance lift justifies the operational complexity, and invest in calibration and explainability tooling (SHAP, LIME) to meet compliance requirements. In many production credit systems, a well-engineered linear model with domain-informed features outperforms a black-box ensemble on the combination of performance, latency, and regulatory acceptance.