Model Monitoring
Skill files3 files

scripts/

templates/

SKILL.md399 lines
1
---
2
name: Model Monitoring
3
description: Monitor model performance, detect data drift, concept drift, and anomalies in production using Prometheus, Grafana, and MLflow
4
---
5
6
# Model Monitoring
7
8
## Overview
9
10
Monitoring deployed machine learning models ensures they continue to perform well in production, detecting data drift, concept drift, and performance degradation.
11
12
## When to Use
13
14
- When models are deployed in production environments serving real users
15
- When detecting data drift or concept drift in input features
16
- When tracking model performance metrics over time
17
- When ensuring model reliability, accuracy, and operational health
18
- When implementing ML observability and alerting systems
19
- When establishing thresholds for model retraining or intervention
20
21
## Monitoring Components
22
23
- **Performance Metrics**: Accuracy, latency, throughput
24
- **Data Drift**: Distribution changes in input features
25
- **Concept Drift**: Changes in target variable relationships
26
- **Output Drift**: Changes in prediction distribution
27
- **Feature Drift**: Individual feature distribution changes
28
- **Anomaly Detection**: Unusual samples in production
29
30
## Monitoring Tools
31
32
- **Prometheus**: Metrics collection and storage
33
- **Grafana**: Visualization and dashboarding
34
- **MLflow**: Model tracking and registry
35
- **TensorFlow Data Validation**: Data statistics
36
- **Evidently**: Drift detection and monitoring
37
- **Great Expectations**: Data quality assertions
38
39
## Python Implementation
40
41
```python
42
import numpy as np
43
import pandas as pd
44
import matplotlib.pyplot as plt
45
from sklearn.ensemble import RandomForestClassifier
46
from sklearn.preprocessing import StandardScaler
47
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
48
from scipy import stats
49
import json
50
from datetime import datetime, timedelta
51
import logging
52
53
logging.basicConfig(level=logging.INFO)
54
logger = logging.getLogger(__name__)
55
56
print("=== 1. Production Monitoring System ===")
57
58
class ModelMonitoringSystem:
59
def __init__(self, model, scaler, baseline_data, baseline_targets):
60
self.model = model
61
self.scaler = scaler
62
self.baseline_data = baseline_data
63
self.baseline_targets = baseline_targets
64
self.baseline_mean = baseline_data.mean(axis=0)
65
self.baseline_std = baseline_data.std(axis=0)
66
self.baseline_predictions = model.predict(baseline_data)
67
68
self.metrics_history = []
69
self.drift_alerts = []
70
self.performance_history = []
71
72
def log_predictions(self, X, y_true, y_pred):
73
"""Log predictions and compute metrics"""
74
timestamp = datetime.now()
75
76
# Compute metrics
77
accuracy = accuracy_score(y_true, y_pred)
78
precision = precision_score(y_true, y_pred, average='weighted', zero_division=0)
79
recall = recall_score(y_true, y_pred, average='weighted', zero_division=0)
80
f1 = f1_score(y_true, y_pred, average='weighted', zero_division=0)
81
82
metric_record = {
83
'timestamp': timestamp,
84
'accuracy': accuracy,
85
'precision': precision,
86
'recall': recall,
87
'f1': f1,
88
'n_samples': len(X)
89
}
90
91
self.metrics_history.append(metric_record)
92
return metric_record
93
94
def detect_data_drift(self, X_new):
95
"""Detect data drift using Kolmogorov-Smirnov test"""
96
drift_detected = False
97
drift_features = []
98
99
for feature_idx in range(X_new.shape[1]):
100
baseline_feature = self.baseline_data[:, feature_idx]
101
new_feature = X_new[:, feature_idx]
102
103
# KS Test
104
ks_statistic, p_value = stats.ks_2samp(baseline_feature, new_feature)
105
106
if p_value < 0.05: # Significant drift detected
107
drift_detected = True
108
drift_features.append({
109
'feature_index': feature_idx,
110
'ks_statistic': float(ks_statistic),
111
'p_value': float(p_value)
112
})
113
114
if drift_detected:
115
alert = {
116
'timestamp': datetime.now(),
117
'type': 'data_drift',
118
'severity': 'high',
119
'drifted_features': drift_features,
120
'n_drifted': len(drift_features)
121
}
122
self.drift_alerts.append(alert)
123
logger.warning(f"Data drift detected in {len(drift_features)} features")
124
125
return drift_detected, drift_features
126
127
def detect_output_drift(self, y_pred_new):
128
"""Detect drift in model predictions"""
129
baseline_pred_dist = pd.Series(self.baseline_predictions).value_counts(normalize=True)
130
new_pred_dist = pd.Series(y_pred_new).value_counts(normalize=True)
131
132
# Compare distributions
133
classes = set(baseline_pred_dist.index) | set(new_pred_dist.index)
134
chi2_stat = 0
135
136
for cls in classes:
137
exp = baseline_pred_dist.get(cls, 0.01)
138
obs = new_pred_dist.get(cls, 0.01)
139
chi2_stat += (obs - exp) ** 2 / max(exp, 0.01)
140
141
p_value = 1 - stats.chi2.cdf(chi2_stat, len(classes) - 1)
142
143
if p_value < 0.05:
144
alert = {
145
'timestamp': datetime.now(),
146
'type': 'output_drift',
147
'severity': 'medium',
148
'chi2_statistic': float(chi2_stat),
149
'p_value': float(p_value)
150
}
151
self.drift_alerts.append(alert)
152
logger.warning("Output drift detected in predictions")
153
return True
154
155
return False
156
157
def detect_performance_degradation(self, y_true, y_pred):
158
"""Detect if model performance has degraded"""
159
current_accuracy = accuracy_score(y_true, y_pred)
160
baseline_accuracy = accuracy_score(self.baseline_targets, self.baseline_predictions)
161
162
degradation_threshold = 0.05 # 5% drop
163
degradation = baseline_accuracy - current_accuracy
164
165
if degradation > degradation_threshold:
166
alert = {
167
'timestamp': datetime.now(),
168
'type': 'performance_degradation',
169
'severity': 'critical',
170
'baseline_accuracy': float(baseline_accuracy),
171
'current_accuracy': float(current_accuracy),
172
'degradation': float(degradation)
173
}
174
self.drift_alerts.append(alert)
175
logger.error("Performance degradation detected")
176
return True
177
178
return False
179
180
def get_monitoring_report(self):
181
"""Generate monitoring report"""
182
if not self.metrics_history:
183
return {}
184
185
metrics_df = pd.DataFrame(self.metrics_history)
186
187
return {
188
'monitoring_period': {
189
'start': self.metrics_history[0]['timestamp'].isoformat(),
190
'end': self.metrics_history[-1]['timestamp'].isoformat(),
191
'n_batches': len(self.metrics_history)
192
},
193
'performance_summary': {
194
'avg_accuracy': float(metrics_df['accuracy'].mean()),
195
'min_accuracy': float(metrics_df['accuracy'].min()),
196
'max_accuracy': float(metrics_df['accuracy'].max()),
197
'std_accuracy': float(metrics_df['accuracy'].std()),
198
'avg_f1': float(metrics_df['f1'].mean())
199
},
200
'drift_summary': {
201
'total_alerts': len(self.drift_alerts),
202
'data_drift_alerts': sum(1 for a in self.drift_alerts if a['type'] == 'data_drift'),
203
'output_drift_alerts': sum(1 for a in self.drift_alerts if a['type'] == 'output_drift'),
204
'performance_alerts': sum(1 for a in self.drift_alerts if a['type'] == 'performance_degradation')
205
},
206
'alerts': self.drift_alerts[-10:] # Last 10 alerts
207
}
208
209
print("Monitoring system initialized")
210
211
# 2. Create baseline model
212
print("\n=== 2. Train Baseline Model ===")
213
214
from sklearn.datasets import make_classification
215
216
# Create baseline data
217
X_baseline, y_baseline = make_classification(n_samples=1000, n_features=20,
218
n_informative=15, random_state=42)
219
scaler = StandardScaler()
220
X_baseline_scaled = scaler.fit_transform(X_baseline)
221
222
model = RandomForestClassifier(n_estimators=100, random_state=42)
223
model.fit(X_baseline_scaled, y_baseline)
224
225
print(f"Baseline model trained on {len(X_baseline)} samples")
226
227
# 3. Initialize monitoring
228
monitor = ModelMonitoringSystem(model, scaler, X_baseline_scaled, y_baseline)
229
230
# 4. Simulate production data and monitoring
231
print("\n=== 3. Production Monitoring Simulation ===")
232
233
# Simulate normal production data
234
X_prod_normal = np.random.randn(500, 20) * 0.5
235
X_prod_normal_scaled = scaler.transform(X_prod_normal)
236
y_pred_normal = model.predict(X_prod_normal_scaled)
237
y_true_normal = np.random.randint(0, 2, 500)
238
239
metrics_normal = monitor.log_predictions(X_prod_normal_scaled, y_true_normal, y_pred_normal)
240
print(f"Normal production batch - Accuracy: {metrics_normal['accuracy']:.4f}")
241
242
# Simulate drifted data
243
X_prod_drift = np.random.randn(500, 20) * 2.0 # Different distribution
244
X_prod_drift_scaled = scaler.transform(X_prod_drift)
245
y_pred_drift = model.predict(X_prod_drift_scaled)
246
y_true_drift = np.random.randint(0, 2, 500)
247
248
metrics_drift = monitor.log_predictions(X_prod_drift_scaled, y_true_drift, y_pred_drift)
249
drift_detected, drift_features = monitor.detect_data_drift(X_prod_drift_scaled)
250
print(f"Drifted production batch - Accuracy: {metrics_drift['accuracy']:.4f}")
251
print(f"Data drift detected: {drift_detected}")
252
253
# Check performance degradation
254
perf_degradation = monitor.detect_performance_degradation(y_true_drift, y_pred_drift)
255
print(f"Performance degradation: {perf_degradation}")
256
257
# 5. Prometheus metrics export
258
print("\n=== 4. Prometheus Metrics Format ===")
259
260
prometheus_metrics = f"""
261
# HELP model_accuracy Model accuracy score
262
# TYPE model_accuracy gauge
263
model_accuracy{"{timestamp='2024-01-01'}"} {metrics_normal['accuracy']:.4f}
264
265
# HELP model_f1_score Model F1 score
266
# TYPE model_f1_score gauge
267
model_f1_score{"{timestamp='2024-01-01'}"} {metrics_normal['f1']:.4f}
268
269
# HELP model_predictions_total Total predictions made
270
# TYPE model_predictions_total counter
271
model_predictions_total 5000
272
273
# HELP model_drift_detected Data drift detection flag
274
# TYPE model_drift_detected gauge
275
model_drift_detected {int(drift_detected)}
276
277
# HELP model_latency_seconds Prediction latency in seconds
278
# TYPE model_latency_seconds histogram
279
model_latency_seconds_bucket{{le="0.01"}} 100
280
model_latency_seconds_bucket{{le="0.05"}} 450
281
model_latency_seconds_bucket{{le="0.1"}} 500
282
"""
283
284
print("Prometheus metrics:")
285
print(prometheus_metrics)
286
287
# 6. Grafana dashboard JSON
288
print("\n=== 5. Grafana Dashboard Configuration ===")
289
290
grafana_dashboard = {
291
'title': 'ML Model Monitoring Dashboard',
292
'panels': [
293
{
294
'title': 'Model Accuracy',
295
'targets': [{'metric': 'model_accuracy'}],
296
'type': 'graph'
297
},
298
{
299
'title': 'Data Drift Alerts',
300
'targets': [{'metric': 'model_drift_detected'}],
301
'type': 'stat'
302
},
303
{
304
'title': 'Prediction Latency',
305
'targets': [{'metric': 'model_latency_seconds'}],
306
'type': 'graph'
307
},
308
{
309
'title': 'Feature Distributions',
310
'targets': [{'metric': 'feature_distribution_change'}],
311
'type': 'heatmap'
312
}
313
]
314
}
315
316
print("Grafana dashboard configured with 4 panels")
317
318
# 7. Visualization
319
print("\n=== 6. Monitoring Visualization ===")
320
321
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
322
323
# Performance over time
324
metrics_df = pd.DataFrame(monitor.metrics_history)
325
axes[0, 0].plot(range(len(metrics_df)), metrics_df['accuracy'], marker='o', label='Accuracy')
326
axes[0, 0].axhline(y=metrics_df['accuracy'].mean(), color='r', linestyle='--', label='Mean')
327
axes[0, 0].set_xlabel('Batch')
328
axes[0, 0].set_ylabel('Accuracy')
329
axes[0, 0].set_title('Model Accuracy Over Time')
330
axes[0, 0].legend()
331
axes[0, 0].grid(True, alpha=0.3)
332
333
# Precision, Recall, F1
334
axes[0, 1].plot(range(len(metrics_df)), metrics_df['precision'], label='Precision', marker='s')
335
axes[0, 1].plot(range(len(metrics_df)), metrics_df['recall'], label='Recall', marker='^')
336
axes[0, 1].plot(range(len(metrics_df)), metrics_df['f1'], label='F1', marker='d')
337
axes[0, 1].set_xlabel('Batch')
338
axes[0, 1].set_ylabel('Score')
339
axes[0, 1].set_title('Performance Metrics Over Time')
340
axes[0, 1].legend()
341
axes[0, 1].grid(True, alpha=0.3)
342
343
# Feature distributions (baseline vs current)
344
feature_stats = pd.DataFrame({
345
'Baseline Mean': np.mean(X_baseline, axis=0)[:10],
346
'Current Mean': np.mean(X_prod_drift, axis=0)[:10]
347
})
348
axes[1, 0].bar(range(len(feature_stats)), feature_stats['Baseline Mean'], alpha=0.7, label='Baseline')
349
axes[1, 0].bar(range(len(feature_stats)), feature_stats['Current Mean'], alpha=0.7, label='Current')
350
axes[1, 0].set_xlabel('Feature')
351
axes[1, 0].set_ylabel('Mean Value')
352
axes[1, 0].set_title('Feature Distribution Drift (First 10)')
353
axes[1, 0].legend()
354
axes[1, 0].grid(True, alpha=0.3, axis='y')
355
356
# Alerts over time
357
alert_types = [a['type'] for a in monitor.drift_alerts]
358
alert_counts = pd.Series(alert_types).value_counts()
359
axes[1, 1].barh(alert_counts.index, alert_counts.values, color=['red', 'orange', 'yellow'])
360
axes[1, 1].set_xlabel('Count')
361
axes[1, 1].set_title('Alert Types Distribution')
362
axes[1, 1].grid(True, alpha=0.3, axis='x')
363
364
plt.tight_layout()
365
plt.savefig('model_monitoring_dashboard.png', dpi=100, bbox_inches='tight')
366
print("\nMonitoring dashboard saved as 'model_monitoring_dashboard.png'")
367
368
# 8. Report generation
369
report = monitor.get_monitoring_report()
370
print("\n=== 7. Monitoring Report ===")
371
print(json.dumps(report, indent=2, default=str))
372
373
print("\nModel monitoring system setup completed!")
374
```
375
376
## Drift Detection Techniques
377
378
- **Kolmogorov-Smirnov Test**: Statistical test for distribution change
379
- **Population Stability Index**: Measures feature distribution shifts
380
- **Chi-square Test**: Categorical feature drift
381
- **Wasserstein Distance**: Optimal transport-based distance
382
- **Jensen-Shannon Divergence**: Information-theoretic metric
383
384
## Alert Thresholds
385
386
- **Critical**: >5% accuracy drop, immediate action
387
- **High**: Data drift in 3+ features, investigation needed
388
- **Medium**: Output drift, monitoring increased
389
- **Low**: Single feature drift, log and track
390
391
## Deliverables
392
393
- Monitoring dashboards
394
- Alert configuration
395
- Drift detection reports
396
- Performance degradation analysis
397
- Retraining recommendations
398
- Action playbook
399

