27 min read · AI for business · AI technology and models

Alert rules and anomaly detection are not rivals where you must pick one. Each catches a different kind of event. This article shows it with code you can run: 4 days of simulated sensor data, 4 kinds of labeled anomalies, and 7 methods side by side, to see what catches what, how fast, and how many false alarms per day each one raises.
The real problem: so many alerts that nobody looks, and events the threshold cannot see
The problem pulls in two directions. First, fixed thresholds set too wide cause frequent false alarms, so people stop looking. Second, some events never cross a threshold at all, such as a sensor stuck at the same value, a value that creeps up but has not reached the line yet, or a value that is normal under heavy load but abnormal for an idle machine. The same number means different things depending on the machine state. So the choice of method has to start from the kind of event you want to see, not from how modern the algorithm is.
Three hypothetical scenarios
These three cases are hypothetical, made up to illustrate the explanation. They are not BT San's real work, and they contain no real customers or figures.
- Suppose a small factory sets an alert for motor current above 12 A. Every time a heavy batch is fed in, the current gets close to that line and the alarm sounds. Staff start muting it. The problem is that one threshold is used for every machine state.
- Suppose a cold room has a temperature sensor that on some days sticks at the same value for hours. The value is still in the normal range, so no limit rule fires, but the data is no longer usable.
- Suppose a maintenance team wants to know whether a pump's vibration is slowly rising. A fixed threshold only alerts after the value has crossed the line, which may be too late.
What the documentation says
| Topic | What the documentation says | What it means for our code |
|---|---|---|
| Outlier vs novelty | scikit-learn separates outlier detection (the training data contains odd values) from novelty detection (the training data is clean, and new data is judged against it) | We train on a first day that is meant to be clean, so this is the novelty approach. We have to accept that in real work the first day may not be clean |
| Isolation Forest | Randomly pick a feature and a split point. The number of splits needed to isolate a point is its path length. The average over many trees measures normality, and anomalous points are isolated sooner | We wrote a short version with numpy along these lines |
| IsolationForest defaults | n_estimators 100, max_samples auto = min(256, n_samples), contamination auto, and the lower score_samples is, the more anomalous the point | We use 100 trees and 256 samples to match, but score in the opposite direction: the higher, the more anomalous, as the original paper does |
| Score in the original paper | Liu, Ting and Zhou (ICDM 2008) use the average path length, adjusted by an expected value that depends on the sample size. A value near 1 suggests an anomaly, and below 0.5 suggests normal | The c_factor function in iforest.py does this sample-size adjustment |
| Modified z-score | NIST recommends 0.6745 times (x minus median) divided by MAD, and flags values above 3.5 as worth checking further, not as a verdict that they are wrong | robust_z uses this formula, with the median and MAD instead of the mean and standard deviation |
| Control chart | NIST states that a point outside the control limits is one signal, but a non-random pattern, such as most points on one side of the center line, is also a signal even when no point crosses a line | This is why limit rules alone are not enough, and why we check patterns with rate of change and flatline |
| Median | numpy.median of an even number of values is the average of the two middle values | Used to find the median of a window and of the training day |
Overview of the example
All the code is in the folder examples/anomaly-detection-vs-rules/. It uses Python 3 with numpy only, no sklearn, and makes no network connection. Every number in the data is generated by us. Use it as a learning example, not as production code.
| File | What it does |
|---|---|
| data.py | Generates simulated data with 3 channels plus the machine state, with event labels, and reads CSV files that have blanks or text |
| detectors.py | The limit rule, the rate-of-change rule, the flatline rule, the rolling-window z-score, and the state-aware z-score |
| iforest.py | A short version of Isolation Forest written with numpy |
| alarm_mgmt.py | Merges signals into single events and lets the methods vote |
| metrics.py | Scores at the event level: was it caught, how late, and how many false alarms |
| pipeline.py / demo.py / sweep.py | Runs every method on the same data, prints the tables, and tries several seeds |
| sample_edge.csv | Edge-case data: blanks, text, negative values, out-of-range values, a stuck value |
| test_anomaly.py / output.txt | 8 unittest tests and the output of a real run |
The order of work is: generate data where the answers are known, run each detector and have it say which sensor to blame, score the results against the answers, and only then try combining methods and cutting the number of alerts.
Step 1: Generate data with known answers
The data has motor current, vibration, temperature and the machine state from a PLC (0 idle, 1 light, 2 heavy), sampled once a minute for 4 days. The first day is normal and is kept for training. Temperature follows the load slowly, as in real equipment that has thermal lag. There are 4 kinds of injected anomalies: spike (a short jump in value), drift (a slow rise), stuck (the sensor holds the same value), and context (current 5 A higher while the machine is idle, which is still below the limit line but wrong for that state).
def make_data(seed=7):
rng = np.random.default_rng(seed)
# machine state from the PLC: 0 idle, 1 light, 2 heavy; blocks of 60-179 minutes
raw = np.zeros(N)
i, first = 0, [0, 1, 2] # the clean training day must see every state
while i < N:
n = int(rng.integers(60, 180))
raw[i:i + n] = first.pop(0) if first else rng.choice([0, 1, 2], p=[0.35, 0.30, 0.35])
i += n
load = np.convolve(np.pad(raw, (4, 0), mode="edge"), np.ones(5) / 5, mode="valid")
state = np.rint(load).astype(int)
t = np.arange(N)
cur = np.interp(load, [0, 1, 2], [3.0, 7.0, 11.4]) + rng.normal(0, 0.40, N)
vib = np.interp(load, [0, 1, 2], [0.8, 1.2, 1.7]) + rng.normal(0, 0.08, N)
target = np.interp(load, [0, 1, 2], [35.0, 45.0, 55.0]) + 3 * np.sin(2 * np.pi * t / 1440)
temp = np.empty(N)
temp[0] = target[0]
for k in range(1, N): # first-order lag: temperature follows load slowly
temp[k] = temp[k - 1] + 0.02 * (target[k] - temp[k - 1])
temp += rng.normal(0, 0.15, N)
d = {"cur": cur, "vib": vib, "temp": temp, "state": state}The first three state blocks are forced to be 0, 1 and 2 so that the training day sees every state. We did not do this at first, and then hit the warning Mean of empty slice because the training day had no idle state at all.
Step 2: Three rules you can explain
The limit rule compares the value to a fixed line. The rate-of-change rule alerts when the value changes more than a set amount per minute. The flatline rule alerts when the value is exactly the same for 10 samples in a row. All three return results per channel, so an alert can say which sensor is suspected. A missing value (NaN) does not trigger the limit rule, because a missing sensor is the job of a separate missing function.
def fixed_limits(d):
# NaN never alarms here; a dead sensor is the job of missing()
return {ch: np.nan_to_num(d[ch], nan=-1e9) > LIMITS[ch] for ch in CH}
def missing(d):
return np.isnan(d["cur"]) | np.isnan(d["vib"]) | np.isnan(d["temp"])
def rate_rule(d):
return {ch: np.nan_to_num(np.abs(np.diff(d[ch], prepend=d[ch][0]))) > RATE[ch] for ch in CH}def flatline(d, n=10):
"""Same value n samples in a row. Real ADCs are noisy, so exact repeats mean a frozen reading.
simplified: exact equality; production would use a tolerance sized to the sensor resolution."""
out = {}
for ch in CH:
x = d[ch]
out[ch] = np.zeros(len(x), bool)
for k in range(n - 1, len(x)):
if np.ptp(x[k - n + 1:k + 1]) == 0:
out[ch][k] = True
return outStep 3: A robust z-score
The first method compares the latest value with the median and MAD of the past 180 minutes. It uses only past data, and a value above 3.5 is treated as suspicious. The advantage is that it does not need to know the machine state. The drawback is that when the machine goes from idle to heavy, the value jumps and triggers an alert.
def robust_z(x, med, mad):
return 0.6745 * (x - med) / max(mad, 1e-6) # Iglewicz-Hoaglin modified z-score
def rolling_robust_z(d, win=180, thr=3.5):
out = {}
for ch in CH:
x = d[ch]
out[ch] = np.zeros(len(x), bool)
for k in range(win, len(x)):
w = x[k - win:k] # past samples only
med = np.nanmedian(w)
mad = np.nanmedian(np.abs(w - med))
if abs(robust_z(x[k], med, mad)) > thr:
out[ch][k] = True
return outThe second method knows the machine state. It uses the median and MAD of each state from the training day, and compares values against the current state. The threshold is 4, and it skips the 6 samples after a state change because the value is still climbing then. It can catch the context anomaly, but it needs a reliable state signal.
def state_baseline(d, n_train):
"""median and MAD of each channel per machine state, from the clean training day."""
base = {}
for s in (0, 1, 2):
m = d["state"][:n_train] == s
for ch in ("cur", "vib", "temp"):
v = d[ch][:n_train][m]
med = np.median(v)
base[(s, ch)] = (med, np.median(np.abs(v - med)))
return base
def blanking(state):
"""True for samples right after a state change (ramps look odd, state-aware methods skip them)."""
ch = np.r_[False, state[1:] != state[:-1]]
out = np.zeros(len(state), bool)
for k in np.flatnonzero(ch):
out[k:k + BLANK] = True
return out
def state_robust_z(d, base, thr=4.0):
out = {ch: np.zeros(len(d[ch]), bool) for ch in CH}
for s in (0, 1, 2):
m = d["state"] == s
for ch in CH:
med, mad = base[(s, ch)]
z = 0.6745 * (np.nan_to_num(d[ch], nan=med) - med) / max(mad, 1e-6)
out[ch] |= m & (np.abs(z) > thr)
blank = blanking(d["state"])
return {ch: v & ~blank for ch, v in out.items()}Step 4: A short Isolation Forest
Each tree randomly picks a feature and a split point until the depth reaches log2 of the sample size. A short average path length means the point is easy to isolate, which means it is anomalous. The cutoff is the 99.5th percentile of the scores on the training day. We try two variants: with and without the machine state as a feature.
def c_factor(n):
return 0.0 if n <= 1 else 2 * (np.log(n - 1) + 0.5772156649) - 2 * (n - 1) / n
class IForest:
def __init__(self, n_trees=100, sample=256, seed=0):
self.n_trees, self.sample, self.rng = n_trees, sample, np.random.default_rng(seed)
def _build(self, X, depth, limit):
if depth >= limit or len(X) <= 1:
return ("leaf", len(X))
f = int(self.rng.integers(X.shape[1]))
lo, hi = X[:, f].min(), X[:, f].max()
if lo == hi:
return ("leaf", len(X))
cut = self.rng.uniform(lo, hi)
m = X[:, f] < cut
return (f, cut, self._build(X[m], depth + 1, limit), self._build(X[~m], depth + 1, limit))
def fit(self, X):
psi = min(self.sample, len(X))
limit = int(np.ceil(np.log2(psi)))
self.psi = psi
self.trees = [self._build(X[self.rng.choice(len(X), psi, replace=False)], 0, limit)
for _ in range(self.n_trees)]
return self
def _path(self, X, node, depth, out, idx):
if node[0] == "leaf":
out[idx] = depth + c_factor(node[1])
return
f, cut, left, right = node
m = X[idx, f] < cut
self._path(X, left, depth + 1, out, idx[m])
self._path(X, right, depth + 1, out, idx[~m])
def score(self, X):
total = np.zeros(len(X))
for tree in self.trees:
out = np.zeros(len(X))
self._path(X, tree, 0, out, np.arange(len(X)))
total += out
return 2 ** (-(total / self.n_trees) / c_factor(self.psi))Isolation Forest only says that a point is unusual. It does not say which sensor. So we blame the channel with the highest state-aware z-score, a shortcut that the code notes.
def blame(flag, d, base):
"""simplified: Isolation Forest says 'odd', not which sensor. Blame the channel with the
largest per-state z. Production: SHAP-style attribution or per-channel models."""
out = {ch: np.zeros(len(flag), bool) for ch in CH}
for k in np.flatnonzero(flag):
zs = []
for ch in CH:
med, mad = base[(int(d["state"][k]), ch)]
zs.append(abs(0.6745 * (d[ch][k] - med) / max(mad, 1e-6)))
out[CH[int(np.argmax(zs))]][k] = True
return outStep 5: Merge signals into alerts people can read
When several methods fire at the same time, that should not turn into dozens of alerts. Episodes merges flagged samples that are no more than 10 minutes apart into a single event.
def episodes(flags, gap=10):
"""Group flagged samples into (start, end) episodes; a quiet stretch longer than gap closes one."""
idx = np.flatnonzero(flags)
if len(idx) == 0:
return []
out, s, prev = [], idx[0], idx[0]
for i in idx[1:]:
if i - prev > gap:
out.append((int(s), int(prev)))
s = i
prev = i
out.append((int(s), int(prev)))
return outThe policy in manage is this: specialized rules such as flatline and rate of change can raise an alert on their own, while the other methods need at least two methods to agree on the same event. It is a cut-down version of alarm management, with no priorities or acknowledgment.
def manage(sources, alone=(), gap=10, votes=2):
"""sources: method name -> {channel: bool array}. One notification per episode.
Methods in 'alone' (specific rules such as flatline) may notify by themselves; the rest
must agree with at least votes-1 other methods inside the same episode.
simplified: no priorities, no acknowledge or shelve state; see the alarm management article."""
union = np.zeros(len(next(iter(sources.values()))["cur"]), bool)
for by_ch in sources.values():
union |= anyflag(by_ch)
notes = []
for s, e in episodes(union, gap):
who = sorted(n for n, f in sources.items() if anyflag(f)[s:e + 1].any())
if set(who) & set(alone) or len(who) >= votes:
chans = sorted({c for n in who for c in CH if sources[n][c][s:e + 1].any()})
notes.append({"start": s, "end": e, "sources": who, "channels": chans})
return notesStep 6: Score at the event level, not the point level
People do not care which points were flagged. They care whether the real event was caught, and how many alerts fired with no event. An event counts as caught when there is an alert from the start of the event until 10 minutes after it ends, and the alert blames the same channel as the event. Delay is the number of minutes from the start of the event to the first alert. Precision is counted per method, on days 2 to 4 only.
def score(by_ch, events, n_train, n):
f = {ch: v.copy() for ch, v in by_ch.items()}
for v in f.values():
v[:n_train] = False # only judge the test days
per_type, delays = {}, {}
for ev in events:
win = f[ev["ch"]][ev["start"]:ev["end"] + 1 + GRACE] # the alarm must blame the right sensor
hit = np.flatnonzero(win)
t = ev["type"]
per_type.setdefault(t, [0, 0])
per_type[t][1] += 1
if len(hit):
per_type[t][0] += 1
delays.setdefault(t, []).append(int(hit[0]))
eps = episodes(anyflag(f), gap=GRACE)
good = 0
for s, e in eps:
good += any(f[ev["ch"]][max(s, ev["start"]):min(e, ev["end"] + GRACE) + 1].any()
for ev in events if s <= ev["end"] + GRACE and e >= ev["start"])
return {"types": per_type, "delay": {t: float(np.median(v)) for t, v in delays.items()},
"episodes": len(eps), "true_episodes": good,
"precision": good / len(eps) if eps else float("nan"),
"false_per_day": (len(eps) - good) / ((n - n_train) / 1440)}def run_all(seed=7):
d, events = make_data(seed)
base = state_baseline(d, N_TRAIN)
blank = blanking(d["state"])
ifs = {}
for name, with_state in (("iforest_no_state", False), ("iforest_state", True)):
X = features(d, with_state)
model = IForest(n_trees=100, sample=256, seed=1).fit(X[:N_TRAIN])
thr = np.quantile(model.score(X[:N_TRAIN]), 0.995)
flag = model.score(X) > thr
if with_state:
flag &= ~blank # state-aware methods skip the ramp after a state change
ifs[name] = blame(flag, d, base)
methods = {"fixed_limits": fixed_limits(d), "rate_rule": rate_rule(d), "flatline": flatline(d),
"rolling_z": rolling_robust_z(d), "state_z": state_robust_z(d, base), **ifs}
combo = {k: methods[k] for k in COMBO}
notes = manage(combo, alone=("flatline", "rate_rule"), gap=10, votes=2)
methods["combined+mgmt"] = to_flags(notes, N)
return d, events, methods, combo, notesReal output
python3 demo.py was run on this machine on 2026-11-21 with seed 7. What follows is the real output of the whole file.
data: 5760 samples, 1/min, day 1 clean (training), days 2-4 test
labelled events:
spike vib start=d2 09:20 length=2 min
spike cur start=d3 07:50 length=1 min
spike cur start=d3 17:00 length=2 min
spike vib start=d4 11:20 length=3 min
drift vib start=d2 19:20 length=600 min
drift temp start=d3 23:40 length=500 min
stuck temp start=d2 14:20 length=240 min
stuck cur start=d3 10:20 length=120 min
context cur start=d2 13:05 length=40 min
context cur start=d3 05:49 length=40 min
context cur start=d3 09:10 length=40 min
recall (found/total) and median delay in minutes, per anomaly type
method spike drift stuck context
fixed_limits 4/4 0.0 1/2 478.0 0/2 - 0/3 -
rate_rule 4/4 0.0 1/2 500.0 2/2 180.0 3/3 40.0
flatline 0/4 - 0/2 - 2/2 9.0 0/3 -
rolling_z 4/4 0.0 2/2 157.5 2/2 60.0 3/3 0.0
state_z 3/4 0.0 2/2 209.5 1/2 58.0 3/3 3.0
iforest_no_state 3/4 0.0 2/2 345.0 1/2 57.0 0/3 -
iforest_state 0/4 - 2/2 347.5 1/2 63.0 0/3 -
combined+mgmt 4/4 0.0 2/2 264.5 2/2 9.0 3/3 3.0
precision = alarm episodes that overlap a real event / all alarm episodes
method episodes real precision false per day
fixed_limits 49 5 0.10 14.7
rate_rule 11 10 0.91 0.3
flatline 2 2 1.00 0.0
rolling_z 24 14 0.58 3.3
state_z 23 13 0.57 3.3
iforest_no_state 20 13 0.65 2.3
iforest_state 8 7 0.88 0.3
combined+mgmt 15 12 0.80 1.0
alarm management on the five combined methods (days 2-4)
flagged samples summed over the 5 methods : 1156
flagged samples after OR : 1043
notifications if every episode is sent (OR) : 62
notifications with the policy (see alarm_mgmt): 15
notes by who raised them: fixed_limits+iforest_state=1, fixed_limits+iforest_state+rate_rule+state_z=1, fixed_limits+iforest_state+state_z=1, fixed_limits+rate_rule+state_z=5, fixed_limits+state_z=2, flatline+iforest_state+rate_rule+state_z=1, flatline+rate_rule=1, rate_rule+state_z=3
edge cases from sample_edge.csv (empty cell, text, negative, out-of-range, frozen value)
row 0 cur=3.1 vib=0.81 temp=35.2 state= 0 -> -
row 1 cur=3.0 vib=0.79 temp=35.1 state= 0 -> -
row 2 cur=nan vib=0.8 temp=35.3 state= 0 -> missing
row 3 cur=3.2 vib=nan temp=35.2 state= 0 -> missing
row 4 cur=-1.5 vib=0.82 temp=35.0 state= 0 -> -
row 5 cur=7.0 vib=1.2 temp=45.0 state= 1 -> -
row 6 cur=7.1 vib=1.19 temp=45.1 state= 1 -> -
row 7 cur=13.4 vib=1.25 temp=45.2 state= 1 -> fixed
row 8 cur=11.5 vib=1.75 temp=55.0 state= 2 -> -
row 9 cur=11.5 vib=1.75 temp=55.0 state= 2 -> -
row 10 cur=11.5 vib=1.75 temp=55.0 state= 2 -> flat(n=3)
row 11 cur=11.6 vib=2.9 temp=72.5 state= 2 -> fixed- The limit rule caught all 4 of 4 spikes, but raised 14.7 false alarms per day, with precision 0.10, because the current under heavy load sits near the 12 A line. It missed all the stuck and context events, caught 1 of 2 drifts, and was 478 minutes late.
- The flatline rule caught both stuck events, within 9 minutes, with zero false alarms. But it sees no other kind of event, so it should sit next to the other rules, not replace them.
- The rate-of-change rule caught 3 of 3 context events, but at 40 minutes, which is when the value came back down, not when the anomaly started. So it should not count as fast.
- The state-aware z-score caught the context events within 3 minutes. The rolling-window version caught them immediately on these events but raised 3.3 false alarms per day. Both have precision of about 0.57 to 0.58.
- Isolation Forest caught both drifts but missed some spikes. With the machine state as a feature, it missed all 4 spikes, because values outside the range it had seen get only a slightly higher score. This is a known limitation. Precision improved to 0.88.
- The ensemble caught 4 of 4 spikes, 2 of 2 drifts, 2 of 2 stuck and 3 of 3 context events, with about 1.0 false alarm per day, and the alerts dropped from 62 to 15 under the voting policy.
Do not read this table as a verdict on which method is best. There are only 11 real events, and each channel has only a few. A single seed can favor one method. That is why sweep.py runs seeds 1 to 8, for a total of 32 spike, 16 drift, 16 stuck and 23 context events.
recall over seeds 1-8 (found/total), and mean false alarm episodes per day
method spike drift stuck context false/day
fixed_limits 29/32 4/16 1/16 0/23 14.3
rate_rule 32/32 9/16 15/16 23/23 0.1
flatline 0/32 0/16 16/16 0/23 0.0
rolling_z 32/32 15/16 16/16 20/23 3.9
state_z 31/32 16/16 10/16 23/23 3.4
iforest_no_state 11/32 13/16 5/16 5/23 2.2
iforest_state 5/32 11/16 4/16 8/23 1.2
combined+mgmt 32/32 13/16 16/16 23/23 1.1The overall picture across 8 seeds matches seed 7 in direction. The limit rule raised 14.3 false alarms per day on average and caught no context events at all (0 of 23). The flatline rule caught 16 of 16 stuck events. The rate-of-change rule caught 15 of 16 stuck events. Isolation Forest caught few spikes (11 and 5 of 32). The ensemble caught 32 of 32 spikes and 23 of 23 context events, but only 13 of 16 drifts, which is lower than some z-scores, with 1.1 false alarms per day on average. All the numbers are valid for this simulated data only.
How the tests work
It uses Python's built-in unittest, run with python3 -m unittest test_anomaly.py. There are 8 tests that cover cases that fail silently and easily: generating the data twice gives the same values and the training day has no events; a flatline needs the full 10 samples to fire; a MAD of zero must not divide by zero; an odd point must get a higher Isolation Forest score than a normal one; blanks and text in a CSV must become NaN and must not trigger the limit rule; and the vote must not let a single noisy method through.
def test_flatline_needs_n_identical_values(self):
x = np.r_[np.arange(5.0), [9.0] * 10, [3.0] * 4, np.arange(5.0)]
d = {"cur": x, "vib": np.arange(len(x)) * 1.0, "temp": np.arange(len(x)) * 2.0}
f = flatline(d, 10)["cur"]
self.assertEqual(int(f.sum()), 1) # only the run of 10 fires, at its last sample
self.assertTrue(f[14]) def test_manage_votes(self):
n = 100
srcs = {"fixed_limits": one(n, cur=[10]), "state_z": one(n, vib=[50]),
"flatline": one(n, temp=[80]), "iforest_state": one(n, vib=[51])}
notes = manage(srcs, alone=("flatline",), gap=5, votes=2)
starts = [x["start"] for x in notes]
self.assertNotIn(10, starts) # one noisy method alone stays silent
self.assertIn(50, starts) # two methods agree
self.assertIn(80, starts) # specific rule may notify alone
self.assertEqual(next(x for x in notes if x["start"] == 50)["channels"], ["vib"])........
----------------------------------------------------------------------
Ran 8 tests in 0.028s
OKIf you take this to real use
- Real data is in a time-series database: pull one range at a time with a query, and compute the median and MAD per state in SQL or ahead of time. Do not load the whole table into memory.
- Large files: read in chunks with a streaming CSV reader, or convert to a columnar format first. This example reads the whole file because it is small.
- Continuous incoming data: the rolling-window z-score can run as a stream by keeping only the latest window. Isolation Forest is trained on a schedule and then scores each new point one at a time.
- Encoding and number formats: files from machines or Excel may be UTF-8 with a BOM, use a comma as the decimal mark, or use Buddhist Era years. Check before reading. This example only checks for blanks and non-numeric text.
- The machine-state signal: if the PLC sends the wrong state or sends it late, the state-aware z-score will be wrong too. Add a rule that checks the state itself.
- Thresholds and timing: every threshold in the example is tuned for the simulated data. It must be adjusted for the real sensors and machines, and someone must be made responsible when an alert fires.
Adapting this to business work
- Cold room or display freezer: use a limit rule based on the product's safety threshold, add a flatline rule to catch a failed sensor, and a baseline by door state, open or closed.
- Pumps or motors in a building: use a z-score by run state together with the vibration trend, to see wear before it crosses the limit line.
- Business data that is not from machines, such as hourly order counts: use the same principle, which is to compare against the normal level for the same time of day, not against a fixed number, and merge alerts down to one event per period.
Common mistakes
- Using the same threshold for every machine state, so there are many false alarms and people stop looking.
- Scoring at the point level instead of the event level, which makes the numbers look better than they are when events are long.
- Reading the Isolation Forest score in the wrong direction: in sklearn, a lower score_samples means more anomalous, but in the original paper a higher score means more anomalous. This example uses the direction of the original paper.
- Trusting Isolation Forest to catch every spike, when values outside the range it has seen get only a slightly higher score.
- Training on data that contains events without knowing it, so the system learns that those events are normal.
- Judging from a few events or a single seed, without trying several datasets.
- Letting every method send alerts straight to people, with no merging or voting layer.
- Forgetting missing values, negative values and out-of-range values, which real data certainly has.
Checklist before use
- Name the kinds of events you want to find, and the cost of a miss or a false alarm.
- Start with rules you can explain, and measure what they miss.
- Collect real past events as the answer key, at least several dozen, not just a few.
- Check that the training data is clean enough and covers every machine state.
- Measure at the event level: caught or not, how late, and false alarms per day.
- Test on several data periods or several seeds before trusting the result.
- Add a layer that merges alerts, and assign a responsible person.
- Schedule a re-check of the baseline whenever the machine or process changes.
Cautions for this example: the data is simulated and does not come from real machines. There are few anomalous events. The numbers change with the seed. Isolation Forest is a short version. Blaming a channel uses a shortcut. The flatline rule uses exactly equal values. The alarm-management layer has no priorities or acknowledgment. It was not tested with real data or real sensors. Use it as a learning example, not as ready-to-use code.
References
- scikit-learn — Novelty and Outlier Detection (Isolation Forest, outlier vs novelty) (accessed 2026-11-21)
- scikit-learn — IsolationForest (defaults, score_samples) (accessed 2026-11-21)
- NIST/SEMATECH e-Handbook — Control charts (accessed 2026-11-21)
- NIST/SEMATECH e-Handbook — Detection of outliers (modified z-score, MAD, 3.5) (accessed 2026-11-21)
- NumPy — numpy.median (accessed 2026-11-21)
- Wikipedia — Isolation forest (Liu, Ting, Zhou, ICDM 2008; score interpretation) (accessed 2026-11-21)




