monitor-model-drift
정보
이 Claude Skill은 Evidently AI와 통계적 검정(PSI, KS)을 활용하여 데이터 드리프트와 컨셉 드리프트를 탐지하는 프로덕션 ML 모델 모니터링을 구현합니다. 성능 저하를 조기에 발견하기 위해 자동화된 경고 및 보고 워크플로우를 설정합니다. 모델의 성능이 설명할 수 없이 하락하거나, 데이터 분포가 변화했을 때, 또는 규제 모니터링이 필요할 때 사용하세요.
빠른 설치
Claude Code
추천npx skills add pjt222/agent-almanac -a claude-code/plugin add https://github.com/pjt222/agent-almanacgit clone https://github.com/pjt222/agent-almanac.git ~/.claude/skills/monitor-model-driftClaude Code에서 이 명령을 복사하여 붙여넣어 스킬을 설치하세요
문서
Monitor Model Drift
See Extended Examples 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.
# 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:
# 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.
# 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.
# 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).
# 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).
# 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).
# 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:
# 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:
# 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 metricsdeploy-ml-model-serving- Model deployment patterns and versioningsetup-prometheus-monitoring- Infrastructure metrics collectionreview-data-analysis- Statistical analysis validation and peer review
GitHub 저장소
연관 스킬
evaluating-llms-harness
테스팅이 Claude Skill은 MMLU, GSM8K를 포함한 60개 이상의 표준화된 학술 과제에서 LLM 성능을 벤치마크하기 위해 lm-evaluation-harness를 실행합니다. 개발자들이 모델 품질을 비교하고, 학습 진행 상황을 추적하거나 학술 결과를 보고할 수 있도록 설계되었습니다. 이 도구는 HuggingFace와 vLLM 모델을 포함한 다양한 백엔드를 지원합니다.
cloudflare-cron-triggers
테스팅이 스킬은 cron 표현식을 사용하여 Worker를 스케줄링하기 위한 Cloudflare Cron Triggers 구현에 관한 포괄적인 지식을 제공합니다. 주기적 작업, 유지보수 작업, 자동화된 워크플로우 설정 방법을 다루며, 잘못된 cron 표현식이나 시간대 문제 같은 일반적인 이슈들을 해결하는 방법을 포함합니다. 개발자들은 이를 통해 스케줄된 핸들러 구성, cron 트리거 테스트, Workflows 및 Green Compute와의 연동 작업을 수행할 수 있습니다.
webapp-testing
테스팅이 Claude Skill은 Python 스크립트를 통해 로컬 웹 애플리케이션을 테스트하기 위한 Playwright 기반 툴킷을 제공합니다. 프론트엔드 검증, UI 디버깅, 스크린샷 캡처, 로그 확인 기능을 지원하며 서버 라이프사이클을 관리합니다. 브라우저 자동화 작업에 사용하되 컨텍스트 오염을 방지하기 위해 소스 코드를 읽지 않고 스크립트를 직접 실행하세요.
finishing-a-development-branch
테스팅이 스킬은 테스트 통과를 확인한 후 체계적인 통합 옵션을 제시하여 개발자가 완성된 작업을 마무리하도록 돕습니다. 구현이 완료된 후 머지, PR 생성, 브랜치 정리와 같은 워크플로우를 안내합니다. 코드가 준비되고 테스트가 완료되었을 때 개발 프로세스를 체계적으로 마무리하기 위해 사용하세요.
