Skip to main content

Lesson 8 of 9

Capstone Project: End-to-End Enterprise Fraud Detection System with Monitoring & Serving

Synthesize the entire course into a capstone enterprise machine learning system. We ingest raw financial transactions, engineer domain velocity and cyclical features, handle severe class imbalance, train an optimized Gradient Boosted Decision Tree, wrap it in an atomic Scikit-Learn Pipeline, benchmark inference latency, compute statistical drift via PSI, and package the solution into a deployable FastAPI serving architecture.

40 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Complete Capstone Production ML System Implementation

Complete Capstone Production ML System Implementation
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split, StratifiedKFold
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import RobustScaler, OneHotEncoder
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.metrics import roc_auc_score, average_precision_score, classification_report
import joblib

# 1. ENTERPRISE DATASET INGESTION & DOMAIN FEATURE ENGINEERING
np.random.seed(42)
n_tx = 5000
df_tx = pd.DataFrame({
    'amount_usd': np.random.lognormal(mean=4.0, sigma=1.2, size=n_tx),
    'account_age_days': np.random.exponential(scale=300, size=n_tx).clip(1, 2000),
    'device_type': np.random.choice(['iOS', 'Android', 'Web'], size=n_tx, p=[0.5, 0.4, 0.1]),
    'channel': np.random.choice(['ONLINE', 'IN_STORE', 'ATM'], size=n_tx, p=[0.7, 0.2, 0.1]),
    'hour_of_day': np.random.randint(0, 24, size=n_tx)
})

# Feature Engineering: Cyclical temporal encoding & velocity proxy
df_tx['sin_hour'] = np.sin(2 * np.pi * df_tx['hour_of_day'] / 24.0)
df_tx['cos_hour'] = np.cos(2 * np.pi * df_tx['hour_of_day'] / 24.0)
df_tx['spend_velocity'] = df_tx['amount_usd'] / np.maximum(df_tx['account_age_days'], 1.0)

# Ground truth fraud (imbalanced ~3% rate)
fraud_risk = (
    0.015 * df_tx['amount_usd']
    + 1.5 * (df_tx['channel'] == 'ONLINE')
    + 8.0 * df_tx['spend_velocity']
    - 4.0
)
df_tx['is_fraud'] = (1 / (1 + np.exp(-fraud_risk)) > np.random.uniform(0, 1, size=n_tx)).astype(int)

# 2. LEAK-FREE DATA PARTITIONING
X = df_tx.drop(columns=['is_fraud', 'hour_of_day'])
y = df_tx['is_fraud']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)

# 3. ATOMIC PREPROCESSING PIPELINE
preprocessor = ColumnTransformer(
    transformers=[
        ('num', RobustScaler(), ['amount_usd', 'account_age_days', 'sin_hour', 'cos_hour', 'spend_velocity']),
        ('cat', OneHotEncoder(drop='first', sparse_output=False, handle_unknown='ignore'), ['device_type', 'channel'])
    ]
)

# 4. CHAMPION PIPELINE ARCHITECTURE
production_pipeline = Pipeline([
    ('prep', preprocessor),
    ('clf', HistGradientBoostingClassifier(
        class_weight='balanced',
        max_iter=100,
        learning_rate=0.08,
        random_state=42
    ))
])

# 5. MODEL TRAINING & VALIDATION
production_pipeline.fit(X_train, y_train)
y_probs = production_pipeline.predict_proba(X_test)[:, 1]

print("=== CAPSTONE ENTERPRISE FRAUD SYSTEM AUDIT ===")
print(f"Held-Out Test ROC-AUC : {roc_auc_score(y_test, y_probs):.4f}")
print(f"Held-Out Test PR-AUC  : {average_precision_score(y_test, y_probs):.4f}")

# 6. SERIALIZATION & SERVING SMOKE TEST
joblib.dump(production_pipeline, 'capstone_fraud_pipeline_v1.joblib')
loaded_pipeline = joblib.load('capstone_fraud_pipeline_v1.joblib')

live_test_applicant = pd.DataFrame([{
    'amount_usd': 1250.00,
    'account_age_days': 14.0,
    'device_type': 'Web',
    'channel': 'ONLINE',
    'sin_hour': np.sin(2 * np.pi * 3 / 24.0), # 3 AM
    'cos_hour': np.cos(2 * np.pi * 3 / 24.0),
    'spend_velocity': 1250.0 / 14.0
}])

live_risk = loaded_pipeline.predict_proba(live_test_applicant)[0, 1]
print(f"\nLive Inference on High-Risk 3 AM Online Transaction: Risk Score = {live_risk*100:.2f}%")
print(f"Automated Action: {'DECLINE & BLOCK CARD' if live_risk > 0.40 else 'APPROVE'}")

Pro Tip: Production Model Cards for Regulatory Compliance

In financial production, every deployed model must be accompanied by a Model Card detailing: (1) Business problem framing, (2) Training data date ranges, (3) Excluded sensitive demographics, (4) Quantitative ROC and PR metrics, and (5) Operational runbooks for incident response.

Diagram
Loading diagramโ€ฆ

MlCapstoneProductionSystem Visual Representation

Hands-On Challenge: Build a Complete FastAPI Microservice

Create a `main.py` script with FastAPI that loads `capstone_fraud_pipeline_v1.joblib` on startup and serves real-time predictions at `/v1/score-transaction` with full Pydantic schema validation.

Quick Quiz & Key Concept Checks

Common Pitfall: Deploying Models Without Automated Rollback

Never deploy a new model without automated health checks. If an error rate spike or drift warning occurs during the first 10 minutes of live traffic, the deployment orchestrator must automatically revert traffic to the previous version.

Topics in This Module

0/9 done