Train a Fraud Detector Under Severe Class Imbalance
Machine LearningModel answerLast updated
Design and defend an end-to-end ML system for fraud detection where genuine fraud accounts for less than 0.1% of transactions.
Scenario
You are an ML engineer at a payments platform. The data science team has built a binary classifier to flag fraudulent transactions in real time. The dataset contains 500 million transactions from the past 18 months; only ~0.08% are labeled fraud (roughly 400,000 positive examples). A junior teammate trained an XGBoost model, achieved 99.92% accuracy, and declared the problem solved. Your tech lead asks you to review the work before it ships.
What is expected
Address the following in your response:
- Problem framing — Why is accuracy a misleading metric here? What are the business consequences of each error type?
- Data strategy — What resampling, weighting, or data-augmentation techniques would you consider, and what are the trade-offs of each?
- Modeling choices — Which algorithms or training modifications are best suited to severe imbalance, and why?
- Evaluation — Define the metrics you would use, explain the precision-recall trade-off, and specify how you would set the decision threshold.
- Deployment & monitoring — How does imbalance affect production monitoring, and what signals would trigger a model refresh?
- Common pitfalls — Identify at least three mistakes practitioners frequently make with imbalanced datasets.
You may assume labels are reliable (no label noise) and that you have access to raw transaction features (amount, merchant category, device fingerprint, velocity signals, etc.).
Hints
Hint 1
Start by computing what accuracy a trivially naive model achieves, then use that as a baseline argument against the metric choice.
Hint 2
Think about the asymmetric cost of false negatives (missed fraud) vs. false positives (blocked legitimate transactions) and how that should drive both your loss function and threshold selection.
Hint 3
Data leakage through the time axis is the single most common mistake in fraud modeling — make sure your validation strategy reflects the temporal nature of the data.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Why Accuracy Is Misleading
A model that predicts "not fraud" for every transaction achieves 99.92% accuracy — exactly the score the junior teammate reported. This is the null model. It catches zero fraudsters and is operationally worthless.
The confusion matrix tells the real story:
- False Negative (FN): fraud goes undetected → direct financial loss, regulatory exposure, customer harm.
- False Positive (FP): legitimate transaction blocked → customer friction, churn, support cost.
Typical industry estimates put the cost of one FN at 5–20× the cost of one FP, so we need a metric that reflects this asymmetry.
2. Evaluation Metrics
Replace accuracy with:
| Metric | Why useful |
|---|---|
| Precision | Of flagged transactions, how many are real fraud? Drives operational load. |
| Recall (Sensitivity) | Of all frauds, how many did we catch? Drives loss exposure. |
| F-beta (β > 1, e.g., β = 2) | Weights recall more than precision, matching business priorities. |
| PR-AUC | Area under the Precision-Recall curve; far more informative than ROC-AUC at extreme imbalance because it ignores the massive true-negative population. |
| Expected cost | cost = FN_cost × FN_count + FP_cost × FP_count; requires a cost matrix from the business. |
ROC-AUC is not sufficient here. Because there are ~499.6 million negatives, even a weak model can move the ROC curve favorably while still missing most frauds.
Threshold selection: Do not use 0.5. Plot the PR curve and choose the operating point that minimizes expected cost (or satisfies a business SLA such as "recall ≥ 85% at precision ≥ 40%").
3. Data Strategy
Resampling
Oversampling positives:
- Random oversampling: fast, risks overfitting to duplicated examples.
- SMOTE: synthesizes new minority examples by interpolating in feature space. Works well for tabular data with continuous features; can create unrealistic examples near class boundaries. Avoid SMOTE on sparse or categorical-heavy feature sets without variant (e.g., SMOTE-NC).
- Apply oversampling only on the training fold, never before the train/test split.
Undersampling negatives:
- Random undersampling discards real data and can hurt calibration.
- Tomek links or Edited Nearest Neighbors remove borderline majority samples to sharpen the decision boundary — more targeted.
Combined: SMOTEENN (SMOTE + Edited Nearest Neighbours) often outperforms either alone.
Class Weighting (preferred baseline)
Set class_weight = {0: 1, 1: N_neg/N_pos ≈ 1250} or tune it as a hyperparameter. Most frameworks (XGBoost scale_pos_weight, sklearn class_weight='balanced') support this natively. No data is discarded; no synthetic noise is introduced. Start here.
Data Augmentation
For transactional data, feature-level noise injection or time-shifted replays of known fraud patterns can increase diversity without pure duplication.
4. Modeling Choices
Tree-based ensembles (XGBoost, LightGBM, CatBoost): Handle tabular imbalance well with scale_pos_weight. LightGBM's is_unbalance=True flag is a convenient shortcut.
Focal Loss (originally from object detection): Down-weights well-classified easy negatives, forcing the model to focus on hard-to-classify minority examples. Highly effective at extreme imbalance; can be plugged into any framework that accepts custom loss functions.
Two-stage models: Train a high-recall coarse filter to reduce the candidate set, then a high-precision ranker on that shortlist. This mirrors real production fraud systems.
Calibration: After training, apply Platt scaling or isotonic regression so that the model's output probability is meaningful for threshold-setting and cost calculations. Tree models are often poorly calibrated out of the box.
Avoid: Naive neural networks without weighted loss; logistic regression without penalty adjustment; any model evaluated solely on accuracy.
5. Temporal Validation — The Most Critical Pitfall
Fraud data has a time axis. Fraudsters adapt; feature distributions shift. Always use a time-based train/validation/test split:
- Train: months 1–14
- Validation: months 15–16
- Test: months 17–18
Never use random k-fold on temporal fraud data. It leaks future information into training, inflates all metrics, and produces models that degrade immediately in production.
6. Deployment & Monitoring
Score distribution drift: Monitor the distribution of model scores daily. A shift in the mean fraud score indicates concept drift (new fraud patterns) or data pipeline issues.
Population Stability Index (PSI): Flags input feature drift. If PSI > 0.2 on key features, investigate before trusting model output.
Business KPIs: Track fraud rate ($ and count), chargeback rate, and false-positive block rate on a rolling 7-day window. Set alerting thresholds.
Refresh triggers:
- Recall on labeled feedback drops >5 percentage points from baseline.
- A new fraud typology is identified by the investigations team.
- PSI > 0.2 on more than 3 top features.
Label delay: Chargebacks and fraud confirmations arrive days to weeks after the transaction. Build a delayed labeling pipeline; do not evaluate on transactions too recent to have stable labels.
7. Common Pitfalls (Summary)
- Applying resampling before the train/test split — synthetic minority samples appear in both train and test, causing optimistic evaluation.
- Using ROC-AUC or accuracy as the primary metric — both are dominated by the majority class at 0.08% prevalence.
- Random k-fold on time-series data — future leaks into past; all validation metrics are inflated.
- Threshold fixed at 0.5 — the optimal operating point at extreme imbalance is almost never 0.5.
- Ignoring calibration — an uncalibrated score makes cost-based threshold tuning unreliable.
- Oversampling categorical features with vanilla SMOTE — interpolation between one-hot vectors produces nonsensical feature combinations.