The most common reason an IoT model looks great offline and useless in production is not the model. It is the features — specifically, the difference between how features were computed in the notebook and how they are computed on the gateway.
This post covers windowing, rolling statistics, gap handling, and the leakage patterns that quietly inflate offline metrics. All the code is plain Python plus NumPy, because feature code should be readable by the person who has to port it to C.
Telemetry is not a table
A training set built from a CSV of sensor rows teaches the wrong mental model. Real telemetry has properties that break table-shaped assumptions:
- Irregular arrival. A 100 Hz sensor does not deliver exactly 100 rows per second. Buffering, retries, and clock drift produce jitter.
- Gaps. Devices reboot, gateways lose uplink, messages are dropped. Gaps are normal, not exceptional.
- Monotonic-ish time with resets. Device clocks jump backwards after NTP sync or battery replacement.
- Multiple rates. Temperature at 1 Hz and vibration at 3.2 kHz share a decision but not a timeline.
Every one of these will silently corrupt a rolling(window=30).mean() if you computed it over row indices instead of time.
Window types and when to use them
| Window | Shape | Use when |
|---|---|---|
| Tumbling | Non-overlapping, fixed duration | You need one decision per interval and cheap compute |
| Sliding (overlapping) | Fixed duration, advancing by a hop | You need low detection latency |
| Expanding | Growing from a start point | Baseline learning at commissioning |
| Event-anchored | Centered on a detected event | Diagnosis and post-hoc analysis |
For alerting, sliding windows with a hop of 10–25% of the window length are the usual choice: a 60 s window with a 10 s hop gives you a decision every 10 s over the last minute, at six times the compute of a tumbling window. That extra compute is almost always worth it — a tumbling 60 s window means a fault that starts at second 1 is not detected until second 60.
Time-based resampling, done once and done right
Build one canonical function and use it everywhere. This is the single highest-leverage piece of code in a telemetry pipeline:
import numpy as np
import pandas as pd
def to_grid(df: pd.DataFrame, freq: str = "1s", time_col: str = "ts") -> pd.DataFrame:
"""Resample irregular telemetry onto a fixed grid, gap-aware.
- duplicates in the same bucket: keep the last
- missing buckets: explicit NaN, NOT dropped
- non-monotonic clocks: sort first
"""
df = df.sort_values(time_col)
# guard against device clock resets creating duplicate timestamps
df = df.drop_duplicates(subset=[time_col], keep="last")
g = df.set_index(pd.to_datetime(df[time_col], utc=True)).drop(columns=[time_col])
return g.resample(freq).last()
Three decisions are baked in, and each one matters:
- Missing buckets become NaN rather than disappearing. If you drop them, every downstream rolling mean silently reweights itself toward the samples that survived, which biases exactly the periods where the device was struggling.
- Duplicates keep the last. A retransmitted message should not double-count.
- Sort before resample. A single backwards clock jump otherwise produces a negative interval and a corrupt resample.
Rolling statistics without a library, because the device has no pandas
You will need the same computation on the gateway. Implement it incumbently so the cost is O(1) per sample instead of O(window):
class RollingStats:
"""Numerically stable rolling mean/variance over a time-ordered stream."""
def __init__(self, maxlen: int):
self.buf = np.empty(maxlen, dtype=np.float64)
self.maxlen = maxlen
self.i = 0
self.n = 0
def push(self, x: float) -> None:
self.buf[self.i] = x
self.i = (self.i + 1) % self.maxlen
self.n = min(self.n + 1, self.maxlen)
def mean_std(self) -> tuple[float, float]:
if self.n < 2:
return float("nan"), float("nan")
w = self.buf[: self.n] if self.n < self.maxlen else self.buf
return float(w.mean()), float(w.std(ddof=1))
If a full-buffer mean/std per window is too expensive on the device (it is O(n) each time), use Welford updates with a compensating subtraction when the oldest sample leaves the buffer — but note that naive "subtract old, add new" variance updates lose precision after millions of samples. For MCU work, recomputing over a small buffer (128–512 samples) every window is usually cheap enough and far easier to trust.
Robust features for industrial signals
Mean and standard deviation are useful but not robust: a single spike inflates σ and hides the next fault. Add these:
def robust_features(w: np.ndarray) -> dict[str, float]:
med = np.median(w)
mad = np.median(np.abs(w - med)) or 1e-9
d = np.diff(w)
return {
"median": med,
"mad": mad,
"robust_z_max": float(np.max(np.abs(w - med)) / (1.4826 * mad)),
"rms": float(np.sqrt(np.mean(w ** 2))),
"crest_factor": float(np.max(np.abs(w)) / (np.sqrt(np.mean(w ** 2)) + 1e-9)),
"diff_energy": float(np.mean(d ** 2)),
"zero_crossing_rate": float(np.mean(np.abs(np.diff(np.signbit(w).astype(np.int8))))),
}
crest_factor and diff_energy are disproportionately useful for mechanical faults: a bearing defect often raises crest factor while leaving RMS almost unchanged, and a loose mount raises high-frequency energy (diff energy) before it raises overall vibration.
For vibration specifically, add a cheap spectral feature. A full FFT is affordable on a gateway and sometimes on a device:
def band_powers(w: np.ndarray, fs: float, bands=((0, 10), (10, 50), (50, 200), (200, 1000))) -> dict:
spec = np.abs(np.fft.rfft(w - w.mean())) ** 2
freqs = np.fft.rfftfreq(len(w), d=1 / fs)
total = spec.sum() or 1e-12
out = {}
for lo, hi in bands:
m = (freqs >= lo) & (freqs < hi)
out[f"band_{lo}_{hi}"] = float(spec[m].sum() / total)
dom = int(np.argmax(spec[1:]) + 1)
out["dominant_hz"] = float(freqs[dom])
return out
Ratios (band power divided by total) transfer better across machines than absolute amplitudes, because they are insensitive to gain and mounting differences.
The leakage patterns that inflate offline scores
These are the ones I see most often. Each produces a model that scores beautifully in a notebook and fails on the first week of real traffic.
1. Normalizing with statistics from the whole dataset
# WRONG: uses future data
mu, sd = df["vib"].mean(), df["vib"].std()
# RIGHT: fit on a training period only, persist the constants
mu, sd = train["vib"].mean(), train["vib"].std()
This is the classic, and it still happens constantly in IoT because the "training period" is often an arbitrary slice of a continuous recording. Worse: on the device, you must ship mu and sd as constants. If you forget, the device computes its own running standard deviation and your scores drift for the first hours after boot.
2. Overlapping windows split across train/test
If windows overlap by 80% and you split randomly, nearly every test window shares samples with a training window. The model memorizes the noise and reports 0.99 AUC.
Split by time, with an embargo equal to at least the window length:
def time_split(df, test_frac=0.2, window_s=60):
cut = int(len(df) * (1 - test_frac))
embargo = window_s # rows, if 1 Hz grid
return df.iloc[: cut - embargo], df.iloc[cut:]
3. Label leakage through maintenance records
A work order created at 09:15 for a fault detected at 09:10 is a label, but if any feature is derived from the maintenance system (e.g., "last service 2 hours ago"), the model learns to read the work-order timestamp rather than the sensor. Audit every feature for a causal path to the label that would not exist at inference time.
4. Aggregates computed after the label timestamp
A 60 s window that extends past the alarm timestamp contains the consequence of the fault. Either center windows strictly before the decision point, or accept that your offline number is optimistic and use a t0 offset:
# features describe the past, label describes the next N seconds
X = features_at(df, t) # only rows <= t
y = any_fault_within(df, t, horizon=300) # only rows > t
5. Resampling that invents data
resample("1s").mean() on a 0.2 Hz sensor forward-fills a slowly changing value across 5 buckets, making it look like a 1 Hz signal. The model learns "this channel is constant", which holds in training and breaks when the sampling rate changes. Either resample to a rate the sensor actually supports, or mark interpolated rows and never use them for training labels.
Training/serving parity is a test, not a promise
The only reliable defence is an automated parity check: run the exact same raw inputs through the Python feature code and through the device (or gateway) feature code, and compare.
def assert_parity(raw_chunk, py_features, c_features, tol=1e-3):
for name, py_val in py_features.items():
c_val = c_features[name]
rel = abs(py_val - c_val) / (abs(py_val) + 1e-9)
assert rel < tol, f"{name}: python={py_val:.6f} device={c_val:.6f} rel={rel:.4f}"
Run it in CI against a recorded fixture, and run it again on-device in a self-test at boot when the sensor has a known calibration signal. Without this, you will eventually ship a normalization bug that makes every device confident and wrong.
A feature set that has survived contact with production
For a rotating-machine vibration + temperature decision, this set is a good starting point:
window: 60 s, hop: 10 s
vib: rms, crest_factor, diff_energy, robust_z_max, band_powers(4), dominant_hz
temp: mean, max, rate_of_change_K_per_min, robust_z_max
joint: vib_rms × temp_delta (interaction), load_normalized_rms
context: operating_mode, minutes_since_start, load_bucket
Two notes on the last line. operating_mode is a categorical that must come from the machine, not be inferred — a model that mixes idle and loaded data learns a bimodal "normal" and alerts on every mode change. And load_normalized_rms (vibration divided by a load proxy) is usually the single feature that makes a model transfer between machines and seasons.
Next: On-Device Anomaly Detection — Statistical Baselines vs. Learned Models.
Top comments (6)
Overlapping windows leaking across train and test splits is one of the easiest ways to fool yourself on time-series data. I've seen models hit 0.98+ offline from random splits on sliding windows and completely fall apart on live traffic.
Shipping mu and sd as fixed constants to the device is a good point too. Do you ever run into seasonal drift making those fixed constants go stale on long-running machines, or does load_normalized_rms mostly take care of that?
Both, and the balance matters. On long-running machines the fixed constants do go stale, but slower than people expect: the mu/sd pair drifts with ambient temperature and load mix more than with age, so a machine running the same duty cycle for two years stays close. Where it breaks is a change in the mix: a new product recipe, a different duty cycle, a sensor swap with a different range.
load_normalized_rms absorbs the level shift from load, not the shape change. If the machine starts running a different load profile, RMS normalisation fixes the scale while the ratio features still move, and the model sees a distribution it was never calibrated on.
What works: version the constants with the model, ship them as a calibration bundle, and recompute on a slow cadence, quarterly or triggered by the drift check in post 10. Two rules I would insist on. First, calibration data has to come from that device's own normal windows, not a fleet aggregate, or you bake another machine's behaviour into this one. Second, never recalibrate silently. A fresh mu/sd is a model change and goes through shadow mode, otherwise a bad recalibration is indistinguishable from a sensor fault, which is exactly the case you cannot afford to confuse.
Treating a fresh mu/sd calibration as a model change and running it through shadow mode is a great rule. Silent recalibration masking a real sensor fault is the kind of bug you only catch way too late. Per-device normal windows instead of a fleet aggregate makes total sense too, especially when two machines on paper end up running slightly different load mixes.
One extra guard worth adding: treat the calibration parameters themselves as a metric. We store mu and sd per device keyed by device_id and model_version, and emit a calibration_delta on every refresh, so a step change shows up on a dashboard even while the anomaly score still looks healthy. That is what catches the silent half of silent recalibration. On the load-mix problem, a single normalizer misfires when two machines run different duty cycles, so we either condition on a coarse load bucket or fall back to a robust scale such as MAD, which moves far less when a minority of high-load windows enters the reference set. The per-device reference window still does most of the work.
The embargo between train and test is a great detail. I hadn’t seen it named before. I’m working on day-ahead electricity load forecasting and ran into the same thing from the other side: every input has to be at least 24 hours old, or the model quietly “sees” the answer. Do you size the embargo by the window length alone, or also by how far ahead you’re predicting?
Both, and the number you want is the sum, not the larger of the two. Leakage happens where the training label window overlaps the test feature window, so the embargo has to cover the label horizon plus the oldest datum a test row reaches back to. With day-ahead H = 24h and inputs lagged 24h, the overlap runs out at 48h, so we embargo 48h before rounding up to whole stride steps. If you use a 168h weekly lag as well, that becomes 192h and your usable test set shrinks fast, which is usually the point where people quietly shorten the lag and rediscover the leak. The same arithmetic applies inside cross-validation: purge H + L around every fold boundary, not just the end. Rounding to the sampling stride matters too, since a partial step still leaks.