Anomaly Detection with Generative Models
The hard part is not scoring outliers â it is keeping the alert queue short enough that humans still read it.
MonitoringPrerequisites
- !Supervised versus unsupervised learning
- !Autoencoders and reconstruction loss
- !Precision, recall and alert fatigue trade-offs
What You'll Learn
- 1Define anomaly relative to a training window instead of an absolute rule
- 2Train an autoencoder and derive a threshold from its reconstruction error
- 3Combine model scores with human triage budgets in production
- 4Handle drift so a slowly changing system does not page anyone at 3 a.m.
An anomaly is a claim about normal
Anomaly detection has a definitional problem that no algorithm solves: outliers are defined relative to normal, and normal is defined by whoever built the training set. A model trained on last quarter's traffic will flag this quarter's successful product launch as anomalous. A fraud detector trained on one region's spending patterns will flag another region's holidays.
The productive framing is that you are not detecting anomalies â you are detecting departures from a reference distribution you chose deliberately, on a time window you refresh deliberately, with an escalation policy you tuned deliberately. Every production system that works has those three choices written down somewhere.
Two failure modes bracket the space. A detector that is too sensitive floods the queue with noise and trains responders to ignore it, which is worse than having no detector at all. A detector that is too conservative misses exactly the events that justify its existence. The lever that controls this trade is the threshold, and the threshold should be set from an operational budget â how many alerts per day a person can actually investigate â rather than from a statistical convention like three standard deviations.
Define the unit of alerting as early as the definition of normal. One anomalous row, one anomalous session and one anomalous customer behave differently: the first might be a sensor blip, the second an outage, the third a compromised account. Systems that score rows but alert on sessions require a grouping layer, and that layer changes the threshold math completely.
Reconstruction with autoencoders
An autoencoder learns to compress normal data and reconstruct it. Examples that resemble the training distribution reconstruct well; anomalous ones do not, because the bottleneck never forced the network to represent them. Reconstruction error becomes an anomaly score with no labels required.
import torch
import torch.nn as nn
class DetectorAE(nn.Module):
"""Compact autoencoder for tabular or sequence features."""
def __init__(self, n_features, latent=16):
super().__init__()
self.encoder = nn.Sequential(
nn.Linear(n_features, 64), nn.ReLU(),
nn.Linear(64, 32), nn.ReLU(),
nn.Linear(32, latent),
)
self.decoder = nn.Sequential(
nn.Linear(latent, 32), nn.ReLU(),
nn.Linear(32, 64), nn.ReLU(),
nn.Linear(64, n_features),
)
def forward(self, x):
return self.decoder(self.encoder(x))
def train_detector(train_loader, n_features, epochs=20, lr=1e-3):
model = DetectorAE(n_features)
opt = torch.optim.Adam(model.parameters(), lr=lr)
loss_fn = nn.MSELoss()
model.train()
for epoch in range(epochs):
total = 0.0
for batch in train_loader:
opt.zero_grad()
loss = loss_fn(model(batch), batch)
loss.backward()
opt.step()
total += loss.item()
print(f"epoch {epoch + 1} recon_loss={total / len(train_loader):.4f}")
model.eval()
return model
def score(model, x):
"""Per-sample reconstruction error as the anomaly score."""
with torch.no_grad():
errors = ((model(x) - x) ** 2).mean(dim=1)
return errors
Two details decide whether this works in practice. Train only on normal data â including anomalies in training teaches the model to reconstruct them, erasing the very signal you care about. And scale features first, because a single high-variance column will dominate the squared error and hide anomalies in every other feature.
Density and distance baselines
Before reaching for neural methods, measure what a simple baseline achieves. Isolation forests, local outlier factor and one-class SVMs are fast, interpretable and often competitive on low-dimensional tabular data. They also give you a reference point: a deep method that beats them by one F1 point is probably not worth its operational complexity.
from sklearn.ensemble import IsolationForest
from sklearn.preprocessing import StandardScaler
import numpy as np
def fit_isolation_baseline(features, contamination=0.01):
"""Fast baseline whose score distribution is easy to calibrate."""
scaler = StandardScaler()
scaled = scaler.fit_transform(features)
model = IsolationForest(
contamination=contamination,
n_estimators=300,
random_state=0,
)
model.fit(scaled)
scores = -model.score_samples(scaled)
return model, scaler, scores
def threshold_from_budget(scores, alerts_per_day, window_rows):
"""Set the threshold so daily alert volume matches triage capacity."""
rows_per_day = window_rows
k = int(alerts_per_day * rows_per_day)
return float(np.sort(scores)[-k])
def compare_methods(real_scores, synthetic_scores):
"""Rank correlation between two scorers â cheap agreement check."""
from scipy.stats import spearmanr
rho, p = spearmanr(real_scores, synthetic_scores)
return {"spearman_rho": float(rho), "p_value": float(p)}
Thresholding from a triage budget is the most transferable idea in this lesson. Instead of arguing about statistical significance, ask how many alerts the team can investigate per day, and place the cut so the queue fits that number.
Feature design beats model choice
Raw measurements are rarely the right input. Anomaly detection works on derived features that describe behavior: rates of change rather than absolute levels, ratios between related quantities, deviation from the same time last week, counts per window. A CPU reading of ninety percent is unremarkable on a batch server at midnight and alarming on a service that idles at ten.
import pandas as pd
def build_features(frame, ts_col="ts", value_col="value", windows=(5, 15, 60)):
"""Rolling context features that make level shifts visible."""
df = frame.sort_values(ts_col).reset_index(drop=True)
base = df[value_col]
feats = pd.DataFrame({"value": base})
feats["diff_1"] = base.diff()
feats["zscore_15"] = (base - base.rolling(15).mean()) / (base.rolling(15).std() + 1e-9)
for w in windows:
feats[f"roll_mean_{w}"] = base.rolling(w).mean()
feats[f"roll_std_{w}"] = base.rolling(w).std()
feats[f"dev_from_{w}"] = base - feats[f"roll_mean_{w}"]
return feats.dropna()
Two traps live here. Features computed with a window that spans the anomaly itself normalize the anomaly away, because the bad period becomes part of its own baseline. And features that leak the future â rolling windows centered instead of trailing â produce evaluation scores that are impossible to reproduce in production, which is how a detector ends up spectacularly good offline and useless once deployed.
LLMs for unstructured signals
Structured sensors have autoencoders; text and logs have language models. An LLM can score whether a support ticket matches the tone of known incidents, extract the failure described in a log excerpt, or compare an access pattern against a written policy. It cannot cheaply score millions of rows, so its role is usually second-stage triage rather than first-stage screening.
import json
from openai import OpenAI
client = OpenAI()
def triage_alert(alert, normal_examples):
"""Second-stage LLM triage of an already-scored anomaly."""
prompt = (
"You are triaging monitoring alerts. Compare the alert to the normal "
"examples and return JSON with keys severity (low/medium/high), "
"reason, and follow_up.\n\n"
f"NORMAL EXAMPLES:\n{normal_examples}\n\n"
f"ALERT:\n{alert}"
)
response = client.chat.completions.create(
model="gpt-4o-mini",
temperature=0,
response_format={"type": "json_object"},
messages=[{"role": "user", "content": prompt}],
)
return json.loads(response.choices[0].message.content)
def escalate_or_log(triage):
if triage["severity"] in ("medium", "high"):
return {"page": True, "summary": triage["reason"], "action": triage["follow_up"]}
return {"page": False, "archive": True, "reason": triage["reason"]}
Keep the LLM out of the paging path for anything latency-critical, and always retain the raw score alongside the LLM's summary. When a reviewer disagrees with a triage decision, the numeric score is the ground truth you can audit; the natural-language rationale is not.
Alert budgets and the queue that gets read
Alert volume is a design constraint, not an accident. The table below shows how thresholds map to operational reality for a service scoring roughly one hundred thousand events per day.
| Alerts per day | Threshold percentile | Typical character | Human cost |
|---|---|---|---|
| 5 | 99.995 | Only extreme events | Low, but misses real incidents |
| 50 | 99.95 | Focused, mostly actionable | Sustainable for one on-call |
| 300 | 99.7 | Heavy, some noise | Needs a triage rotation |
| 1000+ | 99 | Mostly noise | Alerts get ignored entirely |
Deduplication and grouping matter as much as the threshold. Ten alerts from one failing host are one incident; systems that page per event teach responders that the pager is unreliable. Group by root-cause key, attach the affected entities, and send a single escalation with a link to the full affected set.
Drift, seasonality and refreshing the baseline
Normal moves. A detector that never relearns becomes a novelty alarm that fires on every calendar change â month-end batch jobs, holiday traffic, a new client integration. The fix is a reference window that updates on a schedule, paired with a freeze during active incidents so a genuine problem does not redefine itself as normal while you investigate.
class AdaptiveBaseline:
"""Refresh the reference window weekly but never during an incident."""
def __init__(self, model_fn, refresh_days=7):
self.model_fn = model_fn
self.refresh_days = refresh_days
self.frozen_until = None
def maybe_refresh(self, recent_normal, now):
if self.frozen_until and now < self.frozen_until:
return {"refreshed": False, "reason": "incident_freeze"}
if self.last_refresh and (now - self.last_refresh).days < self.refresh_days:
return {"refreshed": False, "reason": "too_soon"}
self.model = self.model_fn(recent_normal)
self.last_refresh = now
return {"refreshed": True, "n": len(recent_normal)}
def freeze(self, until):
"""Called when an incident opens so the model stops adapting."""
self.frozen_until = until
Seasonality needs explicit treatment beyond adaptive windows. If traffic triples every Monday morning, either model the weekly cycle as a feature or compare against the same weekday rather than yesterday. Otherwise the weekly peak becomes a weekly page, and responders learn to expect Monday noise â which is exactly how a real Monday anomaly gets dismissed.
â ī¸Never train on data containing the incident
When an incident is active, incoming events are precisely the ones you do not want in the reference window. Freeze the baseline at incident open and thaw it only after remediation.
Common Mistakes
Setting thresholds from statistical conventions instead of triage capacity
Fix: Derive the threshold from alerts per day the team can actually investigate, then adjust.
Training an autoencoder on a mix of normal and anomalous data
Fix: Fit only on a verified-normal window; anomalies in training teach the model to reconstruct them.
Paging on every scored event instead of grouped incidents
Fix: Group by root-cause key and escalate one summary per incident with the entity list attached.
Letting the baseline retrain during an active incident
Fix: Freeze the reference window when an incident opens and thaw it after remediation closes.
Best Practices
- Establish a simple density baseline before investing in deep reconstruction models
- Scale features before computing reconstruction error
- Set thresholds from an explicit alerts-per-day budget
- Use LLMs for second-stage triage, not first-stage screening at volume
- Document what normal means, and review it whenever the product changes
Key Takeaways
- Anomalies are departures from a reference you chose, on a window you refresh
- Autoencoder reconstruction error works only when training data is verified normal
- Thresholds should come from triage capacity, not from statistical habit
- Group alerts into incidents or responders will stop reading them
- Freeze baselines during incidents so the model cannot learn the outage as normal