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.
- Overview
- Architecture
- Key Results
- Tech Stack
- Project Structure
- Quick Start
- Training the Model
- Running the Pipeline
- API Reference
- Monitoring & Drift Detection
- Dataset
- Contributing
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
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β 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 β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
| 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.
| 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 |
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
- Python 3.11+
- Docker & Docker Compose
- 8 GB RAM recommended
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.txtDownload creditcard.csv from Kaggle and place it at:
data/raw/creditcard.csv
docker-compose up -d zookeeper kafka mlflow grafanaServices will be available at:
- MLflow UI β http://localhost:5000
- Grafana β http://localhost:3000 (admin / fraudsentinel123)
- API Docs β http://localhost:8000/docs
# Run the full training pipeline with MLflow tracking
python -m src.models.trainer
# Or use Make
make trainThis will:
- Load and preprocess
data/raw/creditcard.csv - Apply SMOTE to balance the training set
- Train XGBoost with early stopping
- Log all metrics, params, and model artifact to MLflow
- Save the model to
models/fraud_sentinel.pkl
View results in MLflow:
mlflow ui --host 0.0.0.0 --port 5000
# Open http://localhost:5000uvicorn src.api.main:app --host 0.0.0.0 --port 8000 --reloadpython -m src.streaming.consumerpython -m src.streaming.producer --csv data/raw/creditcard.csv --delay 0.001docker-compose up --buildPredict 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
}
}
}Batch scoring for up to 1,000 transactions at once.
Service health check.
Full interactive docs at http://localhost:8000/docs
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
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
AmountandClassare the only original features
- Fork the repository
- Create your feature branch:
git checkout -b feature/add-lstm-model - Commit your changes:
git commit -m "feat: add LSTM baseline for comparison" - Push to branch:
git push origin feature/add-lstm-model - Open a Pull Request
MIT License β see LICENSE for details.
Built with β€οΈ | Give it a β if you found this useful!