Flag metric spikes with a rolling z-score of the previous values per model

HardpandasPro

Why it matters Rolling z-score alerts on error rate, latency and cost are the simplest anomaly detectors in ML monitoring.

Monitoring flags a day as a spike when it is far from the recent normal. The recent normal must come from the PREVIOUS days only; if the window includes today, a spike hides itself by inflating the mean and the spread.

Write spike_alerts(df) where df has columns model (str), day (string, string order is time order) and value (float), one row per (model, day), rows in arbitrary order.

For each row, look at the same model's previous 3 rows in day order. If there are fewer than 3, the row is not flagged. Otherwise mean and std are over those 3 values (std with ddof=0), and the row is flagged when std > 0 and abs(value - mean) / std > 3.

Return a list of (model, day) tuples for the flagged rows, sorted by model then day.

Signaturedef spike_alerts(df)

Example

model 'a' with days d1 to d5 and values 10, 11, 9, 10, 30 gives [('a', 'd5')]. (d4 has z = 0, d5 has mean 10, std 0.8165, z = 24.5.)

Understand the idea

A z-score says how many standard deviations a value is from a mean: z = (x - mean) / std. For live monitoring the mean and std should describe the recent past, so a rolling window of the previous w values is used, and the current value is compared against it.

Worked example: previous values 11, 9, 10 have mean 10 and std (ddof 0) sqrt((1 + 1 + 0) / 3) = 0.8165. Today's value 30 gives z = (30 - 10) / 0.8165 = 24.5, a clear spike. If 30 were inside its own window (9, 10, 30), the mean would be 16.3 and std 9.7, giving z = 1.4: the spike hides.

Rule: baseline = values t-w to t-1, z_t = (x_t - mean(baseline)) / std(baseline), flag if |z_t| > k. In pandas: s.shift(1).rolling(w).

Serving dashboards flag error rate, latency and cost spikes this way.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: examplespike_alerts(_d1())
  • Sample 2: drop and spike, two modelsspike_alerts(_d2())