基于Python的模型预测误差实时监控脚本
监控核心指标
本监控系统重点跟踪以下三个关键指标:
- 均方误差(MSE):
mse = np.mean((y_true - y_pred) ** 2) - 平均绝对误差(MAE):
mae = np.mean(np.abs(y_true - y_pred)) - 预测偏差率:
bias = np.mean(y_pred - y_true) / np.mean(y_true) * 100
实现方案
创建监控脚本model_monitor.py:
import numpy as np
import time
from datetime import datetime
import smtplib
from email.mime.text import MIMEText
# 预测误差计算函数
def calculate_errors(y_true, y_pred):
mse = np.mean((y_true - y_pred) ** 2)
mae = np.mean(np.abs(y_true - y_pred))
bias = np.mean(y_pred - y_true) / np.mean(y_true) * 100
return {
'mse': mse,
'mae': mae,
'bias': bias,
'timestamp': datetime.now().isoformat()
}
# 告警阈值配置
ALERT_THRESHOLDS = {
'mse': 0.1, # MSE超过0.1触发告警
'mae': 0.05, # MAE超过0.05触发告警
'bias': 2.0 # 偏差率超过2%触发告警
}
class ModelMonitor:
def __init__(self):
self.history = []
def check_and_alert(self, errors):
for metric, threshold in ALERT_THRESHOLDS.items():
if errors[metric] > threshold:
self.send_alert(metric, errors[metric], threshold)
print(f'⚠️ 告警:{metric}超出阈值')
def send_alert(self, metric, current_value, threshold):
# 简单邮件告警实现
msg = MIMEText(f'模型预测异常:{metric}={current_value:.4f}, 阈值={threshold}')
msg['Subject'] = f'模型监控告警 - {metric}'
# 此处配置邮件服务器信息
# 定时执行监控
monitor = ModelMonitor()
while True:
# 模拟获取预测结果
y_true = np.random.randn(100)
y_pred = y_true + np.random.randn(100) * 0.1
errors = calculate_errors(y_true, y_pred)
monitor.check_and_alert(errors)
time.sleep(300) # 每5分钟检查一次
部署建议
将脚本部署为系统服务,使用systemd或supervisor进行进程管理。配置日志轮转避免磁盘占满。

讨论