Machine learning with Python and scikit-learn: anomaly detection on metrics and incident prediction
A hands-on guide to classic ML for DevOps and SRE: generate synthetic metrics, detect anomalies with IsolationForest, predict incidents with RandomForest, understand precision and recall for alerting, avoid data leakage, and take the model to production with joblib.
AI$ pip install scikit-learn pandas▍Not every AI problem needs an LLM. If the question is “is this latency spike normal?” or “will there be an incident in the next 15 minutes?”, the data is numbers in columns, and classic machine learning answers in milliseconds, with no external call. In this guide you’ll use scikit-learn to detect anomalies in metrics and predict incidents, with synthetic data and real outputs.
This article is part of the AI with Python guide. If the terms are still fuzzy, start with what AI, machine learning, and LLMs are.
When classic ML beats an LLM
LLMs are great with text. Infrastructure metrics, however, are tabular data, and that’s where classic models are usually the simpler choice.
| Criterion | Classic ML (scikit-learn) | LLM |
|---|---|---|
| Data type | Tables and numeric series | Text, code, natural language |
| Cost per prediction | Local CPU, next to nothing | Tokens or GPU |
| Latency | Milliseconds | Seconds |
| Explainability | Feature importance, visible rules | Hard to audit |
| Reproducibility | Same input, same output | May vary between calls |
| Where it shines | Anomalies, forecasting, metric classification | Summaries, text triage, natural-language interface |
The two complement each other: the classic model detects, and the LLM summarizes the context for the on-call engineer.
Setting up the environment
The examples were tested on November 25, 2026 with Python 3.15, numpy 2.5.5, pandas 3.1.1, and scikit-learn 1.9.1.
python3 -m venv .venv
source .venv/bin/activate
pip install scikit-learn pandas
python -c "import sklearn, joblib; print(sklearn.__version__, joblib.__version__)"
1.9.1 1.6.0
numpy and joblib come in as scikit-learn dependencies; no need to install them separately.
Generating synthetic metrics
Let’s simulate one week of metrics for a service, one row per minute: CPU, p95 latency, and error rate. The generator injects 30 incidents (20 minutes of gradual degradation, with varying intensity, before 10 minutes of failure), false alarms that go away on their own, and 15 isolated one-minute spikes. The fixed seed guarantees the same numbers as this article.
import numpy as np
import pandas as pd
def generate_metrics(days=7, n_incidents=30, n_false=60, n_spikes=15, seed=42):
rng = np.random.default_rng(seed) # fixed seed: same numbers every run
n = days * 24 * 60 # one row per minute
minute = np.arange(n) % 1440
cycle = np.sin(2 * np.pi * (minute - 360) / 1440) # load rises by day, drops at night
cpu = 45 + 15 * cycle + rng.normal(0, 3, n)
lat = 180 + 30 * cycle + rng.normal(0, 12, n)
err = np.clip(rng.normal(0.5, 0.25, n), 0, None)
incident = np.zeros(n, dtype=int)
spike = np.zeros(n, dtype=int)
# incidents: 20 min of gradual degradation, then 10 min of failure
block = n // n_incidents
for i in range(n_incidents):
start = i * block + rng.integers(60, block - 60)
ramp = np.linspace(0, 1, 20) * rng.uniform(0.2, 1.0) # weak or strong signal
cpu[start - 20:start] += 25 * ramp
lat[start - 20:start] += 250 * ramp
err[start - 20:start] += 1.5 * ramp
cpu[start:start + 10] += 35
lat[start:start + 10] += 600
err[start:start + 10] += 6
incident[start:start + 10] = 1
# false alarms: degradations that go away on their own (deploy, GC, backup...)
for start in rng.integers(30, n - 30, n_false):
if incident[start - 30:start + 30].any():
continue
shape = np.concatenate([np.linspace(0, 1, 10), np.linspace(1, 0, 10)])
cpu[start:start + 20] += 20 * shape
lat[start:start + 20] += 200 * shape
err[start:start + 20] += 1.2 * shape
# isolated one-minute spikes, no incident
for start in rng.choice(np.flatnonzero(incident == 0), n_spikes, replace=False):
cpu[start] = rng.uniform(92, 99)
lat[start] += rng.uniform(500, 900)
spike[start] = 1
return pd.DataFrame(
{"cpu_pct": cpu.clip(0, 100).round(1),
"latency_p95_ms": lat.round(0),
"error_pct": err.round(2),
"incident": incident,
"injected_spike": spike},
index=pd.date_range("2026-11-01", periods=n, freq="min", name="minute"),
)
if __name__ == "__main__":
df = generate_metrics()
print(df.shape)
print(df.head(3).to_string())
print(df[["incident", "injected_spike"]].sum())
Save it as data.py and run python data.py:
(10080, 5)
cpu_pct latency_p95_ms error_pct incident injected_spike
minute
2026-11-01 00:00:00 30.9 131.0 0.47 0 0
2026-11-01 00:01:00 26.9 147.0 0.47 0 0
2026-11-01 00:02:00 32.3 172.0 1.13 0 0
incident 300
injected_spike 15
dtype: int64
The incident and injected_spike columns are the answer key: the anomaly model never sees them, but they let us check the result.
Anomaly detection with IsolationForest
IsolationForest is unsupervised: it needs no labeled examples. It splits the points with random cuts; rare points get isolated after just a few cuts and receive a low score. It’s a good start when you don’t have an organized incident history yet.
Train and flag
from sklearn.ensemble import IsolationForest
from data import generate_metrics
df = generate_metrics()
columns = ["cpu_pct", "latency_p95_ms", "error_pct"]
model = IsolationForest(n_estimators=200, contamination=0.01, random_state=42)
model.fit(df[columns])
df["anomaly"] = model.predict(df[columns]) # -1 = anomaly, 1 = normal
df["score"] = model.decision_function(df[columns]) # the lower, the stranger
suspects = df[df["anomaly"] == -1]
print(f"minutes flagged: {len(suspects)} of {len(df)}")
print(f"injected spikes found: {suspects['injected_spike'].sum()} of {df['injected_spike'].sum()}")
print(f"flagged inside incidents: {suspects['incident'].sum()}")
print(suspects.sort_values("score")[columns + ["score"]].head(5).round(3).to_string())
Real output of python anomalies.py:
minutes flagged: 101 of 10080
injected spikes found: 12 of 15
flagged inside incidents: 84
cpu_pct latency_p95_ms error_pct score
minute
2026-11-05 13:22:00 95.4 809.0 7.10 -0.029
2026-11-01 10:13:00 94.7 825.0 6.79 -0.026
2026-11-04 13:43:00 96.7 790.0 6.00 -0.025
2026-11-02 12:21:00 95.6 810.0 6.82 -0.025
2026-11-06 17:05:00 98.1 1004.0 1.21 -0.024
Of the 101 minutes flagged, 84 are inside incidents and 12 are injected spikes, like the last row: very high CPU and latency, normal errors.
How contamination works
contamination is the fraction of training points you expect to be anomalous. It doesn’t change the trees, only the threshold: with 0.01, the 1% of points with the lowest score become -1. See the effect by changing the value:
from sklearn.ensemble import IsolationForest
from data import generate_metrics
df = generate_metrics()
columns = ["cpu_pct", "latency_p95_ms", "error_pct"]
for c in ["auto", 0.005, 0.01, 0.03, 0.05]:
m = IsolationForest(n_estimators=200, contamination=c, random_state=42).fit(df[columns])
flagged = m.predict(df[columns]) == -1
print(f"contamination={c!s:<6} flagged={flagged.sum():>4} "
f"spikes={df['injected_spike'][flagged].sum():>2}/15 "
f"incident_min={df['incident'][flagged].sum():>3}/300")
contamination=auto flagged=1454 spikes=15/15 incident_min=300/300
contamination=0.005 flagged= 51 spikes= 7/15 incident_min= 40/300
contamination=0.01 flagged= 101 spikes=12/15 incident_min= 84/300
contamination=0.03 flagged= 303 spikes=15/15 incident_min=279/300
contamination=0.05 flagged= 504 spikes=15/15 incident_min=300/300
The default "auto" uses the threshold from the algorithm’s original paper and, here, flagged 1,454 minutes: one alert every seven minutes. Start from the rate your team can actually investigate.
Predicting incidents in the next 15 minutes
The real win is warning before it happens. That’s supervised learning: the incident history becomes the label used to train a classifier.
Features that only look at the past
A single minute doesn’t show that “latency is climbing.” We create trend features: 5- and 15-minute rolling means and the change over the last 5. The target is 1 if there’s an incident in the next 15 minutes.
import pandas as pd
from data import generate_metrics
METRICS = ["cpu_pct", "latency_p95_ms", "error_pct"]
def build_features(df, horizon=15):
X = pd.DataFrame(index=df.index)
for col in METRICS:
X[col] = df[col]
X[f"{col}_mean5"] = df[col].rolling(5).mean() # only looks backward
X[f"{col}_mean15"] = df[col].rolling(15).mean()
X[f"{col}_delta5"] = df[col] - df[col].shift(5) # how much did it rise in 5 min?
# target: will there be an incident in any of the next 15 minutes?
future = pd.concat([df["incident"].shift(-k) for k in range(1, horizon + 1)], axis=1)
y = future.max(axis=1)
# keep only what can be predicted: minutes that are still healthy, with full windows
ok = X.notna().all(axis=1) & future.notna().all(axis=1) & (df["incident"] == 0)
return X[ok], y[ok].astype(int)
if __name__ == "__main__":
X, y = build_features(generate_metrics())
print(X.shape)
print(y.value_counts())
(9751, 12)
0 9301
1 450
Name: count, dtype: int64
We drop the minutes when the incident is already happening. That leaves 450 positives against 9,301 negatives, under 5%.
Training with a Pipeline
A Pipeline bundles preprocessing and model into a single object. RandomForestClassifier doesn’t need scaling, but StandardScaler keeps a swap to LogisticRegression one line away.
Watch out for train_test_split: by default it shuffles the rows, which puts future minutes in the training set. Use shuffle=False to train on the past and test on the future.
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from data import generate_metrics
from features import build_features
X, y = build_features(generate_metrics())
# shuffle=False: train on the first 70% of time, test on the future
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, shuffle=False
)
model = Pipeline([
("scale", StandardScaler()),
("rf", RandomForestClassifier(
n_estimators=200, class_weight="balanced", random_state=42, n_jobs=-1
)),
])
model.fit(X_train, y_train)
predicted = model.predict(X_test)
print(classification_report(y_test, predicted, target_names=["normal", "incident"]))
importance = pd.Series(
model.named_steps["rf"].feature_importances_, index=X.columns
).sort_values(ascending=False)
print(importance.head(6).round(3).to_string())
Output of python train.py:
precision recall f1-score support
normal 0.99 0.99 0.99 2791
incident 0.79 0.76 0.77 135
accuracy 0.98 2926
macro avg 0.89 0.87 0.88 2926
weighted avg 0.98 0.98 0.98 2926
latency_p95_ms 0.227
error_pct_mean5 0.178
latency_p95_ms_delta5 0.170
latency_p95_ms_mean5 0.164
error_pct 0.052
error_pct_mean15 0.051
Ignore the 0.98 accuracy: always answering “normal” would be right more than 95% of the time here. Look at the incident row.
Precision, recall, and alert fatigue
- Precision (0.79): of the minutes when the model alerted, how many really came before an incident. Low precision means false positives, that is, people woken up for nothing and alert fatigue.
- Recall (0.76): of the minutes that preceded incidents, how many the model caught. Low recall means incidents that arrive without warning.
predict uses a 0.5 threshold, but you can pick another one with predict_proba. Add this to the end of train.py:
from sklearn.metrics import precision_score, recall_score
prob = model.predict_proba(X_test)[:, 1] # probability of an incident
for threshold in [0.3, 0.5, 0.7]:
alert = (prob > threshold).astype(int)
print(f"threshold={threshold} alerts={alert.sum():>3} "
f"precision={precision_score(y_test, alert):.2f} "
f"recall={recall_score(y_test, alert):.2f}")
The new lines in the output:
threshold=0.3 alerts=175 precision=0.65 recall=0.84
threshold=0.5 alerts=129 precision=0.79 recall=0.76
threshold=0.7 alerts= 91 precision=0.96 recall=0.64
At 0.7, almost every alert is real, but a third of the warnings are lost. To page someone in the middle of the night, prefer high precision; for a chat channel, you can accept more noise. The team decides, not the model.
What the model looked at
feature_importances_ shows how much each feature helped the trees. p95 latency and its trends add up to more than half; CPU doesn’t even make the top 6, because in this data it rises together with latency, and among redundant features the forest tends to favor one. This importance can favor features with many distinct values; for a second opinion, use sklearn.inspection.permutation_importance.
Classic mistakes (and how to avoid them)
The script below measures recall with cross-validation in four ways; three of them show a common mistake:
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import KFold, TimeSeriesSplit, cross_val_score
from data import generate_metrics
from features import build_features
df = generate_metrics()
X, y = build_features(df)
# WRONG: center=True computes the mean with 7 minutes from the future
X_leaky = X.copy()
X_leaky["lat_centered"] = df["latency_p95_ms"].rolling(15, center=True).mean()
def recall(X, cv, class_weight="balanced"):
rf = RandomForestClassifier(
n_estimators=200, class_weight=class_weight, random_state=42, n_jobs=-1
)
return cross_val_score(rf, X, y, cv=cv, scoring="recall").mean()
time_based = TimeSeriesSplit(n_splits=5)
shuffled = KFold(n_splits=5, shuffle=True, random_state=42)
print(f"TimeSeriesSplit (baseline): {recall(X, time_based):.2f}")
print(f"shuffled KFold: {recall(X, shuffled):.2f}")
print(f"with a leaky feature: {recall(X_leaky, time_based):.2f}")
print(f"without class_weight='balanced': {recall(X, time_based, None):.2f}")
TimeSeriesSplit (baseline): 0.75
shuffled KFold: 0.85
with a leaky feature: 0.79
without class_weight='balanced': 0.66
- Shuffling a time series. Shuffled
KFoldpromises 0.85, but that’s optimism: neighboring minutes, nearly identical, land in both training and test.TimeSeriesSplitalways trains on the past and validates on the following period, just like production. - Data leakage. A feature that sees the future, such as
rolling(..., center=True), improves the number in the notebook, but in production that future doesn’t exist. Every feature must be computable from the data available at that minute. Fit theStandardScalerinside thePipeline, on training data only. - Class imbalance. With under 5% positives, answering “normal” is almost always right.
class_weight="balanced"gives the rare class more weight and raised recall from 0.66 to 0.75.
Saving and loading with joblib
Save the whole pipeline, scaler and model together. Add this to the end of train.py:
import joblib
joblib.dump(model, "incident_model.joblib")
loaded = joblib.load("incident_model.joblib")
risk = pd.Series(loaded.predict_proba(X_test)[:, 1], index=X_test.index)
print(risk[risk > 0.5].head(5).round(2).to_string())
minute
2026-11-05 23:03:00 0.63
2026-11-06 00:32:00 0.60
2026-11-06 00:34:00 0.70
2026-11-06 01:01:00 0.68
2026-11-06 01:07:00 0.56
- Security: joblib uses pickle under the hood, and loading a pickle can execute arbitrary code. Never load a model from an untrusted source. Treat the file as a build artifact: produced by your pipeline, stored in a controlled repository, with its hash checked. The scikit-learn documentation mentions alternatives such as skops and ONNX.
- Version: load it with the same scikit-learn version used for training; pin it in
requirements.txt.
Taking it to production
Two common formats; the first one covers most cases:
| Format | How it works | When to use |
|---|---|---|
| Batch job | A CronJob reads the last 15 minutes of metrics, calls predict_proba, and publishes the risk as a metric |
Predictions every minute, no synchronous dependency |
| Small API | An HTTP service loads the model once and answers predictions on demand | Other systems need to query the risk right away |
In the batch job, the risk becomes a regular time series and alerting stays in Alertmanager, with deduplication: ten consecutive minutes above the threshold are one alert. After the deploy, keep three habits:
- Retraining: schedule it (for example, weekly) with the new incidents and compare the new model with the current one over the same period before switching.
- Drift monitoring: traffic changes and the model ages. Compare recent features with the training ones. Add this to the end of
train.py:
# drift: how far the last day's mean moved from training, in standard deviations
last_day = X_test.tail(1440)
drift = ((last_day.mean() - X_train.mean()) / X_train.std()).abs()
print(drift.sort_values(ascending=False).head(3).round(2).to_string())
latency_p95_ms_mean5 0.06
latency_p95_ms 0.05
latency_p95_ms_mean15 0.05
The values are low because the synthetic data doesn’t change. In production, alert when any feature crosses a limit.
- Quality over time: log every alert and whether it became an incident; real precision and recall only show up with that history. LLMOps practices apply to classic models too, and the bigger picture is in AIOps in practice.
The model runs on your infrastructure, and the metrics never leave it. If the features include personal data, such as IPs or user IDs, privacy laws such as Brazil’s LGPD or the GDPR still apply; follow your company’s data policy.
Checklist
- I start with classic ML when the data is tabular and numeric
- I use a fixed seed and synthetic data to test the pipeline end to end
- I choose
contaminationbased on the alert rate the team can investigate - I build features that only look at the past and validate with
TimeSeriesSplit - I evaluate precision and recall for the rare class, not accuracy, and pick the threshold with the team
- I save the whole
Pipelinewith joblib, pin the scikit-learn version, and never load a model from an unknown source - I monitor drift and alert quality, and retrain with new incidents
The best model for your metrics might have just a few hundred trees and fit in a CronJob: start simple, measure honestly, and only then add complexity.