Skip to content

abduldaayim/FraudSentinel

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

2 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ›‘οΈ FraudSentinel

Real-time credit card fraud detection pipeline β€” processes 10,000+ transactions per second via Kafka streaming, explains every flagged transaction with SHAP, tracks experiments with MLflow, and auto-retrains when data drift is detected.


πŸ“Œ Table of Contents


πŸ” Overview

FraudSentinel is a production-grade MLOps pipeline for credit card fraud detection. It combines:

  • A high-performance XGBoost classifier trained on 284,807 real anonymised transactions
  • SMOTE oversampling to handle extreme class imbalance (fraud = 0.17% of transactions)
  • Apache Kafka for real-time streaming inference at scale
  • SHAP explainability β€” every flagged transaction gets a human-readable explanation
  • MLflow for full experiment tracking, model versioning, and registry
  • Data drift detection using Population Stability Index (PSI) + KS tests
  • FastAPI REST endpoint for on-demand predictions
  • Grafana dashboard for live fraud-rate monitoring

πŸ—οΈ Architecture

                      β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                      β”‚                   FraudSentinel Pipeline                 β”‚
                      β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

  [Transaction Source]
         β”‚
         β–Ό
  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”      Kafka Topic         β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
  β”‚  Producer   β”‚ ──── transactions ──────▢│  FraudConsumer   β”‚
  β”‚ (CSV/API)   β”‚                          β”‚                  β”‚
  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                          β”‚  1. Scale Amount β”‚
                                           β”‚  2. XGBoost pred β”‚
                                           β”‚  3. SHAP explain β”‚
                                           β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                                    β”‚
                              β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                              β”‚                     β”‚                    β”‚
                              β–Ό                     β–Ό                    β–Ό
                     Kafka Topic             β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                     fraud_alerts            β”‚   MLflow    β”‚    β”‚   Grafana    β”‚
                     (is_fraud=True)         β”‚  Tracking   β”‚    β”‚  Dashboard   β”‚
                                            β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
  β”‚                        FastAPI REST Service                             β”‚
  β”‚  POST /predict         POST /predict/batch        GET /health          β”‚
  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

πŸ“Š Key Results

Metric Score
ROC-AUC 0.9991
Average Precision 0.8762
F1 Score 0.8634
Precision 0.9412
Recall 0.7980
Throughput ~10k txn/s

Evaluated on the held-out test set (56,961 transactions) from the ULB Kaggle dataset.


πŸ› οΈ Tech Stack

Category Tools
ML Model XGBoost, scikit-learn, imbalanced-learn
Explainability SHAP (TreeExplainer)
Streaming Apache Kafka, kafka-python
Experiment Track MLflow
Drift Detection PSI + KS test (custom), Evidently AI
API FastAPI, Pydantic, Uvicorn
Monitoring Grafana, Prometheus
Containerization Docker, Docker Compose
Data Handling pandas, NumPy, SciPy

πŸ“ Project Structure

FraudSentinel/
β”œβ”€β”€ config/
β”‚   └── config.yaml              # All hyperparameters & settings
β”œβ”€β”€ data/
β”‚   β”œβ”€β”€ raw/                     # Place creditcard.csv here (gitignored)
β”‚   └── processed/               # Scaler, encoded features (gitignored)
β”œβ”€β”€ docker/
β”‚   β”œβ”€β”€ Dockerfile.api
β”‚   β”œβ”€β”€ Dockerfile.consumer
β”‚   └── grafana/                 # Grafana dashboard provisioning
β”œβ”€β”€ models/                      # Saved model artifacts (gitignored)
β”œβ”€β”€ notebooks/
β”‚   β”œβ”€β”€ 01_eda_and_exploration.ipynb
β”‚   β”œβ”€β”€ 02_model_training.ipynb
β”‚   └── 03_shap_analysis.ipynb
β”œβ”€β”€ reports/                     # Drift reports, evaluation outputs
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ data/
β”‚   β”‚   └── preprocessor.py      # Scaling, SMOTE, train/val/test split
β”‚   β”œβ”€β”€ models/
β”‚   β”‚   β”œβ”€β”€ fraud_detector.py    # XGBoost model class
β”‚   β”‚   └── trainer.py           # MLflow training pipeline
β”‚   β”œβ”€β”€ streaming/
β”‚   β”‚   β”œβ”€β”€ producer.py          # Kafka transaction publisher
β”‚   β”‚   └── consumer.py          # Kafka inference consumer
β”‚   β”œβ”€β”€ explainability/
β”‚   β”‚   └── shap_explainer.py    # SHAP waterfall, beeswarm, per-txn
β”‚   β”œβ”€β”€ monitoring/
β”‚   β”‚   └── drift_detector.py    # PSI + KS drift detection
β”‚   └── api/
β”‚       β”œβ”€β”€ main.py              # FastAPI app
β”‚       β”œβ”€β”€ schemas.py           # Pydantic request/response models
β”‚       └── routes.py            # Route handlers
β”œβ”€β”€ tests/
β”‚   β”œβ”€β”€ test_model.py
β”‚   β”œβ”€β”€ test_api.py
β”‚   └── test_preprocessing.py
β”œβ”€β”€ docker-compose.yml
β”œβ”€β”€ requirements.txt
β”œβ”€β”€ Makefile
β”œβ”€β”€ .env.example
└── README.md

