Ensure ML models maintain performance in production
ML models are trained on historical data but deployed in a changing world. Over time, the relationship between features and outcomes shifts, causing model performance to degrade. This is known as model decay or model staleness.
Input feature distribution changes: P(X) changes
\[P_{train}(X) \neq P_{prod}(X)\]
Example: User age distribution shifts younger due to marketing campaign
Target relationship changes: P(Y|X) changes
\[P_{train}(Y|X) \neq P_{prod}(Y|X)\]
Example: What constitutes "spam" evolves as attackers adapt
Target distribution changes: P(Y) changes
\[P_{train}(Y) \neq P_{prod}(Y)\]
Example: Fraud rate increases during holiday season
Abrupt change (e.g., policy change, bug)
Slow change over time (e.g., user behavior)
Step-wise changes (e.g., feature updates)
Cyclical patterns (e.g., seasonality)
In production, you often can't measure concept drift directly because labels arrive with delay (or never). Focus on data drift as a proxy - if inputs change significantly, model performance likely degrades. Monitor prediction distribution as another signal.
| Method | Feature Type | Description | When to Use |
|---|---|---|---|
| KS Test | Numerical | Max difference between CDFs | General purpose, sensitive to location and shape |
| PSI | Any (binned) | Population Stability Index | Credit scoring, regulatory compliance |
| Chi-Square | Categorical | Compare observed vs expected frequencies | Categorical features, low cardinality |
| Wasserstein | Numerical | Earth Mover's Distance | When magnitude of drift matters |
| JS Divergence | Any (binned) | Symmetric KL divergence | Bounded metric, good for comparisons |
import numpy as np
from scipy import stats
from scipy.spatial.distance import jensenshannon
class DriftDetector:
"""
Statistical methods for detecting distribution drift.
"""
@staticmethod
def ks_test(reference, current):
"""
Kolmogorov-Smirnov test for numerical features.
Returns statistic and p-value.
"""
statistic, p_value = stats.ks_2samp(reference, current)
return {
'method': 'KS Test',
'statistic': statistic,
'p_value': p_value,
'drift_detected': p_value < 0.05
}
@staticmethod
def psi(reference, current, bins=10):
"""
Population Stability Index.
PSI < 0.1: No significant change
PSI 0.1-0.25: Moderate change, investigate
PSI > 0.25: Significant change, action required
"""
# Create bins from reference distribution
bin_edges = np.percentile(reference, np.linspace(0, 100, bins + 1))
bin_edges[0] = -np.inf
bin_edges[-1] = np.inf
# Calculate proportions
ref_counts = np.histogram(reference, bins=bin_edges)[0]
cur_counts = np.histogram(current, bins=bin_edges)[0]
ref_pct = ref_counts / len(reference)
cur_pct = cur_counts / len(current)
# Avoid division by zero
ref_pct = np.clip(ref_pct, 0.0001, 1)
cur_pct = np.clip(cur_pct, 0.0001, 1)
# Calculate PSI
psi_value = np.sum((cur_pct - ref_pct) * np.log(cur_pct / ref_pct))
return {
'method': 'PSI',
'statistic': psi_value,
'drift_detected': psi_value > 0.25,
'severity': 'none' if psi_value < 0.1 else 'moderate' if psi_value < 0.25 else 'high'
}
@staticmethod
def chi_square_test(reference, current):
"""
Chi-square test for categorical features.
"""
# Get unique categories
categories = set(reference) | set(current)
# Count frequencies
ref_counts = {cat: sum(1 for x in reference if x == cat) for cat in categories}
cur_counts = {cat: sum(1 for x in current if x == cat) for cat in categories}
# Align and convert to arrays
ref_freq = np.array([ref_counts.get(cat, 0) for cat in categories])
cur_freq = np.array([cur_counts.get(cat, 0) for cat in categories])
# Normalize to same total
ref_freq = ref_freq / ref_freq.sum() * cur_freq.sum()
statistic, p_value = stats.chisquare(cur_freq, f_exp=ref_freq)
return {
'method': 'Chi-Square',
'statistic': statistic,
'p_value': p_value,
'drift_detected': p_value < 0.05
}
@staticmethod
def js_divergence(reference, current, bins=50):
"""
Jensen-Shannon divergence (symmetric, bounded 0-1).
"""
# Create histograms
min_val = min(reference.min(), current.min())
max_val = max(reference.max(), current.max())
bin_edges = np.linspace(min_val, max_val, bins + 1)
ref_hist, _ = np.histogram(reference, bins=bin_edges, density=True)
cur_hist, _ = np.histogram(current, bins=bin_edges, density=True)
# Normalize to valid probability distributions
ref_hist = ref_hist / ref_hist.sum()
cur_hist = cur_hist / cur_hist.sum()
js_dist = jensenshannon(ref_hist, cur_hist)
return {
'method': 'JS Divergence',
'statistic': js_dist,
'drift_detected': js_dist > 0.1 # Threshold is domain-specific
}
# Usage example
reference_data = np.random.normal(0, 1, 10000)
current_data = np.random.normal(0.5, 1.2, 10000) # Drifted
detector = DriftDetector()
print(detector.ks_test(reference_data, current_data))
print(detector.psi(reference_data, current_data))
print(detector.js_divergence(reference_data, current_data))
# Classifier-based drift detection
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score
import numpy as np
def classifier_drift_detection(reference, current, threshold=0.55):
"""
Train classifier to distinguish reference vs current data.
If AUC > threshold, distributions are distinguishable = drift detected.
Intuition: If you can't tell reference from current, no drift.
"""
# Label data
ref_labels = np.zeros(len(reference))
cur_labels = np.ones(len(current))
X = np.vstack([reference, current])
y = np.concatenate([ref_labels, cur_labels])
# Train classifier
clf = RandomForestClassifier(n_estimators=100, max_depth=5, random_state=42)
auc_scores = cross_val_score(clf, X, y, cv=5, scoring='roc_auc')
mean_auc = auc_scores.mean()
return {
'method': 'Classifier Test',
'auc': mean_auc,
'drift_detected': mean_auc > threshold,
'confidence': 'high' if mean_auc > 0.7 else 'medium' if mean_auc > 0.55 else 'low'
}
# DDM (Drift Detection Method) for streaming
class DDM:
"""
Drift Detection Method for online learning.
Monitors error rate and triggers when it increases significantly.
"""
def __init__(self, min_samples=30, warning_level=2, drift_level=3):
self.min_samples = min_samples
self.warning_level = warning_level
self.drift_level = drift_level
self.reset()
def reset(self):
self.n = 0
self.p = 0
self.s = 0
self.p_min = float('inf')
self.s_min = float('inf')
def add_element(self, error):
"""
Add prediction result (0 = correct, 1 = error).
Returns 'drift', 'warning', or 'normal'.
"""
self.n += 1
# Update error rate
self.p = self.p + (error - self.p) / self.n
self.s = np.sqrt(self.p * (1 - self.p) / self.n)
if self.n < self.min_samples:
return 'normal'
# Track minimum
if self.p + self.s < self.p_min + self.s_min:
self.p_min = self.p
self.s_min = self.s
# Check for drift
if self.p + self.s >= self.p_min + self.drift_level * self.s_min:
self.reset()
return 'drift'
elif self.p + self.s >= self.p_min + self.warning_level * self.s_min:
return 'warning'
return 'normal'
Monitor at multiple levels: Infrastructure (latency, errors) → Data Quality (nulls, schema) → Feature Drift (distribution changes) → Model Performance (accuracy, business KPIs)
# Comprehensive monitoring implementation
from dataclasses import dataclass
from typing import Dict, List, Optional
import numpy as np
from datetime import datetime
@dataclass
class FeatureStats:
mean: float
std: float
min: float
max: float
null_rate: float
unique_count: int
percentiles: Dict[str, float]
class ModelMonitor:
"""
Production model monitoring system.
"""
def __init__(self, reference_data: dict, feature_names: List[str]):
self.reference_stats = self._compute_stats(reference_data, feature_names)
self.feature_names = feature_names
self.alerts = []
def _compute_stats(self, data: dict, features: List[str]) -> Dict[str, FeatureStats]:
stats = {}
for feature in features:
values = np.array(data[feature])
non_null = values[~np.isnan(values)] if np.issubdtype(values.dtype, np.number) else values
stats[feature] = FeatureStats(
mean=np.mean(non_null) if len(non_null) > 0 else 0,
std=np.std(non_null) if len(non_null) > 0 else 0,
min=np.min(non_null) if len(non_null) > 0 else 0,
max=np.max(non_null) if len(non_null) > 0 else 0,
null_rate=1 - len(non_null) / len(values),
unique_count=len(np.unique(non_null)),
percentiles={
'p25': np.percentile(non_null, 25) if len(non_null) > 0 else 0,
'p50': np.percentile(non_null, 50) if len(non_null) > 0 else 0,
'p75': np.percentile(non_null, 75) if len(non_null) > 0 else 0,
'p99': np.percentile(non_null, 99) if len(non_null) > 0 else 0,
}
)
return stats
def check_data_quality(self, current_data: dict) -> List[dict]:
"""
Check for data quality issues.
"""
issues = []
for feature in self.feature_names:
values = np.array(current_data[feature])
ref_stats = self.reference_stats[feature]
# Check null rate
current_null_rate = np.sum(np.isnan(values)) / len(values) if np.issubdtype(values.dtype, np.number) else 0
if current_null_rate > ref_stats.null_rate * 2 + 0.01:
issues.append({
'feature': feature,
'issue': 'high_null_rate',
'severity': 'high',
'expected': ref_stats.null_rate,
'actual': current_null_rate
})
# Check for out-of-range values
if np.issubdtype(values.dtype, np.number):
non_null = values[~np.isnan(values)]
range_buffer = (ref_stats.max - ref_stats.min) * 0.5
out_of_range = np.sum(
(non_null < ref_stats.min - range_buffer) |
(non_null > ref_stats.max + range_buffer)
) / len(non_null)
if out_of_range > 0.01:
issues.append({
'feature': feature,
'issue': 'out_of_range',
'severity': 'medium',
'out_of_range_pct': out_of_range
})
return issues
def check_drift(self, current_data: dict) -> Dict[str, dict]:
"""
Check for feature drift using PSI.
"""
drift_results = {}
for feature in self.feature_names:
ref_values = np.array(current_data[feature])
cur_values = np.array(current_data[feature])
# Use PSI for drift detection
psi_result = DriftDetector.psi(ref_values, cur_values)
drift_results[feature] = psi_result
return drift_results
def check_prediction_drift(self, predictions: np.ndarray, reference_predictions: np.ndarray):
"""
Monitor prediction distribution changes.
"""
return {
'prediction_mean_shift': abs(predictions.mean() - reference_predictions.mean()),
'prediction_std_change': predictions.std() / reference_predictions.std(),
'ks_statistic': stats.ks_2samp(predictions, reference_predictions)[0],
'extreme_prediction_rate': np.mean((predictions < 0.01) | (predictions > 0.99))
}
def generate_report(self, current_data: dict, predictions: np.ndarray) -> dict:
"""
Generate comprehensive monitoring report.
"""
return {
'timestamp': datetime.now().isoformat(),
'data_quality': self.check_data_quality(current_data),
'feature_drift': self.check_drift(current_data),
'sample_size': len(predictions),
'prediction_stats': {
'mean': predictions.mean(),
'std': predictions.std(),
'min': predictions.min(),
'max': predictions.max()
}
}
| Severity | Condition | Response | Example |
|---|---|---|---|
| Critical | Model serving failures, major data issues | Immediate page, consider rollback | 100% null rate, serving errors spike |
| High | Significant drift detected (PSI > 0.25) | Page on-call, investigate within hours | Major feature distribution shift |
| Medium | Moderate drift (0.1 < PSI < 0.25) | Create ticket, investigate within days | Gradual drift in multiple features |
| Low | Minor anomalies | Log for review, batch investigation | Slight uptick in edge cases |
# Automated retraining trigger
class RetrainingController:
"""
Decide when to trigger model retraining.
"""
def __init__(self, config):
self.config = config
self.drift_history = []
self.last_retrain = datetime.now()
def should_retrain(self, monitoring_report: dict) -> dict:
"""
Determine if retraining is needed based on monitoring signals.
"""
reasons = []
urgency = 'none'
# Check feature drift
high_drift_features = [
f for f, result in monitoring_report['feature_drift'].items()
if result.get('severity') == 'high'
]
if len(high_drift_features) >= self.config['max_drifted_features']:
reasons.append(f"High drift in {len(high_drift_features)} features")
urgency = 'high'
# Check data quality
critical_issues = [
i for i in monitoring_report['data_quality']
if i['severity'] == 'high'
]
if critical_issues:
reasons.append(f"{len(critical_issues)} critical data quality issues")
urgency = 'critical'
# Check time since last retrain
days_since_retrain = (datetime.now() - self.last_retrain).days
if days_since_retrain > self.config['max_days_between_retrains']:
reasons.append(f"{days_since_retrain} days since last retrain")
if urgency == 'none':
urgency = 'low'
# Track drift history for trend
self.drift_history.append(monitoring_report)
return {
'should_retrain': len(reasons) > 0,
'urgency': urgency,
'reasons': reasons,
'recommendation': self._get_recommendation(urgency, reasons)
}
def _get_recommendation(self, urgency: str, reasons: list) -> str:
if urgency == 'critical':
return "IMMEDIATE ACTION: Consider rollback while investigating"
elif urgency == 'high':
return "Schedule retraining within 24 hours"
elif urgency == 'low':
return "Add to next scheduled retraining batch"
return "Continue monitoring"
# Example configuration
config = {
'max_drifted_features': 3,
'max_days_between_retrains': 30,
'performance_threshold': 0.05 # 5% degradation
}
Know the landscape: Evidently AI (open source, great for drift), WhyLabs (managed, real-time), Arize (embeddings, LLMs), Fiddler (explainability focus). For custom solutions, combine Prometheus/Grafana for metrics with custom drift detection code.
Without labels, focus on proxy signals:
| Aspect | Data Drift | Concept Drift |
|---|---|---|
| Definition | P(X) changes | P(Y|X) changes |
| Detection | Easy (compare distributions) | Hard (requires labels) |
| Example | User age shifts younger | What constitutes "spam" changes |
| Impact | Model may extrapolate poorly | Model fundamentally wrong |
| Solution | May not need retraining | Definitely needs retraining |