python
import streamlit as st
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import scipy.stats as stats
from sklearn.calibration import calibration_curve
from sklearn.metrics import brier_score_loss, accuracy_score, log_loss
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
import warnings
warnings.filterwarnings('ignore')
st.set_page_config(page_title="Model Performance Monitoring Hub", layout="wide")
@st.cache_data
def generate_sample_data(n_samples=5000, seed=42):
"""Generate synthetic binary classification data for demo."""
np.random.seed(seed)
n_features = 5
X_ref = np.random.randn(n_samples, n_features)
y_ref = (np.sum(X_ref[:, :2], axis=1) > 0).astype(int) + np.random.binomial(1, 0.1, n_samples)
# Simulate reference predictions (well-calibrated model)
scaler = StandardScaler()
X_ref_scaled = scaler.fit_transform(X_ref)
model_ref = RandomForestClassifier(n_estimators=100, random_state=seed)
model_ref.fit(X_ref_scaled, y_ref)
y_pred_proba_ref = model_ref.predict_proba(X_ref_scaled)[:, 1]
# Current data with drift (shift in feature 0)
X_curr = X_ref.copy()
X_curr[:, 0] += np.random.normal(2, 0.5, n_samples) # Drift in first feature
y_curr = (np.sum(X_curr[:, :2], axis=1) > 0).astype(int) + np.random.binomial(1, 0.1, n_samples)
X_curr_scaled = scaler.transform(X_curr)
y_pred_proba_curr = model_ref.predict_proba(X_curr_scaled)[:, 1]
# Challenger model predictions (Logistic Regression)
model_challenger = LogisticRegression(random_state=seed)
model_challenger.fit(X_curr_scaled, y_curr)
y_pred_proba_challenger = model_challenger.predict_proba(X_curr_scaled)[:, 1]
ref_df = pd.DataFrame(X_ref, columns=[f'feature_{i}' for i in range(n_features)])
ref_df['y_true'] = y_ref
ref_df['y_pred_proba'] = y_pred_proba_ref
ref_df['y_pred'] = (y_pred_proba_ref > 0.5).astype(int)
curr_df = pd.DataFrame(X_curr, columns=[f'feature_{i}' for i in range(n_features)])
curr_df['y_true'] = y_curr
curr_df['y_pred_proba'] = y_pred_proba_curr
curr_df['y_pred'] = (y_pred_proba_curr > 0.5).astype(int)
curr_df['y_pred_challenger_proba'] = y_pred_proba_challenger
curr_df['y_pred_challenger'] = (y_pred_proba_challenger > 0.5).astype(int)
return ref_df, curr_df
def detect_drift(ref_data, curr_data, feature, alpha=0.01):
"""Univariate drift detection using KS test."""
ks_stat, p_value = stats.ks_2samp(ref_data[feature], curr_data[feature])
drift_detected = p_value < alpha
return {'feature': feature, 'ks_stat': ks_stat, 'p_value': p_value, 'drift': drift_detected}
def compute_calibration(y_true, y_proba, n_bins=10):
"""Compute calibration metrics: ECE, Brier Score, Reliability Diagram data."""
fraction_of_positives, mean_predicted_value = calibration_curve(y_true, y_proba, n_bins=n_bins)
ece = np.average(np.abs(mean_predicted_value - fraction_of_positives), weights=np.size(y_true) / n_bins * fraction_of_positives)
brier = brier_score_loss(y_true, y_proba)
return {
'ece': ece,
'brier': brier,
'reliability_x': mean_predicted_value,
'reliability_y': fraction_of_positives
}
def backtest_exceptions(ref_df, curr_df, error_threshold=0.3):
"""Detect backtesting exceptions: large prediction errors."""
ref_errors = np.abs(ref_df['y_pred_proba'] - ref_df['y_true'])
curr_errors = np.abs(curr_df['y_pred_proba'] - curr_df['y_true'])
ref_exceptions = ref_errors > error_threshold
curr_exceptions = curr_errors > error_threshold
return {
'ref_exception_rate': ref_exceptions.mean(),
'curr_exception_rate': curr_exceptions.mean(),
'exception_increase': curr_exceptions.mean() - ref_exceptions.mean() > 0.05,
'curr_exceptions': curr_exceptions.sum()
}
def challenger_comparison(ref_df, curr_df):
"""Compare incumbent vs challenger model."""
incumbent_acc_ref = accuracy_score(ref_df['y_true'], ref_df['y_pred'])
incumbent_acc_curr = accuracy_score(curr_df['y_true'], curr_df['y_pred'])
challenger_acc_curr = accuracy_score(curr_df['y_true'], curr_df['y_pred_challenger'])
incumbent_logloss_curr = log_loss(curr_df['y_true'], curr_df['y_pred_proba'])
challenger_logloss_curr = log_loss(curr_df['y_true'], curr_df['y_pred_challenger_proba'])
challenger_better = challenger_acc_curr > incumbent_acc_curr + 0.02 or challenger_logloss_curr < incumbent_logloss_curr - 0.02
return {
'incumbent_acc_ref': incumbent_acc_ref,
'incumbent_acc_curr': incumbent_acc_curr,
'challenger_acc_curr': challenger_acc_curr,
'challenger_better': challenger_better,
'logloss_improvement': incumbent_logloss_curr - challenger_logloss_curr
}
def check_escalation(drift_issues, cal_degradation, exceptions_high, challenger_better):
"""Aggregate issues for escalation."""
issues = []
if drift_issues > 0:
issues.append("Data drift detected")
if cal_degradation:
issues.append("Calibration degradation")
if exceptions_high:
issues.append("High backtest exceptions")
if challenger_better:
issues.append("Challenger model outperforms incumbent")
severity = "CRITICAL" if len(issues) >= 2 else "WARNING" if issues else "OK"
return severity, issues
# Load data
st.title("🚀 Model Performance Monitoring Hub")
st.markdown("A comprehensive dashboard for monitoring ML model performance: **Drift**, **Calibration**, **Backtesting Exceptions**, **Challenger Models**, and **Escalation**.")
ref_df, curr_df = generate_sample_data()
# Sidebar for controls
st.sidebar.header("Controls")
upload_ref = st.sidebar.file_uploader("Upload Reference Data (CSV)", key="ref")
upload_curr = st.sidebar.file_uploader("Upload Current Data (CSV)", key="curr")
if upload_ref and upload_curr:
ref_df = pd.read_csv(upload_ref)
curr_df = pd.read_csv(upload_curr)
st.sidebar.success("Data uploaded!")
alpha_drift = st.sidebar.slider("Drift Detection Alpha", 0.001, 0.05, 0.01)
error_threshold = st.sidebar.slider("Exception Error Threshold", 0.1, 0.5, 0.3)
tab1, tab2, tab3, tab4, tab5 = st.tabs(["📊 Overview", "🔄 Drift", "⚖️ Calibration", "🧪 Backtesting", "⚔️ Challengers", "🚨 Escalation"])
with tab1:
col1, col2 = st.columns(2)
with col1:
st.metric("Incumbent Accuracy (Ref)", f"{accuracy_score(ref_df['y_true'], ref_df['y_pred']):.3f}")
st.metric("Incumbent Accuracy (Curr)", f"{accuracy_score(curr_df['y_true'], curr_df['y_pred']):.3f}")
with col2:
st.metric("Challenger Accuracy (Curr)", f"{accuracy_score(curr_df['y_true'], curr_df['y_pred_challenger']):.3f}")
st.metric("Dataset Size (Curr)", f"{len(curr_df):,}")
with tab2:
st.subheader("Data Drift Detection (KS Test)")
drift_results = []
for feature in ref_df.columns[:5]: # Assume first 5 are features
result = detect_drift(ref_df, curr_df, feature, alpha_drift)
drift_results.append(result)
drift_df = pd.DataFrame(drift_results)
st.dataframe(drift_df, use_container_width=True)
drift_issues = drift_df['drift'].sum()
col1, col2 = st.columns(2)
col1.metric("Drift Issues", drift_issues)
col2.metric("Max KS Stat", f"{drift_df['ks_stat'].max():.3f}")
fig_drift = px.bar(drift_df, x='feature', y='ks_stat', color='drift', title="Drift by Feature")
st.plotly_chart(fig_drift, use_container_width=True)
with tab3:
st.subheader("Model Calibration")
cal_ref = compute_calibration(ref_df['y_true'], ref_df['y_pred_proba'])
cal_curr = compute_calibration(curr_df['y_true'], curr_df['y_pred_proba'])
st.metric("Brier Score (Ref)", f"{cal_ref['brier']:.3f}")
st.metric("Brier Score (Curr)", f"{cal_curr['brier']:.3f}")
st.metric("ECE (Curr)", f"{cal_curr['ece']:.3f}")
fig_cal = make_subplots(rows=1, cols=2, subplot_titles=('Ref', 'Curr'))
fig_cal.add_trace(go.Scatter(x=cal_ref['reliability_x'], y=cal_ref['reliability_y'], mode='markers+lines', name='Ref'), row=1, col=1)
fig_cal.add_trace(go.Scatter(x=cal_curr['reliability_x'], y=cal_curr['reliability_y'], mode='markers+lines', name='Curr'), row=1, col=2)
fig_cal.add_trace(go.Scatter(x=[0,1], y=[0,1], mode='lines', line=dict(dash='dash'), showlegend=False), row=1, col=1)
fig_cal.add_trace(go.Scatter(x=[0,1], y=[0,1], mode='lines', line=dict(dash='dash'), showlegend=False), row=1, col=2)
st.plotly_chart(fig_cal, use_container_width=True)
cal_degradation = cal_curr['brier'] > cal_ref['brier'] + 0.02
with tab4:
st.subheader("Backtesting Exceptions")
exceptions = backtest_exceptions(ref_df, curr_df, error_threshold)
st.metric("Ref Exception Rate", f"{exceptions['ref_exception_rate']:.1%}")
st.metric("Curr Exception Rate", f"{exceptions['curr_exception_rate']:.1%}")
st.metric("Exceptions Count (Curr)", exceptions['curr_exceptions'])
curr_df['error'] = np.abs(curr_df['y_pred_proba'] - curr_df['y_true'])
curr_df['exception'] = curr_df['error'] > error_threshold
fig_errors = px.histogram(curr_df, x='error', color='exception', title="Error Distribution", nbins=50)
st.plotly_chart(fig_errors, use_container_width=True)
exceptions_high = exceptions['exception_increase']
with tab4:
pass # Wait, tab4 is backtesting, already done above? Wait, tabs are tab1 overview, tab2 drift, tab3 cal, tab4 backtest (above), tab5 challengers
with tab5:
st.subheader("Challenger Models")
challenger = challenger_comparison(ref_df, curr_df)
col1, col2, col3 = st.columns(3)
col1.metric("Incumbent Acc (Curr)", f"{challenger['incumbent_acc_curr']:.3f}")
col2.metric("Challenger Acc (Curr)", f"{challenger['challenger_acc_curr']:.3f}")
col3.metric("LogLoss Improvement", f"{challenger['logloss_improvement']:.3f}")
st.dataframe(pd.DataFrame([challenger]), use_container_width=True)
if challenger['challenger_better']:
st.success("✅ Challenger outperforms incumbent!")
with tab6: # Escalation tab
st.subheader("🚨 Escalation Dashboard")
severity, issues = check_escalation(drift_issues, cal_degradation, exceptions_high, challenger['challenger_better'])
if severity == "CRITICAL":
st.error(f"🚨 **{severity}**: {', '.join(issues)}")
elif severity == "WARNING":
st.warning(f"⚠️ **{severity}**: {', '.join(issues)}")
else:
st.success("✅ All systems nominal.")
# Summary table
summary = {
'Metric': ['Drift Issues', 'Cal Degradation', 'High Exceptions', 'Challenger Better'],
'Status': [drift_issues > 0, cal_degradation, exceptions_high, challenger['challenger_better']],
'Action': ['Investigate features', 'Recalibrate model', 'Review exceptions', 'Promote challenger']
}
st.dataframe(pd.DataFrame(summary))
st.markdown("---")
st.caption("Built with Streamlit, Scikit-learn, Plotly. Upload your own CSV data with columns: feature_*, y_true, y_pred_proba, y_pred_challenger_proba.")
This is a production-ready, interactive hub! 🔍 Extend with Evidently AI or Prometheus for scale.