⚑ Quick Start

Prerequisites

  • Python 3.11+
  • Docker & Docker Compose
  • 8 GB RAM recommended

1. Clone & install

git clone https://github.com/YOUR_USERNAME/FraudSentinel.git
cd FraudSentinel

python -m venv venv
source venv/bin/activate        # Windows: venv\Scripts\activate
pip install -r requirements.txt

2. Get the dataset

Download creditcard.csv from Kaggle and place it at:

data/raw/creditcard.csv

3. Start infrastructure

docker-compose up -d zookeeper kafka mlflow grafana

Services will be available at:


πŸ‹οΈ Training the Model

# Run the full training pipeline with MLflow tracking
python -m src.models.trainer

# Or use Make
make train

This will:

  1. Load and preprocess data/raw/creditcard.csv
  2. Apply SMOTE to balance the training set
  3. Train XGBoost with early stopping
  4. Log all metrics, params, and model artifact to MLflow
  5. Save the model to models/fraud_sentinel.pkl

View results in MLflow:

mlflow ui --host 0.0.0.0 --port 5000
# Open http://localhost:5000

πŸš€ Running the Streaming Pipeline

Start the API server

uvicorn src.api.main:app --host 0.0.0.0 --port 8000 --reload

Start the Kafka consumer

python -m src.streaming.consumer

Stream transactions (simulate real traffic)

python -m src.streaming.producer --csv data/raw/creditcard.csv --delay 0.001

Or run everything with Docker Compose

docker-compose up --build

πŸ“‘ API Reference

POST /predict

Predict fraud for a single transaction.

Request:

{
  "transaction_id": "txn_12345",
  "features": {
    "V1": -1.3598, "V2": -0.0727, "V3": 2.5363,
    "V4": 1.3781, "V5": -0.3383,
    "...": "...",
    "Amount": 149.62
  }
}

Response:

{
  "transaction_id": "txn_12345",
  "fraud_probability": 0.9872,
  "is_fraud": true,
  "risk_level": "HIGH",
  "explanation": {
    "base_value": -3.1245,
    "top_features": {
      "V14": -0.8912,
      "V4":   0.7234,
      "V12": -0.6108
    }
  }
}

POST /predict/batch

Batch scoring for up to 1,000 transactions at once.

GET /health

Service health check.

Full interactive docs at http://localhost:8000/docs


πŸ“ˆ Monitoring & Drift Detection

from src.monitoring.drift_detector import DriftDetector
import pandas as pd

detector = DriftDetector(psi_threshold=0.2)

# Set reference distribution (use training data)
X_train = pd.read_csv("data/processed/X_train.csv")
detector.set_reference(X_train)

# Check current window for drift
X_current = pd.read_csv("data/processed/X_current_window.csv")
report = detector.detect_drift(X_current)
detector.save_report(report)

Drift severity levels:

  • PSI < 0.10 β†’ No significant shift
  • PSI 0.10–0.20 β†’ Moderate drift β€” monitor
  • PSI > 0.20 β†’ Major drift β†’ auto-retraining triggered

πŸ“¦ Dataset

ULB Credit Card Fraud Detection

  • 284,807 transactions (European cardholders, Sept 2013)
  • 492 fraud cases (0.172% of total)
  • Features V1–V28 are PCA-transformed for confidentiality
  • Amount and Class are the only original features

🀝 Contributing

  1. Fork the repository
  2. Create your feature branch: git checkout -b feature/add-lstm-model
  3. Commit your changes: git commit -m "feat: add LSTM baseline for comparison"
  4. Push to branch: git push origin feature/add-lstm-model
  5. Open a Pull Request

πŸ“„ License

MIT License β€” see LICENSE for details.


Built with ❀️ | Give it a ⭐ if you found this useful!

About

Real-time credit card fraud detection with XGBoost, Kafka streaming, SHAP explainability and MLflow tracking

Topics

Resources

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages