Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Applied Ensemble Methods: Fraud Detection

Core imports successful!

1. The Dataset: Credit Card Fraud Detection

We’ll use the famous Credit Card Fraud Detection dataset from Kaggle — real anonymized transactions from European cardholders in September 2013.

Dataset characteristics:

  • 284,807 transactions over 2 days

  • 492 frauds (0.172% — extremely imbalanced!)

  • 30 features: Time, Amount, and 28 PCA-transformed features (V1-V28) for privacy

  • This is the most cited fraud detection dataset in ML literature

Source: Kaggle Credit Card Fraud Detection

We’ll try to download the real dataset; if unavailable, we’ll fall back to a synthetic version that mimics its characteristics.

============================================================
CREDIT CARD FRAUD DETECTION DATASET
============================================================
Source: Local file: creditcard.csv
Total transactions: 284,807
Fraudulent: 492 (0.173%)
Legitimate: 284,315 (99.827%)
Features: 30 (Time, V1-V28, Amount)
============================================================
<Figure size 1200x400 with 2 Axes>

Notice: Fraudulent transactions tend to have higher amounts.
This is one signal the model can learn.
Training set: 227,845 samples (394 fraud)
Test set: 56,962 samples (98 fraud)
Features: 30

2. The Challenge: Imbalanced Classification

With only 2% fraud, a naive model could predict “legitimate” for everything and achieve 98% accuracy — but catch zero fraud!

Metrics that matter for fraud detection:

  • Precision: Of predicted frauds, how many are real? (avoid annoying customers)

  • Recall: Of actual frauds, how many did we catch? (minimize losses)

  • PR-AUC: Precision-Recall Area Under Curve (better than ROC-AUC for imbalanced data)

Let’s see what happens with a naive baseline.

Naive Baseline (Predict All Legitimate)
==================================================
Accuracy: 99.83%
Frauds caught: 0 out of 98

This is why accuracy is misleading for imbalanced data!

3. XGBoost: The Industry Standard

XGBoost handles imbalanced data well with the scale_pos_weight parameter, which adjusts the weight of the minority class.

Why XGBoost dominates fraud detection:

  1. Handles imbalanced data natively

  2. Fast training (no GPU needed)

  3. Built-in feature importance

  4. Robust to outliers

  5. Easy to deploy in production

Scale pos weight: 577.3 (ratio of legitimate to fraud)

XGBoost trained successfully!
XGBoost Performance
==================================================
              precision    recall  f1-score   support

  Legitimate       1.00      1.00      1.00     56864
       Fraud       0.88      0.84      0.86        98

    accuracy                           1.00     56962
   macro avg       0.94      0.92      0.93     56962
weighted avg       1.00      1.00      1.00     56962


ROC-AUC: 0.9684
PR-AUC: 0.8787

Confusion Matrix:
  True Negatives: 56,853 (legitimate correctly identified)
  False Positives: 11 (legitimate flagged as fraud)
  False Negatives: 16 (fraud missed!)
  True Positives: 82 (fraud caught!)

4. Neural Network Comparison

Let’s train a neural network on the same data and compare. This demonstrates why deep learning isn’t always the answer for tabular data.

Neural Network Performance
==================================================
              precision    recall  f1-score   support

  Legitimate       1.00      1.00      1.00     56864
       Fraud       0.88      0.79      0.83        98

    accuracy                           1.00     56962
   macro avg       0.94      0.89      0.91     56962
weighted avg       1.00      1.00      1.00     56962


ROC-AUC: 0.9794
PR-AUC: 0.8683
<Figure size 1400x500 with 2 Axes>

5. Model Explainability: Why This Matters in 2026

With regulations like the EU AI Act and increasing scrutiny on algorithmic decisions, explainability is crucial.

Tree ensembles provide:

  1. Feature importance — which features drive predictions?

  2. SHAP values — why did the model make THIS specific prediction?

This is much harder with neural networks!

<Figure size 1000x800 with 1 Axes>
Top 5 Most Important Features:
  V14: 0.5912
  V4: 0.0612
  V12: 0.0422
  V8: 0.0234
  V13: 0.0171
<Figure size 800x950 with 1 Axes>
SHAP values show the impact of each feature on model predictions.
This is crucial for explaining individual fraud decisions to regulators.
Explaining a Fraud Detection Decision
==================================================
Transaction probability of fraud: 99.99%
Model decision: FRAUD

Top factors contributing to this decision:
  V14: increases fraud probability by 6.557
  V10: increases fraud probability by 1.685
  V7: increases fraud probability by 1.080
  V8: decreases fraud probability by 0.929
  V12: increases fraud probability by 0.849

6. Production Considerations

Why Banks Choose XGBoost Over Deep Learning

FactorXGBoostDeep Learning
Training timeMinutesHours
HardwareCPU onlyGPU preferred
Inference speed~1ms~10ms
ExplainabilityBuilt-inRequires extra tools
Regulatory complianceEasyDifficult
Model size~10MB~100MB+

Real-World Deployment

# Save model for production
import joblib
joblib.dump(xgb_model, 'fraud_model.pkl')

# Load and predict (in production)
model = joblib.load('fraud_model.pkl')
fraud_probability = model.predict_proba(transaction)[0, 1]

if fraud_probability > 0.7:
    block_transaction()
elif fraud_probability > 0.3:
    flag_for_review()
else:
    approve_transaction()
Threshold Analysis: Precision vs Recall Tradeoff
============================================================
Threshold    Precision    Recall       Frauds Caught  
------------------------------------------------------------
0.3          86.46%       84.69%       83/98
0.5          88.17%       83.67%       82/98
0.7          90.11%       83.67%       82/98
0.9          94.19%       82.65%       81/98

Business decision: Choose threshold based on cost of false positives vs missed fraud.

7. Summary: Why Ensembles Still Matter

Key Takeaways

  1. For tabular data, tree ensembles still outperform deep learning in most benchmarks

  2. XGBoost/LightGBM advantages:

    • No GPU required

    • Handles imbalanced data natively

    • Built-in feature importance

    • Easy to explain to regulators

    • Fast inference for production

  3. When to use deep learning instead:

    • Images, text, audio (unstructured data)

    • Very high-cardinality categoricals (embeddings help)

    • When you have massive datasets (100M+ rows)

  4. The hybrid approach (industry trend):

    • Use LLMs/embeddings to create features from text

    • Feed those features into XGBoost for final prediction

    • Best of both worlds!

Further Reading


Exercises

  1. Try LightGBM: Install lightgbm and compare its performance to XGBoost. Which is faster?

  2. SMOTE resampling: Use imblearn.over_sampling.SMOTE to oversample the minority class. Does it improve recall?

  3. Cost-sensitive learning: Modify the threshold based on the actual cost of false positives (10customerservicecall)vsfalsenegatives(10 customer service call) vs false negatives (500 fraud loss).

  4. Ensemble of ensembles: Combine XGBoost, LightGBM, and CatBoost using soft voting. Does the meta-ensemble outperform individual models?