返回技能列表

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 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 + alert on data drift + concept drift in prod ML models via statistical tests + automated monitoring.

Use When

  • Prod ML models w/ unexplained perf degradation
  • New data distributions differ from training
  • Seasonal/temporal shifts in input features
  • Need proactive alerts before business metrics impacted
  • Regulatory: SR 11-7, EU AI Act
  • Multi model versions deployed → drift comparison

In

  • Required: Prod predictions + features (last 30-90 days)
  • Required: Reference dataset (training or validation)
  • Required: Ground truth labels (may be delayed)
  • Optional: Feature importance / SHAP values
  • Optional: Business metric thresholds for alerting
  • Optional: Historical drift reports for trend

Do

Step 1: Install + Config Evidently AI

Set up monitoring framework + deps.

# 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}

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

→ Config created w/ thresholds matching model tolerance.

If err: start conservative (PSI > 0.2, KS p-value < 0.01) + tune by false positive rate.

Step 2: Data Drift Detection

Drift detection pipeline w/ 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, JSON report w/ per-feature stats, drifted features identified.

If err: check missing values (impute/drop), reference + current data same cols, data types match.

Step 3: Generate Evidently Reports

Visual HTML reports for human review + 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 in monitoring/reports/, browser-viewable w/ interactive charts showing distribution comparisons.

If err: write perms to output dir, Evidently version ≥ 0.4.0, data frames have ≥100 rows recommended.

Step 4: Concept Drift Detection

Monitor pred perf → detect concept drift (relationship features-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)

→ Perf monitoring detects when accuracy/AUC drops below threshold → potential concept drift.

If err: ground truth labels available (may need delayed validation batch), prediction scores calibrated (0-1 range classification), no label leakage in features.

Step 5: Automated Alerting

Integrate w/ 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 on drift, severity by drift share + critical feature involvement.

If err: test webhook URLs w/ curl, PagerDuty integration key has perms, firewall outbound HTTPS, retry logic for transient failures.

Step 6: Schedule Monitoring Jobs

Automate drift detection on schedule (daily/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)

Cron alternative:

# 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 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 auto on schedule, reports generated, alerts only when drift exceeds thresholds, all activity logged.

If err: scheduler process running (ps aux | grep scheduler), cron service active, data sources accessible, review logs for exceptions, dead man's switch alert if job doesn't run.

Check

  • PSI + KS test calculations match expected values for known drift scenarios
  • Evidently HTML reports render correctly + show distribution overlays
  • Critical feature drift → immediate alerts
  • Concept drift detector identifies perf degradation within 3 days
  • Alerts delivered all configured channels (Slack, email, PagerDuty)
  • Scheduled job runs w/o manual intervention 7+ days
  • False positive rate < 5% (tune thresholds if higher)
  • Drift detection completes < 5min for 1M rows

Traps

  • Stale reference data: Update quarterly or after retraining to reflect natural data evolution
  • Sample size mismatch: Current + reference datasets similar sizes (>1000 rows each) for reliable stats
  • Missing ground truth: Concept drift needs labels; implement delayed labeling if real-time unavailable
  • Seasonality confusion: Weekly/monthly patterns → false positives; time-aligned reference windows or deseasonalize features
  • Alert fatigue: Start high thresholds, lower based on actual retraining cadence
  • Ignore data quality drift: Monitor missing values, outliers, encoding errors separately from distribution drift
  • Over-reliance on aggregate: Per-feature analysis crucial; aggregate drift may mask individual feature shifts
  • Neglect prediction distribution: Even w/o ground truth, sudden prediction shifts signal issues

  • detect-anomalies-aiops — time series anomaly detection for operational metrics
  • deploy-ml-model-serving — model deployment patterns + versioning
  • setup-prometheus-monitoring — infrastructure metrics collection
  • review-data-analysis — statistical analysis validation + peer review

GitHub 仓库

pjt222/agent-almanac
路径: i18n/caveman-ultra/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或清理等结构化选项。核心价值在于确保代码质量的同时,标准化分支收尾流程。

查看技能