There is a reflex in IoT projects that goes: "we have anomaly data, so we need a model." Often the honest answer is that a robust statistical baseline will detect 80% of the incidents with 2% of the engineering effort — and, crucially, with far fewer false alarms during the first two weeks after commissioning, which is exactly when trust is built.

This post compares the two approaches honestly, gives you working code for the statistical side, and describes the hybrid that I end up shipping most of the time.

What "anomaly" means operationally

Before comparing detectors, define what you are detecting. Three very different problems get called "anomaly detection":

  1. Point outliers — a single sample outside the historical range. Sensor glitch, transient spike.
  2. Level shift / drift — the process moves to a new operating point and stays there. Fouling, wear, a changed setpoint.
  3. Shape change — the signal's dynamics change while its mean stays flat. Bearing defect, looseness, cavitation.

A robust z-score handles (1) well and (2) adequately. It is poor at (3), because crest factor and spectral content can change dramatically with an unchanged mean. If your failure modes are mostly (3), a model that sees a window of raw or lightly processed samples earns its complexity. If they are (1) and (2), a statistical baseline is not a compromise — it is the right tool.

The baseline, properly done

A naive mean ± 3σ fails for three reasons: spikes inflate σ, the distribution is rarely Gaussian, and it ignores time. Fix all three:

import numpy as np class RobustBaseline: """Median/MAD baseline with EWMA smoothing and hysteresis. Handles spikes (median), non-Gaussian tails (MAD + quantile), and slow drift (EWMA) without a training pipeline. """ MAD_TO_SIGMA = 1.4826 def __init__(self, alpha=0.02, warmup=300, k_warn=4.0, k_alarm=6.0, hold=5): self.alpha = alpha self.warmup = warmup self.k_warn = k_warn self.k_alarm = k_alarm self.hold = hold self.n = 0 self.med = None self.mad = None self.state = "ok" self._over = 0 def update(self, x: float) -> tuple[str, float]: if self.med is None: self.med, self.mad = x, 1e-6 self.n += 1 # EWMA on centre and spread: adapts to setpoint changes, resists spikes self.med += self.alpha * (x - self.med) self.mad += self.alpha * (abs(x - self.med) - self.mad) sigma = max(self.mad * self.MAD_TO_SIGMA, 1e-9) z = (x - self.med) / sigma # during warm-up, only widen the band; never alert if self.n < self.warmup: return "warmup", z if abs(z) >= self.k_alarm: self._over += 1 else: self._over = 0 if self._over >= self.hold: self.state = "alarm" elif abs(z) >= self.k_warn: self.state = "warn" elif self.state == "alarm" and abs(z) < self.k_warn: self.state = "warn" elif abs(z) < self.k_warn * 0.5: self.state = "ok" return self.state, z 

Four design choices carry most of the value:

  • EWMA rather than a fixed historical window. A machine that ramps to a new load for 20 minutes is not anomalous; a fixed baseline from last month says it is. The EWMA follows the operating point.
  • MAD rather than σ. One 10× spike changes σ by a lot and median absolute deviation by almost nothing.
  • A warm-up period that never alerts. You will thank yourself on day one of every deployment.
  • Hold-down plus hysteresis (k_alarm > k_warn, and a return threshold at half of k_warn). This alone typically cuts alert volume by half. More on that in the hysteresis post.

Where the baseline breaks

Three failure modes are worth knowing because they tell you when to graduate to a model:

Correlated channels. A temperature rise in a motor is normal if current also rose and the ambient did not. A per-channel z-score cannot express "high, but consistent with load". This is where a learned model — or even a simple multivariate Mahalanobis distance — wins immediately.

Shape-only faults. A crest-factor rise from 2.1 to 3.4 on a bearing is a classic early indicator that stays invisible to a mean-based detector. If your maintenance history is dominated by these, you need window features or a model.

Multi-modal normal behaviour. A compressor that runs loaded, idle, and in a defrost cycle has three distinct "normal" operating points. A single centre/spread pair produces alerts at every transition. You can fix this with mode-conditioned baselines (one RobustBaseline per mode) — which is usually the cheap correct answer, and a strong argument against reaching for a neural network too early.

Fair comparison: the metrics that matter

