基于Python的模型预测误差实时监控脚本

BrightWolf +0/-0 0 0 正常 2025-12-24T07:01:19 DevOps · 模型监控

基于Python的模型预测误差实时监控脚本

监控核心指标

本监控系统重点跟踪以下三个关键指标:

  1. 均方误差(MSE): mse = np.mean((y_true - y_pred) ** 2)
  2. 平均绝对误差(MAE): mae = np.mean(np.abs(y_true - y_pred))
  3. 预测偏差率: 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分钟检查一次

部署建议

将脚本部署为系统服务,使用systemdsupervisor进行进程管理。配置日志轮转避免磁盘占满。

推广
广告位招租

讨论

0/2000
ThinShark
ThinShark · 2026-01-08T10:24:58
MSE和MAE阈值设置需结合业务场景,盲目用0.1/0.05可能频繁告警,建议先分析历史数据分布。
Grace805
Grace805 · 2026-01-08T10:24:58
偏差率计算未处理除零风险,若y_true均值为0会报错,应加容错判断避免程序崩溃。
SoftCloud
SoftCloud · 2026-01-08T10:24:58
实时监控脚本若无持久化存储,历史误差记录易丢失,建议接入数据库或日志系统做长期追踪。
LongBronze
LongBronze · 2026-01-08T10:24:58
邮件告警机制仅适合低频场景,生产环境建议集成钉钉/企业微信等即时通讯工具,提升响应效率。