Articles / mlopsmachine-learningpythonprojects
Build an ML model monitoring dashboard in Python: SQLite, PSI drift and Streamlit
Log every prediction to SQLite, then track accuracy as labels arrive, prediction mix, confidence, PSI drift per feature and latency percentiles in Streamlit.
A model that scored 100% on its holdout set can be wrong one request in ten a week later, and nothing in the serving code will tell you. The inputs moved, the model kept answering, and the only people who noticed were the users. A monitoring dashboard is how you notice first.
Most tutorials compute a few metrics on one batch held in memory and draw them. That skips the hard parts. Real labels arrive days late, so on the newest days you have no accuracy at all. Drift tests give different answers depending on sample size. Latency on a shared machine is mostly noise from other processes. This post builds a monitor that handles those cases:
- every prediction logged to SQLite, with labels joined in later when they arrive
- per-day accuracy that stays blank until labels exist, instead of pretending
- prediction mix and confidence, the signals you get without labels
- PSI per feature against a reference window, with a check of how noisy PSI is at your sample size
- p50, p95 and p99 latency per day
- alerts that compare today with the reference window, and a Streamlit page on top
All of it runs offline on scikit-learn's Wine dataset. The tables below are real output from the code shown.
Two earlier posts cover the LLM side of this. The LLM evaluation dashboard compares prompt versions on a fixed dataset, and the LLM cost and latency tracker logs tokens and cost per call. This post is about a classic tabular model in production. What to do once an alert fires (retraining, champion and challenger, rollback) is in auto-retrain an ML model on drift.
How the pieces fit#
request --> predict_and_log() --> response
|
v
predictions table (features JSON, prediction, confidence, latency_ms)
^
| joined on request_id, days later
labels table (label, label_ts)
|
v
metrics.py --> accuracy / mix / confidence / PSI / latency / alerts
|
v
app.py (Streamlit, re-reads the DB once a minute)
The serving path does one extra thing: an INSERT. Everything else runs off the database, on its own schedule, so a slow dashboard never slows a prediction.
Logging predictions and late labels#
# monitor_db.py
import json
import sqlite3
import time
import uuid
SCHEMA = """
CREATE TABLE IF NOT EXISTS predictions (
request_id TEXT PRIMARY KEY,
ts REAL NOT NULL, -- unix seconds
model_version TEXT NOT NULL,
features TEXT NOT NULL, -- JSON object, feature name -> value
prediction INTEGER NOT NULL,
confidence REAL NOT NULL, -- max class probability
latency_ms REAL NOT NULL
);
CREATE TABLE IF NOT EXISTS labels (
request_id TEXT PRIMARY KEY REFERENCES predictions(request_id),
label INTEGER NOT NULL,
label_ts REAL NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_pred_ts ON predictions(ts);
"""
def connect(path="monitor.db"):
db = sqlite3.connect(path)
db.executescript(SCHEMA)
return db
def predict_and_log(db, model, model_version, row, ts=None):
"""Run one prediction, time it, and write one row. Returns (request_id, prediction)."""
start = time.perf_counter()
proba = model.predict_proba(row)[0]
latency_ms = (time.perf_counter() - start) * 1000
pred = int(proba.argmax())
request_id = uuid.uuid4().hex
db.execute(
"INSERT INTO predictions VALUES (?, ?, ?, ?, ?, ?, ?)",
(request_id, ts or time.time(), model_version,
json.dumps({k: float(v) for k, v in row.iloc[0].items()}),
pred, float(proba.max()), latency_ms),
)
return request_id, pred
def log_label(db, request_id, label, label_ts=None):
"""Called later, when the true outcome is known."""
db.execute("INSERT OR REPLACE INTO labels VALUES (?, ?, ?)",
(request_id, int(label), label_ts or time.time()))
Some choices here are deliberate.
Labels live in their own table. The prediction row is written once, at request time. The label might come from a support ticket, a chargeback or a human reviewer, days later, so it gets its own table keyed on request_id. The caller has to return request_id to whoever will know the outcome. If you skip that, you can never compute accuracy, however good the dashboard is.
Features are stored as they were at prediction time. Not a foreign key into a feature store that may have been updated since. Drift checks need the exact values the model saw.
argmax works as the class here because the Wine labels are 0, 1 and 2, which match model.classes_. With string labels, use model.classes_[proba.argmax()].
model_version is on every row. When you deploy a new model, you want to split every chart by version. Without it, a bad deploy and natural drift look the same.
The latency is measured around predict_proba only. That is the model's share. Your users also wait on network, parsing and feature lookups, so in a real service, time the whole handler too. The FastAPI post shows where that timing sits in a request.
SQLite is fine for one service writing a few requests a second. If several worker processes write to the same file, turn on write-ahead logging so readers do not block the writer. Past that, the same two tables move to Postgres or a warehouse without changing the metric code.
A week of traffic with drift and late labels#
The demo needs production traffic that drifts on a known day. The model is a 200-tree random forest trained on 70% of the Wine dataset, which has 178 samples, 13 numeric features and 3 classes.
# simulate.py
import datetime as dt
import os
import numpy as np
import pandas as pd
from sklearn.datasets import load_wine
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from monitor_db import connect, log_label, predict_and_log
rng = np.random.default_rng(7)
X, y = load_wine(return_X_y=True, as_frame=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=42, stratify=y)
model = RandomForestClassifier(n_estimators=200, random_state=42).fit(X_train, y_train)
print("holdout accuracy:", round(model.score(X_test, y_test), 3))
# Training features, kept to check for train/serve skew later.
X_train.to_csv("reference.csv", index=False)
if os.path.exists("monitor.db"):
os.remove("monitor.db")
db = connect("monitor.db")
DAYS, PER_DAY = 7, 300
LABELLED_DAYS = 5 # labels arrive late: the last 2 days have none yet
DRIFT_FROM = 3 # day index where the input data starts to change
start = dt.datetime(2026, 11, 1, tzinfo=dt.timezone.utc).timestamp()
# Synthetic traffic: one Gaussian per class, fitted on the training rows.
# (Resampling the 54 test rows would itself look like drift; see "PSI has a noise floor".)
classes = sorted(y_train.unique())
prior = y_train.value_counts(normalize=True).sort_index().to_numpy()
fits = {c: (X_train[y_train == c].mean(), X_train[y_train == c].cov()) for c in classes}
def traffic(n):
labels = rng.choice(classes, size=n, p=prior)
rows = [rng.multivariate_normal(*fits[c]) for c in labels]
return pd.DataFrame(rows, columns=X.columns).clip(lower=0), labels
for day in range(DAYS):
batch, labels = traffic(PER_DAY)
if day >= DRIFT_FROM:
batch["alcohol"] += 0.8 # about one training std
batch["color_intensity"] *= 1.4 # a new supplier, a recalibrated sensor...
for i in range(PER_DAY):
ts = start + day * 86400 + i * (86400 / PER_DAY)
rid, _ = predict_and_log(db, model, "rf-v1", batch.iloc[[i]], ts=ts)
if day < LABELLED_DAYS:
log_label(db, rid, labels[i], label_ts=ts + 86400)
db.commit()
n = db.execute("SELECT COUNT(*) FROM predictions").fetchone()[0]
m = db.execute("SELECT COUNT(*) FROM labels").fetchone()[0]
print(f"logged {n} predictions, {m} labels")
holdout accuracy: 1.0
logged 2100 predictions, 1500 labels
The script writes seven days of 300 requests each, from 1 to 7 November. From day 4 (4 November), alcohol shifts up by 0.8 and color_intensity grows by 40%. Labels exist for days 1 to 5. Days 6 and 7 have none, as if outcomes take two days to come back. The 1.0 holdout score is on only 54 rows, so it promises less than it seems to.
The metrics#
All metrics come from one join, grouped by UTC day.
# metrics.py
import json
import sqlite3
import numpy as np
import pandas as pd
from scipy.stats import ks_2samp
def load(db_path="monitor.db"):
db = sqlite3.connect(db_path)
df = pd.read_sql_query(
"""SELECT p.*, l.label
FROM predictions p LEFT JOIN labels l USING (request_id)""", db)
df["day"] = pd.to_datetime(df["ts"], unit="s", utc=True).dt.strftime("%Y-%m-%d")
feats = pd.DataFrame([json.loads(s) for s in df.pop("features")])
return df, feats
def daily_accuracy(df):
g = df.groupby("day")
out = pd.DataFrame({
"requests": g.size(),
"labelled": g["label"].count(),
})
hit = (df["prediction"] == df["label"]).where(df["label"].notna())
out["accuracy"] = hit.groupby(df["day"]).mean().round(3) # NaN when no labels yet
return out
def prediction_mix(df):
return (pd.crosstab(df["day"], df["prediction"], normalize="index")
.round(2).add_prefix("class_"))
def confidence(df, low=0.6):
g = df.groupby("day")["confidence"]
return pd.DataFrame({"mean_conf": g.mean().round(3),
"low_conf_share": g.apply(lambda s: (s < low).mean()).round(3)})
def latency(df):
g = df.groupby("day")["latency_ms"]
return pd.DataFrame({f"p{q}_ms": g.quantile(q / 100).round(2) for q in (50, 95, 99)})
The LEFT JOIN keeps predictions with no label yet. The .where(df["label"].notna()) line matters: comparing a prediction with a missing label gives False, and False counts as a miss. Without the mask, days 6 and 7 would show 0% accuracy and someone would get paged for a model that is fine.
Here is the output for the simulated week:
requests labelled accuracy
day
2026-11-01 300 300 0.97
2026-11-02 300 300 0.977
2026-11-03 300 300 0.983
2026-11-04 300 300 0.937
2026-11-05 300 300 0.893
2026-11-06 300 0 NaN
2026-11-07 300 0 NaN
prediction class_0 class_1 class_2
day
2026-11-01 0.31 0.41 0.28
2026-11-02 0.36 0.38 0.26
2026-11-03 0.33 0.41 0.26
2026-11-04 0.38 0.31 0.31
2026-11-05 0.39 0.29 0.31
2026-11-06 0.37 0.33 0.30
2026-11-07 0.32 0.35 0.33
mean_conf low_conf_share
day
2026-11-01 0.870 0.063
2026-11-02 0.888 0.037
2026-11-03 0.875 0.047
2026-11-04 0.824 0.157
2026-11-05 0.806 0.193
2026-11-06 0.808 0.197
2026-11-07 0.822 0.143
Accuracy falls from about 0.98 to 0.89 once the drift starts, and the error rate goes from 2.3% (the reference-window average) to 10.7%. On days 6 and 7 the accuracy column is empty, and that is the honest answer.
The confidence table has no such gap. The share of predictions below 0.6 confidence goes from about 5% to 14 to 20% on the same day the inputs change, two days before any label could confirm it. Confidence and prediction mix are your early signals. Accuracy is the confirmation.
The prediction mix is the weakest of the three here. Class 1 drops from about 40% to about 30% on days 4 and 5, then partly recovers on day 7, while the true class mix never changed. Swings of a few points also appear on normal days (31% to 36% for class 0 between days 1 and 2). A mix chart catches big moves, like a model that suddenly predicts one class for 70% of traffic. It is a poor detector for small ones at 300 requests a day.
Feature drift with PSI#
The population stability index compares how one feature's values spread across bins in two samples. With reference share r and current share c in each bin, PSI is the sum of (c - r) * ln(c / r) over the bins. It is 0 when the shares match and grows with every bin that moves.
def psi(reference, current, bins=5, eps=1e-4):
"""Population stability index with bin edges from the reference's quantiles."""
edges = np.unique(np.quantile(reference, np.linspace(0, 1, bins + 1)))
edges[0], edges[-1] = -np.inf, np.inf # catch values outside the old range
ref_pct = np.histogram(reference, edges)[0] / len(reference)
cur_pct = np.histogram(current, edges)[0] / len(current)
ref_pct, cur_pct = np.clip(ref_pct, eps, None), np.clip(cur_pct, eps, None)
return float(np.sum((cur_pct - ref_pct) * np.log(cur_pct / ref_pct)))
def drift_table(reference, current):
rows = []
for col in reference.columns:
rows.append({"feature": col,
"psi": round(psi(reference[col], current[col]), 3),
"ks_p": ks_2samp(reference[col], current[col]).pvalue})
out = pd.DataFrame(rows).sort_values("psi", ascending=False).reset_index(drop=True)
out["status"] = pd.cut(out["psi"], [-1, 0.1, 0.25, np.inf],
labels=["stable", "watch", "drift"])
return out
Three details keep this from breaking. Bin edges come from the reference's quantiles, so each reference bin holds about the same share of data. The outer edges are set to infinity, so a value above anything seen before still lands in a bin and does not vanish from the count. The eps clip stops ln(0) when a bin is empty. np.unique handles features with many repeated values, where two quantiles can be equal.
The 0.1 and 0.25 cut-offs are a common rule of thumb (Yurdakul, 2018 discusses them and their limits), not a statistical test. Treat them as a starting point and tune them on your own history.
Reference window or training data?#
The question "drifted compared to what?" has two useful answers, and they catch different problems.
drift, 2026-11-07 vs reference window
feature psi ks_p status
0 alcohol 0.708 1.796683e-22 drift
1 color_intensity 0.403 6.083102e-14 drift
2 proanthocyanins 0.049 2.917979e-03 stable
3 nonflavanoid_phenols 0.042 1.383876e-01 stable
4 proline 0.034 1.383876e-01 stable
drift, 2026-11-01 vs training data
feature psi ks_p status
0 malic_acid 0.251 0.004544 drift
1 nonflavanoid_phenols 0.102 0.802853 watch
2 magnesium 0.075 0.037909 stable
Against a reference window of known-good production traffic (days 1 to 3, 900 rows), the two features that were changed come out on top, and nothing else gets close.
Against the training data, day 1 already shows malic_acid at 0.251, before any drift was injected. That is real. The simulator draws from a Gaussian, and the real malic_acid values are skewed to the right, so the simulated traffic never matched training. In production the same pattern is called train/serve skew: a unit change, a different default for missing values, a feature computed one way in the notebook and another way in the service. Run the training comparison once at launch and after each deploy, then use a production window for daily monitoring.
KS p-values and sample size#
The ks_p column is the two-sample Kolmogorov-Smirnov test from SciPy. Look at proanthocyanins: PSI says stable (0.049), the KS p-value is 0.003, and a p < 0.05 rule would flag it. Nothing was done to that feature. The p-value answers "are these two samples from exactly the same distribution?", and with 900 and 300 rows, the test can detect differences too small to affect the model. With 13 features checked daily at 0.05, you would also expect a false alarm about every second day on chance alone. Use the KS statistic or PSI as an effect size, and keep p-values out of the alert rule.
PSI has a noise floor#
PSI is not 0 for two samples from the same distribution. It has a floor that depends on sample size and bin count. To measure it, take two samples from the same normal distribution and compute PSI 500 times:
# psi_noise.py: PSI between two samples from the SAME distribution
import numpy as np
from metrics import psi
rng = np.random.default_rng(0)
print(f"{'ref n':>6}{'cur n':>7}{'bins':>6}{'median PSI':>12}{'95th pct':>10}")
for n_ref, n_cur in [(124, 300), (900, 300), (5000, 2000)]:
for bins in (5, 10):
vals = [psi(rng.normal(size=n_ref), rng.normal(size=n_cur), bins=bins) for _ in range(500)]
print(f"{n_ref:>6}{n_cur:>7}{bins:>6}{np.median(vals):>12.3f}{np.percentile(vals, 95):>10.3f}")
ref n cur n bins median PSI 95th pct
124 300 5 0.036 0.111
124 300 10 0.097 0.199
900 300 5 0.015 0.041
900 300 10 0.038 0.079
5000 2000 5 0.002 0.007
5000 2000 10 0.006 0.012
With a 124-row reference (this model's whole training set) and 10 bins, one feature-day in twenty scores 0.2 or more with no drift at all, close to the 0.25 drift line. With 13 features, about half of all days would have at least one feature that near the line. Resampling the 54 test rows as traffic makes it worse: with 10 bins, every feature scored as drifted on day 1 of an earlier run of this demo, magnesium at 0.975. The fix was a larger reference, fewer bins, and traffic that matched the reference. Run this check once for your own row counts before you pick thresholds.
Latency percentiles#
p50_ms p95_ms p99_ms
day
2026-11-01 101.83 1016.98 1493.20
2026-11-02 113.41 470.46 564.66
2026-11-03 134.79 564.91 774.90
2026-11-04 44.72 380.97 586.95
2026-11-05 28.18 152.10 298.69
2026-11-06 56.98 331.83 414.50
2026-11-07 30.42 205.33 346.47
The model and the input size never changed, yet p95 moved between 152 ms and 1,017 ms. These numbers were measured on a laptop with a load average near 300 from other jobs, so the spread most likely comes from the host, not the model. That is a useful thing to see on a dashboard: a latency alert tells you something about the serving machine, and the drift alert above is the one that says something about the data. Always chart p95 and p99 next to p50. One slow call in a hundred never shows in the median.
A quick benchmark on the same machine shows where the time goes:
# bench.py: one row at a time vs one batch of 300
import time
import numpy as np
from sklearn.datasets import load_wine
from sklearn.ensemble import RandomForestClassifier
X, y = load_wine(return_X_y=True, as_frame=True)
model = RandomForestClassifier(n_estimators=200, random_state=42).fit(X, y)
rows = X.sample(300, replace=True, random_state=0)
single = []
for i in range(len(rows)):
t = time.perf_counter(); model.predict_proba(rows.iloc[[i]])
single.append((time.perf_counter() - t) * 1000)
t = time.perf_counter(); model.predict_proba(rows); batch_ms = (time.perf_counter() - t) * 1000
print(f"single row: p50 {np.percentile(single, 50):.1f} ms, p95 {np.percentile(single, 95):.1f} ms, "
f"p99 {np.percentile(single, 99):.1f} ms, mean {np.mean(single):.1f} ms")
print(f"batch of 300: {batch_ms:.1f} ms total, {batch_ms / 300:.2f} ms per row")
single row: p50 46.4 ms, p95 277.8 ms, p99 465.7 ms, mean 81.5 ms
batch of 300: 42.3 ms total, 0.14 ms per row
The mean (81.5 ms) is almost twice the median (46.4 ms) because a few slow calls pull it up, which is why the dashboard reports percentiles. Scoring 300 rows in one call took less time than one single-row call. Nearly all of the single-row cost is fixed overhead per predict_proba call, not per-row arithmetic. If your traffic allows micro-batching, that is the first latency fix to try.
Alerts relative to a baseline#
def alerts(acc, conf, drift, lat, ref_days, max_acc_drop=0.05, max_p95_ms=200):
"""Compare today with the reference window, not with fixed absolute numbers."""
out = []
base_acc = acc.loc[ref_days, "accuracy"].mean()
labelled = acc.dropna(subset=["accuracy"])
newest = labelled.index[-1]
if base_acc - labelled.loc[newest, "accuracy"] > max_acc_drop:
out.append(f"accuracy {labelled.loc[newest, 'accuracy']:.3f} on {newest} "
f"vs {base_acc:.3f} in the reference window")
base_low = conf.loc[ref_days, "low_conf_share"].mean()
today_low = conf["low_conf_share"].iloc[-1]
if today_low > 2 * base_low:
out.append(f"low-confidence share {today_low:.1%} vs {base_low:.1%} in the reference window")
drifted = drift.loc[drift["status"] == "drift", "feature"].tolist()
if drifted:
out.append(f"PSI > 0.25 on: {', '.join(drifted)}")
if lat["p95_ms"].iloc[-1] > max_p95_ms:
out.append(f"p95 latency {lat['p95_ms'].iloc[-1]:.1f} ms")
return out
ALERTS:
- accuracy 0.893 on 2026-11-05 vs 0.977 in the reference window
- low-confidence share 14.3% vs 4.9% in the reference window
- PSI > 0.25 on: alcohol, color_intensity
- p95 latency 205.3 ms
Accuracy and confidence are checked against the reference window, not fixed numbers like "accuracy below 0.85". A fixed line set for this model would be wrong for the next one, and a drop from 0.98 to 0.89 matters even though 0.89 sounds fine. The accuracy alert names the newest labelled day, so whoever reads it knows the figure is two days old. The latency line is an absolute budget because it comes from a promise to users, not from the model's history. On this loaded laptop it fired, which is the correct result for that machine.
In production, send these to Slack or a pager, and require a condition to hold for two checks in a row before paging anyone. One noisy day should not wake people up.
The Streamlit dashboard#
# app.py: streamlit run app.py
import streamlit as st
import metrics as m
st.set_page_config(page_title="Model monitor", layout="wide")
@st.cache_data(ttl=60) # re-read the database at most once a minute
def load():
return m.load("monitor.db")
df, feats = load()
days = sorted(df["day"].unique())
ref_days = st.sidebar.multiselect("Reference window", days, default=days[:3])
today = st.sidebar.selectbox("Day to check", days, index=len(days) - 1)
if not ref_days:
st.stop()
acc, conf, lat = m.daily_accuracy(df), m.confidence(df), m.latency(df)
drift = m.drift_table(feats[df["day"].isin(ref_days)], feats[df["day"] == today])
st.title(f"rf-v1 on {today}")
upto = slice(None, today) # alerts look at "today" as the newest day
for msg in m.alerts(acc.loc[upto], conf.loc[upto], drift, lat.loc[upto], ref_days):
st.error(msg)
c1, c2, c3, c4 = st.columns(4)
labelled = acc.loc[:today].dropna(subset=["accuracy"])
c1.metric("Accuracy (newest labelled day)", f"{labelled['accuracy'].iloc[-1]:.1%}",
help=f"Labels lag; newest labelled day is {labelled.index[-1]}")
c2.metric("Labelled today", f"{acc.loc[today, 'labelled']} / {acc.loc[today, 'requests']}")
c3.metric("Low-confidence share", f"{conf.loc[today, 'low_conf_share']:.1%}",
delta=f"{conf.loc[today, 'low_conf_share'] - conf.loc[ref_days, 'low_conf_share'].mean():+.1%}",
delta_color="inverse")
c4.metric("p95 latency", f"{lat.loc[today, 'p95_ms']:.0f} ms")
left, right = st.columns(2)
left.subheader("Accuracy by day (labelled days only)")
left.line_chart(acc["accuracy"])
right.subheader("Prediction mix by day")
right.bar_chart(m.prediction_mix(df))
left.subheader("Latency percentiles (ms)")
left.line_chart(lat)
right.subheader(f"Feature drift: {today} vs reference window")
right.dataframe(drift, hide_index=True)
The page is a thin layer over metrics.py, so the numbers on screen are the ones the tests check. st.cache_data with ttl=60 stops every browser refresh from re-reading the whole table. The reference window is a sidebar control because the right baseline changes: after a planned change, such as a new market, you move the window forward instead of living with a permanent alert. delta_color="inverse" on st.metric shows a rise in low-confidence share in red, since up is bad for that metric. The "Labelled today" tile shows 0 / 300 on the newest days, which tells the reader why the accuracy tile shows an older day.
Run it with streamlit run app.py. For this post it ran headless with Streamlit 1.67.0 on port 8599: /_stcore/health returned ok, the root page returned HTTP 200, and then the server was stopped.
Tests#
A health check only proves the server started. A typo in app.py still returns 200 and shows a stack trace in the browser. Streamlit's AppTest runs the script without a browser and lets you check what it rendered:
# test_app.py: runs the dashboard script without a browser
from streamlit.testing.v1 import AppTest
def test_dashboard_renders_and_alerts():
at = AppTest.from_file("app.py", default_timeout=60).run()
assert not at.exception
assert at.title[0].value == "rf-v1 on 2026-11-07"
assert len(at.metric) == 4
assert any("alcohol" in e.value for e in at.error)
The metric code gets plain unit tests, including the label-lag case that would otherwise show 0% accuracy:
# test_metrics.py: run with python -m pytest -q
import numpy as np
import pandas as pd
from metrics import daily_accuracy, psi
rng = np.random.default_rng(1)
def test_psi_near_zero_for_same_distribution():
assert psi(rng.normal(size=5000), rng.normal(size=5000)) < 0.02
def test_psi_large_for_one_std_shift():
assert psi(rng.normal(size=5000), rng.normal(1.0, 1, size=5000)) > 0.25
def test_psi_handles_values_outside_reference_range():
assert np.isfinite(psi(np.arange(100.0), np.full(50, 1e6)))
def test_accuracy_is_nan_until_labels_arrive():
df = pd.DataFrame({"day": ["d1", "d1", "d2"], "prediction": [1, 0, 1],
"label": [1, 1, np.nan]})
acc = daily_accuracy(df)
assert acc.loc["d1", "accuracy"] == 0.5
assert np.isnan(acc.loc["d2", "accuracy"]) and acc.loc["d2", "labelled"] == 0
..... [100%]
5 passed in 11.74s
Versions used: Python 3.15, pandas 3.1.1, NumPy 2.5.5, scikit-learn 1.9.1, SciPy 1.18.1, Streamlit 1.67.0, pytest 9.2.0. Install with pip install pandas numpy scikit-learn scipy streamlit pytest in a virtual environment.
Things that go wrong#
- Labels that never come back. If the outcome system drops 30% of labels, and the dropped ones are the hard cases, your accuracy looks better than it is. Chart the labelled share next to accuracy, as the "Labelled today" tile does.
- Feedback loops. If the model's prediction decides what happens next (a loan declined, so no repayment label ever exists), labels only arrive for one kind of prediction. Accuracy on those is biased, and only a small random holdout of unfiltered decisions fixes it.
- Timezones. Days here are UTC. If your business day is IST, a UTC day boundary splits Indian evening traffic in two. Pick one and write it in the chart titles.
- Too many features. With 300 features, some will cross any threshold every day. Rank drift by feature importance and alert on the features the model uses most.
- The dashboard as the only check. Nobody watches a dashboard at 3 a.m. The alert function is the part that matters. The page is for the person who got paged.
Google's ML Test Score rubric lists monitoring tests that go further than this post, such as checking that training and serving compute the same features and that the model has not gone stale. It works as a checklist once this version runs.
Sources#
- scikit-learn: load_wine
- scikit-learn: RandomForestClassifier
- SciPy: scipy.stats.ks_2samp
- pandas: crosstab
- Python: sqlite3
- Python: time.perf_counter
- SQLite: write-ahead logging
- Streamlit: st.cache_data
- Streamlit: st.metric
- Streamlit: AppTest
- Streamlit on PyPI
- Breck et al., The ML Test Score (Google Research)