monitor-model-drift
Implement model drift monitoring using Evidently AI, statistical tests (PSI, KS), and custom metrics to detect data drift and concept drift in production ML systems. Set up automated alerting and reporting workflows to catch degradation before it impacts business metrics. Use when production models show unexplained performance degradation, when new data distributions differ from training data, when seasonal shifts affect input features, or when regulatory requirements mandate model monitoring.
Best use case
monitor-model-drift is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
Implement model drift monitoring using Evidently AI, statistical tests (PSI, KS), and custom metrics to detect data drift and concept drift in production ML systems. Set up automated alerting and reporting workflows to catch degradation before it impacts business metrics. Use when production models show unexplained performance degradation, when new data distributions differ from training data, when seasonal shifts affect input features, or when regulatory requirements mandate model monitoring.
Teams using monitor-model-drift should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/monitor-model-drift/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How monitor-model-drift Compares
| Feature / Agent | monitor-model-drift | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
Implement model drift monitoring using Evidently AI, statistical tests (PSI, KS), and custom metrics to detect data drift and concept drift in production ML systems. Set up automated alerting and reporting workflows to catch degradation before it impacts business metrics. Use when production models show unexplained performance degradation, when new data distributions differ from training data, when seasonal shifts affect input features, or when regulatory requirements mandate model monitoring.
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
SKILL.md Source
# Monitor Model Drift
> See [Extended Examples](references/EXAMPLES.md) for complete configuration files and templates.
Detect and alert on data drift and concept drift in production ML models using statistical tests and automated monitoring.
## When to Use
- Production ML models with unexplained performance degradation
- New data distributions differ from training data
- Seasonal or temporal shifts in input features
- Need proactive alerts before business metrics are impacted
- Regulatory requirements for model monitoring (e.g., SR 11-7, EU AI Act)
- Multiple model versions deployed requiring drift comparison
## Inputs
- **Required**: Production model predictions and features (last 30-90 days)
- **Required**: Reference dataset (training or validation data)
- **Required**: Ground truth labels (may be delayed)
- **Optional**: Feature importance scores or SHAP values
- **Optional**: Business metric thresholds for alerting
- **Optional**: Historical drift reports for trend analysis
## Procedure
### Step 1: Install and Configure Evidently AI
Set up the monitoring framework with appropriate dependencies.
```bash
# Create virtual environment
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install Evidently and dependencies
pip install evidently pandas scikit-learn prometheus-client
# Create monitoring directory structure
mkdir -p monitoring/{reports,config,alerts}
```
Create configuration file:
```python
# monitoring/config/drift_config.py
from evidently.metric_preset import DataDriftPreset, TargetDriftPreset
from evidently.metrics import (
DatasetDriftMetric,
DatasetMissingValuesMetric,
ColumnDriftMetric,
)
# ... (see EXAMPLES.md for complete implementation)
```
**Got:** Configuration file created with thresholds matching your model's tolerance.
**If fail:** Start with conservative thresholds (PSI > 0.2, KS p-value < 0.01) and tune based on false positive rate.
### Step 2: Implement Data Drift Detection
Create drift detection pipeline with multiple statistical tests.
```python
# monitoring/drift_detector.py
import pandas as pd
import numpy as np
from scipy.stats import ks_2samp, chi2_contingency
from evidently.report import Report
from evidently.metric_preset import DataDriftPreset
from evidently.metrics import ColumnDriftMetric, DatasetDriftMetric
from datetime import datetime, timedelta
# ... (see EXAMPLES.md for complete implementation)
```
**Got:** Drift detection runs successfully, produces JSON report with per-feature statistics, and identifies drifted features.
**If fail:** Check for missing values (impute or drop), ensure reference and current data have the same columns, verify data types match between datasets.
### Step 3: Generate Evidently Reports
Create visual HTML reports for human review and debugging.
```python
# monitoring/generate_reports.py
from evidently.report import Report
from evidently.metric_preset import DataDriftPreset, TargetDriftPreset
from evidently.metrics import (
ColumnDriftMetric,
DatasetDriftMetric,
DatasetMissingValuesMetric,
)
# ... (see EXAMPLES.md for complete implementation)
```
**Got:** HTML reports generated in `monitoring/reports/`, viewable in browser with interactive charts showing distribution comparisons.
**If fail:** Verify write permissions to output directory, check that Evidently version is >= 0.4.0, ensure data frames have sufficient rows (>100 recommended).
### Step 4: Implement Concept Drift Detection
Monitor prediction performance to detect concept drift (relationship between features and target changes).
```python
# monitoring/concept_drift.py
import pandas as pd
import numpy as np
from sklearn.metrics import roc_auc_score, mean_squared_error, accuracy_score
from typing import Dict, List
import json
# ... (see EXAMPLES.md for complete implementation)
```
**Got:** Performance monitoring detects when model accuracy/AUC drops below threshold, signaling potential concept drift.
**If fail:** Ensure ground truth labels are available (may require delayed validation batch job), verify prediction scores are calibrated (0-1 range for classification), check for label leakage in features.
### Step 5: Set Up Automated Alerting
Integrate drift detection with alerting systems (Slack, PagerDuty, email).
```python
# monitoring/alerting.py
import requests
import json
from typing import Dict, List
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# ... (see EXAMPLES.md for complete implementation)
```
**Got:** Alerts sent to Slack/PagerDuty when drift detected, with severity based on drift share and critical feature involvement.
**If fail:** Test webhook URLs with curl first, verify PagerDuty integration key has correct permissions, check firewall rules for outbound HTTPS, implement retry logic for transient network failures.
### Step 6: Schedule Monitoring Jobs
Automate drift detection to run on schedule (daily or weekly).
```python
# monitoring/scheduler.py
import schedule
import time
import logging
from datetime import datetime, timedelta
import pandas as pd
logging.basicConfig(
# ... (see EXAMPLES.md for complete implementation)
```
Alternatively, use cron:
```bash
# Add to crontab (crontab -e)
# Run daily at 2 AM
0 2 * * * cd /path/to/monitoring && /path/to/venv/bin/python scheduler.py >> logs/cron.log 2>&1
```
Or use Airflow DAG:
```python
# airflow/dags/drift_monitoring_dag.py
from airflow import DAG
from airflow.operators.python import PythonOperator
from datetime import datetime, timedelta
default_args = {
'owner': 'ml-team',
'depends_on_past': False,
# ... (see EXAMPLES.md for complete implementation)
```
**Got:** Monitoring runs automatically on schedule, generates reports, sends alerts only when drift exceeds thresholds, logs all activity.
**If fail:** Check scheduler process is running (`ps aux | grep scheduler`), verify cron service is active, ensure data sources are accessible, review logs for exceptions, set up dead man's switch alert if job does not run.
## Validation
- [ ] PSI and KS test calculations produce expected values for known drift scenarios
- [ ] Evidently HTML reports render correctly and show distribution overlays
- [ ] Critical feature drift triggers alerts immediately
- [ ] Concept drift detector identifies performance degradation within 3 days
- [ ] Alerts delivered to all configured channels (Slack, email, PagerDuty)
- [ ] Scheduled job runs without manual intervention for 7+ days
- [ ] False positive rate < 5% (tune thresholds if higher)
- [ ] Drift detection completes in < 5 minutes for 1M rows
## Pitfalls
- **Stale reference data**: Update reference dataset quarterly or after model retraining to reflect natural data evolution
- **Sample size mismatch**: Ensure current and reference datasets have similar sizes (>1000 rows each) for reliable statistics
- **Missing ground truth**: Concept drift requires labels; implement a delayed labeling pipeline if real-time labels are unavailable
- **Seasonality confusion**: Weekly/monthly patterns may trigger false positives; use time-aligned reference windows or deseasonalize features
- **Alert fatigue**: Start with high thresholds and gradually lower them based on actual model retraining cadence
- **Ignoring data quality drift**: Monitor missing values, outliers, and encoding errors separately from distribution drift
- **Over-reliance on aggregate metrics**: Per-feature analysis is crucial; aggregate drift may mask critical individual feature shifts
- **Neglecting prediction distribution**: Even without ground truth, sudden prediction distribution shifts signal issues
## Related Skills
- `detect-anomalies-aiops` - Time series anomaly detection for operational metrics
- `deploy-ml-model-serving` - Model deployment patterns and versioning
- `setup-prometheus-monitoring` - Infrastructure metrics collection
- `review-data-analysis` - Statistical analysis validation and peer reviewRelated Skills
setup-prometheus-monitoring
Configure Prometheus for time-series metrics collection, including scrape configurations, service discovery, recording rules, and federation patterns for multi-cluster deployments. Use when setting up centralized metrics collection for microservices, implementing time-series monitoring for application and infrastructure, establishing a foundation for SLO/SLI tracking and alerting, or migrating from legacy monitoring solutions to a modern observability stack.
run-ab-test-models
Design and execute A/B tests for ML models in production using traffic splitting, statistical significance testing, and canary/shadow deployment. Measure performance differences and make data-driven rollout decisions. Use to validate a new model before full rollout, compare candidate models from different algorithms, measure business metric impact of model changes, or meet regulatory gradual rollout requirements.
register-ml-model
Register trained models in MLflow Model Registry with version control, implement stage transitions (Staging, Production, Archived) with approval workflows, and manage model lineage with comprehensive metadata and deployment tracking. Use when promoting a trained model from experimentation to production, managing multiple model versions across development stages, implementing approval workflows for governance, rolling back to previous versions, or auditing model changes for compliance.
prepare-print-model
Export and optimize 3D models for FDM/SLA printing including STL/3MF export, mesh integrity verification, wall thickness checking, support generation, and slicing. Use when exporting from CAD or modeling software for 3D printing, verifying STL/3MF files are printable before slicing, troubleshooting models that fail to slice correctly, optimizing part orientation for strength or surface finish, or converting between model formats while preserving printability.
monitor-data-integrity
Design and operate a data integrity monitoring programme based on ALCOA+ principles. Covers detective controls, audit trail review schedules, anomaly detection patterns (off-hours activity, sequential modifications, bulk changes), metrics dashboards, investigation triggers, and escalation matrix definition. Use when establishing a data integrity monitoring programme for GxP systems, preparing for inspections where data integrity is a focus area, after a data integrity incident requiring enhanced monitoring, or when implementing MHRA, WHO, or PIC/S guidance.
monitor-binary-version-baselines
Establish and maintain longitudinal baselines of CLI binary contents across versions. Covers marker selection by category (API / identity / config / telemetry / flag / function), weighted scoring, threshold-based system-presence detection, and per-version baseline records. Use when tracking a feature's lifecycle across releases, when probing for dark-launched or removed capabilities, or when verifying that a scanning tool still catches known-good markers on old binaries.
model-markov-chain
Build and analyze discrete or continuous Markov chains including transition matrix construction, state classification, stationary distribution computation, and mean first passage times. Use when modeling a memoryless system with observed transition counts or rates, computing long-run steady-state probabilities, determining expected hitting times or absorption probabilities, classifying states as transient or recurrent, or building a foundation for hidden Markov models or reinforcement learning MDPs.
fit-hidden-markov-model
Fit hidden Markov models using the Baum-Welch (EM) algorithm with model selection, Viterbi decoding for state sequences, and forward-backward probabilities. Use when observations are generated by unobservable latent states, you need to segment a time series into latent regimes (market regimes, speech phonemes, biological sequences), compute sequence probabilities, decode the most likely hidden state path, or compare models with different numbers of hidden states.
fit-drift-diffusion-model
Fit cognitive drift-diffusion models (Ratcliff DDM) to reaction time and accuracy data with parameter estimation (drift rate, boundary separation, non-decision time), model comparison, and parameter recovery validation. Use when modeling binary decision-making with reaction time data, estimating cognitive parameters from experimental data, comparing sequential sampling model variants, or decomposing speed-accuracy tradeoff effects into latent cognitive components.
deploy-ml-model-serving
Deploy machine learning models to production serving infrastructure using MLflow, BentoML, or Seldon Core with REST/gRPC endpoints, implement autoscaling, monitoring, and A/B testing capabilities for high-performance model inference at scale. Use when deploying trained models for real-time inference, setting up REST or gRPC prediction APIs, implementing autoscaling for variable load, running A/B tests between model versions, or migrating from batch to real-time inference.
deploy-edge-ai-model
Deploy machine learning models to edge devices using Google AI Edge Gallery, TensorFlow Lite, ONNX Runtime, and MediaPipe. Covers model quantization (INT8/INT4), on-device inference with Gemma 4 models, Android/iOS deployment via AI Edge Gallery, hardware delegate selection (GPU/NPU/DSP), and performance benchmarking on constrained devices. Use when deploying models to mobile phones, IoT devices, or embedded systems where cloud inference is impractical due to latency, cost, or connectivity constraints.
analyze-generative-diffusion-model
Analyze pre-trained generative diffusion models (Stable Diffusion, DALL-E, Flux) by computing quality metrics (FID, IS, CLIP score, precision/recall), inspecting noise schedules, extracting and visualizing attention maps, and probing latent spaces. Use when evaluating a pre-trained generative diffusion model's output quality, comparing noise schedule variants, analyzing cross-attention patterns for text-conditioned generation, interpolating between latent codes, or detecting out-of-distribution inputs.