Handle Class Imbalance in Fraud Detection
Machine LearningModel answerLast updated
Design and evaluate an ML pipeline for detecting rare fraudulent transactions, navigating class imbalance at every stage from data to deployment.
Scenario
You are an ML engineer at a payments company. The risk team hands you a labeled dataset of 50 million transactions from the past 12 months. Only 0.08% of them are confirmed fraud — roughly 40,000 positive examples.
Your task is to build a production model that flags fraudulent transactions in near-real-time (within 200 ms). The business cost of a false negative (missed fraud) is roughly 20× higher than the cost of a false positive (incorrectly flagging a legitimate transaction).
What the interviewer expects
Walk through your entire approach as if presenting to a senior ML team. Specifically address:
- Problem framing — how do you account for the asymmetric cost and class imbalance from the start?
- Data preparation — which resampling or weighting strategies would you consider, and what are their trade-offs?
- Model choice and training — what algorithms are well-suited, and how do you configure them for imbalance?
- Evaluation — which metrics do you use and why? Which metrics would mislead you here?
- Threshold selection — how do you pick the decision threshold given the cost asymmetry?
- Deployment concerns — what drift or feedback-loop issues should you watch for in production?
Be concrete: mention specific techniques, justify choices with trade-offs, and flag common mistakes.
Hints
Hint 1
Accuracy is ~99.92% if you predict all-legitimate — what does that tell you about which metrics to use?
Hint 2
Think about the 20:1 cost ratio when choosing your resampling strategy and when setting the classification threshold — these are two different levers.
Hint 3
Fraud patterns shift over time as fraudsters adapt. How does that affect your data pipeline and monitoring strategy?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Problem Framing
The 20:1 false-negative-to-false-positive cost ratio is the north star for every decision. Encode it explicitly rather than hoping a default model will discover it.
Key insight: a naive model that always predicts "legitimate" achieves 99.92% accuracy. Accuracy is therefore a useless metric here. Frame this as a cost-sensitive classification problem from day one.
2. Data Preparation
Resampling options
| Technique | Mechanism | Pros | Cons |
|---|---|---|---|
| Random oversampling | Duplicate minority rows | Simple, fast | Overfitting on duplicated rows |
| SMOTE | Synthesize minority neighbors | More generalization than duplication | Can create unrealistic points in sparse regions; slow at this scale |
| Random undersampling | Drop majority rows | Fast, reduces training time | Discards real data; information loss |
| Class weights | Penalize misclassifying minority | No data fabrication; uses all rows | Requires algorithm support; sensitive to weight tuning |
Recommendation at 50 M rows: use class weights (set minority weight to ~20 to reflect cost ratio) as the primary lever. Optionally combine with mild undersampling of the majority class (e.g., keep 10% of legitimate) to reduce training time while preserving most signal. Avoid heavy SMOTE at this scale — it is computationally expensive and fraud feature spaces (sparse categorical IDs, amounts) are poorly suited to interpolation.
3. Model Choice and Training
Gradient-boosted trees (XGBoost / LightGBM) are the standard starting point for tabular fraud data:
- Native
scale_pos_weight(XGBoost) oris_unbalance/class_weight(LightGBM) handle imbalance directly. - Handle mixed feature types (amounts, merchant categories, device fingerprints) well.
- Fast inference — important for the 200 ms SLA.
Logistic regression with class_weight='balanced' is a useful baseline and interpretable for the risk team.
Neural networks are possible but rarely necessary for tabular fraud data and add latency risk.
Training configuration tips:
- Use stratified k-fold cross-validation to ensure each fold has representative fraud examples.
- Tune
scale_pos_weightor equivalent as a hyperparameter (try values between 10 and 50, bracketing the 20:1 cost ratio). - Apply early stopping on a stratified validation set, monitored via PR-AUC (see Section 4).
4. Evaluation Metrics
Use these
- Precision-Recall AUC (PR-AUC): summarizes model quality across all thresholds without being distorted by the massive true-negative count. This is your primary offline metric.
- F-beta score (β = 2 or β = 4): weights recall higher than precision, consistent with the cost ratio. Use this when reporting a single threshold-level number.
- Expected cost:
FN_count × 20 + FP_count × 1— convert model outputs to business dollars.
Avoid these (or use carefully)
- Accuracy: misleading (see above).
- ROC-AUC: less sensitive to imbalance than PR-AUC because ROC uses the true-negative rate, which is dominated by the huge legitimate class.
Concrete target example
A model with PR-AUC of 0.72 vs. a baseline of 0.55 is a meaningful improvement. Pair it with: "At a threshold of 0.3, we catch 88% of fraud (recall) with a 6% false positive rate among flagged transactions (precision = 0.94 on positives)."
5. Threshold Selection
Default threshold of 0.5 is wrong for asymmetric costs. Instead:
Method 1 — Cost minimization: sweep thresholds from 0 to 1, compute Expected Cost = 20 × FN + 1 × FP on a held-out validation set, pick the threshold that minimizes it.
Method 2 — Business constraint: the ops team can manually review at most N flagged transactions per day. Find the threshold that caps daily flags at N while maximizing recall.
Typical result: optimal threshold often falls between 0.1 and 0.3 for heavily imbalanced fraud models — much lower than 0.5.
6. Deployment and Monitoring
Feedback loop (survivorship bias)
Once the model blocks transactions, you never observe ground truth for blocked cases. Over time, training data reflects only transactions the model allowed through — the model's own past decisions corrupt future labels. Mitigate with:
- Random exploration: pass a small random fraction (e.g., 0.5%) of flagged transactions through uninvestigated to gather unbiased labels.
- Reject inference: use semi-supervised methods to estimate labels for blocked transactions.
Concept drift
Fraudsters adapt. Monitor:
- Data drift: feature distributions (transaction amounts, merchant categories) via PSI (Population Stability Index) weekly.
- Model drift: track PR-AUC and recall on a rolling weekly labeled window. Trigger retraining if PR-AUC drops >5% relative.
Class ratio drift
The fraud rate itself can shift (e.g., spikes during holiday season). Monitor the raw positive rate in incoming data and recalibrate the threshold or retrain when it deviates significantly from the training-time rate.
Common Mistakes to Avoid
- Evaluating with accuracy or ROC-AUC alone — gives false confidence.
- Applying SMOTE after train/validation split on the full dataset — this leaks synthetic minority samples into the validation fold, inflating metrics.
- Forgetting to stratify splits — a random split could put all fraud in one fold at 0.08% base rate.
- Treating threshold selection as an afterthought — it is a first-class business decision tied directly to cost.
- Ignoring temporal ordering — always use time-based splits (train on months 1–9, validate on 10–12) rather than random splits, since fraud patterns are time-correlated.