Do not compare detectors with AUC. Compare them the way operations experiences them:

  • Time to detect — minutes from fault onset to first alarm, per incident.
  • False alarms per device per day — the number your on-call rotation actually feels.
  • Alert precision — share of alarms a technician judges actionable.
  • Lead time before failure — for predictive maintenance, the window in which you can act.

A worked comparison table from a real fleet of 180 pumps looked like this:

Detector Median time to detect False alarms / device / day Precision Flash need
Per-channel robust z 41 min 1.8 0.34 < 1 KB
Multivariate Mahalanobis 22 min 0.9 0.52 ~ 2 KB
1D CNN on raw window 8 min 0.4 0.71 96 KB
CNN + rule engine + dedup 8 min 0.1 0.88 96 KB

Note the last row: the big win in precision did not come from a better model, it came from the rule engine and de-duplication layered on top. That pattern repeats — the model is rarely the whole answer.

The Mahalanobis row is worth dwelling on. It costs a covariance matrix and a few multiplications, fits in a couple of kilobytes, and captures load-correlated behaviour that per-channel z-scores miss. For many fleets it is the best effort-to-value ratio available.

import numpy as np class MahalanobisBaseline: def __init__(self, feature_names, shrink=0.10): self.names = feature_names self.shrink = shrink self.mu = None self.inv_cov = None def fit(self, X: np.ndarray) -> "MahalanobisBaseline": self.mu = X.mean(axis=0) cov = np.cov(X, rowvar=False) # shrinkage keeps the inverse stable with correlated features cov = (1 - self.shrink) * cov + self.shrink * np.eye(cov.shape[0]) * np.trace(cov) / cov.shape[0] self.inv_cov = np.linalg.inv(cov) return self def score(self, x: np.ndarray) -> float: d = x - self.mu return float(np.sqrt(d @ self.inv_cov @ d)) 

Score thresholds come from the chi-square distribution, not from a 3σ rule: for d features, the 99.9th percentile of χ²(d) is a defensible alarm threshold. Hardcode the resulting constant in the firmware so the device does not need a stats library.

The hybrid I usually ship

per-sample → device: hard limits (deterministic, no model) per-window → gateway: robust baseline per operating mode (cheap, always on) └─ if |z| > k_warn: run the learned model on the window per-event → cloud: correlation, dedup, triage 

The baseline acts as a cheap gate, and the model runs only on windows the baseline flagged. On a 200-device fleet this cut inference CPU by roughly 90% while keeping detection latency identical, because the baseline catches the same onsets the model does — it just cannot say much about what is happening.

There is a second benefit that matters more: the baseline is the fallback. If a model update goes wrong, or a device's model fails to load, the baseline still detects level shifts and point outliers. A pipeline whose only detector is a neural network has no degraded mode; it has an outage.

Guarding the baseline against setpoint changes

Baselines go bad when the process changes: a new product run, a retuned controller, a replaced sensor. Three cheap guards:

1 Mode-conditioned state. Key the baseline on an operating mode supplied by the machine, not inferred. baselines[mode].update(x).
2 Commissioning reset with an explicit window. Allow a supervised "rebaseline" that ignores data for N minutes after a setpoint command, so the ramp itself never becomes the new normal.
3 Slow-drift detection on the baseline itself. Track med over days; if it moves more than X% without a maintenance event, that is a signal in its own right, not noise to be absorbed.

That third guard is genuinely useful. On one fleet, the alarm that actually predicted failures was not a z-score at all — it was "the EWMA centre of the vibration RMS moved 15% in a week without a setpoint change". Slow, boring, and more predictive than the model.

Deciding

Use the baseline alone when: your failure modes are point outliers or level shifts, you have fewer than ~10 correlated channels, and your false-alarm budget is tight from day one.

Add a learned model when: faults are shape-based, channels are strongly correlated, or you have enough labelled incidents to evaluate a model honestly (a dozen is not enough to distinguish a model from a baseline — you need dozens).

Ship the hybrid almost always: baseline as gate and fallback, model for diagnosis, rule engine and de-duplication on top. That is the architecture the rest of this series builds toward.

Next: Designing a Rule Engine That Complements Your ML Model.