返回技能列表

monitor-model-drift

pjt222
更新于 Yesterday
3 次查看
17
2
17
在 GitHub 上查看
测试aitestingautomationdesigndata

关于

This skill detects data and concept drift in production ML models using Evidently AI and statistical tests like PSI and KS. It sets up automated monitoring, alerting, and reporting workflows to catch performance degradation early. Use it when models degrade unexpectedly, data distributions shift, or for regulatory compliance.

快速安装

Claude Code

推荐
主要方式
npx skills add pjt222/agent-almanac -a claude-code
插件命令备选方式
/plugin add https://github.com/pjt222/agent-almanac
Git 克隆备选方式
git clone https://github.com/pjt222/agent-almanac.git ~/.claude/skills/monitor-model-drift

在 Claude 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.

适用场景

  • Production ML models experiencing 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

输入

  • 必需: Production model predictions and features (last 30-90 days)
  • 必需: Reference dataset (training or validation data)
  • 必需: Ground truth labels (may be delayed)
  • 可选: Feature importance scores or SHAP values
  • 可选: Business metric thresholds for alerting
  • 可选: Historical drift reports for trend analysis

步骤

第 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)

预期结果: Configuration file created with thresholds matching your model's tolerance.

失败处理: Start with conservative thresholds (PSI > 0.2, KS p-value < 0.01) and tune based on false positive rate.

第 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)

预期结果: Drift detection runs successfully, produces JSON report with per-feature statistics, and identifies drifted features.

失败处理: Check for missing values (impute or drop), ensure reference and current data have same columns, verify data types match between datasets.

第 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)

预期结果: HTML reports generated in monitoring/reports/, viewable in browser with interactive charts showing distribution comparisons.

失败处理: Verify write permissions to output directory, check that Evidently version is >= 0.4.0, ensure data frames have sufficient rows (>100 recommended).

第 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)

预期结果: Performance monitoring detects when model accuracy/AUC drops below threshold, signaling potential concept drift.

失败处理: Ensure ground truth labels are available (may require delayed validation batch job), verify prediction scores are properly calibrated (0-1 range for classification), check for label leakage in features.

第 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)

预期结果: Alerts sent to Slack/PagerDuty when drift detected, with severity based on drift share and critical feature involvement.

失败处理: 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.

第 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)

预期结果: Monitoring runs automatically on schedule, generates reports, sends alerts only when drift exceeds thresholds, logs all activity.

失败处理: 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 doesn't run.

验证清单

  • 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

常见问题

  • 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 delayed labeling pipeline if real-time labels 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 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 crucial; aggregate drift may mask critical individual feature shifts
  • Neglecting prediction distribution: Even without ground truth, sudden prediction distribution shifts signal issues

相关技能

  • 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 review

GitHub 仓库

pjt222/agent-almanac
路径: i18n/zh-CN/skills/monitor-model-drift
0
agentsagentskillsai-assisted-developmentclaude-codeskillsteams

相关推荐技能

evaluating-llms-harness

测试

该Skill通过60+个学术基准测试(如MMLU、GSM8K等)评估大语言模型质量,适用于模型对比、学术研究及训练进度追踪。它支持HuggingFace、vLLM和API接口,被EleutherAI等行业领先机构广泛采用。开发者可通过简单命令行快速对模型进行多任务批量评估。

查看技能

cloudflare-cron-triggers

测试

这个Claude Skill提供了关于Cloudflare Cron Triggers的完整知识库,用于通过cron表达式定时执行Workers。它支持配置周期性任务、维护作业和自动化工作流,并能处理常见的cron触发错误。开发者可以用它来设置定时任务、测试cron处理器,并集成Workflows和Green Compute功能。

查看技能

webapp-testing

测试

该Skill为开发者提供了基于Playwright的本地Web应用测试工具集,支持自动化测试前端功能、调试UI行为、捕获屏幕截图和查看浏览器日志。它包含管理服务器生命周期的辅助脚本,可直接作为黑盒工具运行而无需阅读源码。适用于需要快速验证本地Web应用界面和交互功能的开发场景。

查看技能

finishing-a-development-branch

测试

这个Skill用于开发分支完成后的集成决策,当代码实现完成且测试通过时,它会引导开发者选择合适的工作流。它首先验证测试状态,然后提供合并、创建PR或清理等结构化选项。核心价值在于确保代码质量的同时,标准化分支收尾流程。

查看技能