© AJ Geddes · MIT · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 13,275 prompts

More by @OpenSourceBuffGuy

See all
Edible Landscape Cake of a City prompt image

Edible Landscape Cake of a City

Makes a macro food photo of a rectangular landscape cake for any city, with edible terrain, fruit lettering of the place name and a tiny sugar landmark.

image-prompt, nano-banana, placeholders, template, conditional-logic, food-photography, baking, landscape, macro, bokeh, photorealistic, natural-light, soft-lighting, text-rendering, typography, cooking, creativity, step-by-step-guide, for-artists, concept-art, miniature, cityscape, travel

Half photo, half black-ink illustration poster prompt image

Half photo, half black-ink illustration poster

Turns an uploaded photo into a 2:3 editorial poster, with the original photograph on top and a minimalist black-ink illustration of its subject below, plus handwritten notes.

image-prompt, poster, reference-image, split-screen, ink-drawing, illustration, minimalist, black-and-white, negative-space, editorial, typography, text-rendering, vertical-format, style-transfer, photography, limited-palette, structured-output, nano-banana, for-artists, for-photographers, for-designers, long-form

Student Feedback Coach prompt image

Student Feedback Coach

Helps teachers write specific, strength-first, growth-oriented feedback on student work, naming one or two highest-leverage improvements and concrete next steps.

system-prompt, act-as, coach, education, k12-education, higher-education, grading, critique, rewriting, for-teachers, for-students, xml-tags, structured-output, guardrails, encouraging, empathetic, template, expert-advice, rubric, iterative-refinement, task-decomposition, long-form

Reviews

Loading reviews…

Discussion

Loading comments…