Home AI SkillsDetect Server Metric Anomalies with Python, scikit-learn and AI

Detect Server Metric Anomalies with Python, scikit-learn and AI

by Knowledge Base Linux
Detect Server Metric Anomalies with Python — Detect Server Metric Anomalies with Python, scikit-learn and AI

Threshold alerts cry wolf: CPU above 90% is harmless during a backup and fatal during a traffic spike. Anomaly detection solves this by learning what “normal” looks like for your servers and flagging only the behavior that deviates from it. In this guide you will collect CPU and memory metrics on Linux, train a simple Isolation Forest model with Python and scikit-learn, detect anomalies, and use an LLM to explain the results. This article covers Detect Server Metric Anomalies with Python in detail.

Why Anomaly Detection Beats Static Thresholds – Detect Server Metric Anomalies with Python

Static thresholds encode one person’s guess about every server, for every hour of the week. Anomaly detection flips the model:

  • It learns each server’s own rhythm — nightly backups, weekly batch jobs, business-hour peaks.
  • It catches combinations: CPU slightly high + memory climbing + load unusual for this hour.
  • It reduces alert fatigue, because normal-but-loud behavior stops paging you.
  • It surfaces slow leaks (memory creeping up for days) that threshold alerts notice only at the crash.

Pair it with a conventional tool like Netdata for collection and dashboards; the ML layer adds judgment on top of the raw numbers.

Prerequisites – Detect Server Metric Anomalies with Python

  • An Ubuntu server with Python 3.10+ and pip.
  • Basic Python and comfort reading CSV files.
  • Optional: an LLM API key to generate explanations for detected anomalies.

Step 1: Collect Training Data for Anomaly Detection

You need at least a few days of normal behavior. This tiny collector samples CPU, memory and load every minute into a CSV:

# collect_metrics.py
import csv, os, time
import psutil

FILE = "/var/log/metrics.csv"
new = not os.path.exists(FILE)
with open(FILE, "a", newline="") as f:
    w = csv.writer(f)
    if new:
        w.writerow(["ts", "hour", "cpu", "mem", "load1"])
    w.writerow([int(time.time()), time.localtime().tm_hour,
                psutil.cpu_percent(interval=1),
                psutil.virtual_memory().percent,
                os.getloadavg()[0]])
pip install psutil scikit-learn pandas
echo "* * * * * root /usr/bin/python3 /opt/collect_metrics.py" | sudo tee /etc/cron.d/metrics

Let it run for several days before training — a model trained on one quiet afternoon knows nothing about your real workload. Knowing how to check RAM usage manually helps you sanity-check what the collector records.

Step 2: Train an Isolation Forest Model

Isolation Forest is the standard first choice for anomaly detection on metrics: it needs no labeled incidents and works well on numeric time-series features.

# detect_anomalies.py
import pandas as pd
from sklearn.ensemble import IsolationForest

df = pd.read_csv("/var/log/metrics.csv")
features = df[["hour", "cpu", "mem", "load1"]]

model = IsolationForest(n_estimators=200, contamination=0.01, random_state=42)
model.fit(features)
df["anomaly"] = model.predict(features)   # -1 = anomaly, 1 = normal

bad = df[df["anomaly"] == -1].tail(20)
print(bad.to_string(index=False))

contamination=0.01 tells the model to expect about 1% of points to be anomalous. Run this after a week of collection and inspect what it flags: you should recognize your backup window as normal and (hopefully) spot at least one event you remember being real.

Anomaly detection radar finding an outlier in metric data

Step 3: Score New Data and Alert on Anomalies

In production, load the trained model and score only fresh rows. Persist the model once with joblib:

import joblib
joblib.dump(model, "/opt/anomaly-model.pkl")

Then a small checker scores the last hour and prints a warning your monitoring can pick up, or posts it to chat using the same webhook pattern as a broader AI automation setup:

# check_recent.py
import joblib, pandas as pd, time
model = joblib.load("/opt/anomaly-model.pkl")
df = pd.read_csv("/var/log/metrics.csv")
recent = df[df["ts"] > time.time() - 3600].copy()
recent["anomaly"] = model.predict(recent[["hour", "cpu", "mem", "load1"]])
hits = recent[recent["anomaly"] == -1]
if not hits.empty:
    print(f"ANOMALY: {len(hits)} unusual minutes in the last hour")
    print(hits.tail(5).to_string(index=False))

Step 4: Explain Anomalies with an LLM

A flagged row (“load1 = 14.2 at 03:12”) still needs interpretation. Send the anomalous window plus surrounding context to an LLM with a grounded prompt:

PROMPT:
"The rows below were flagged by an anomaly detection model on server web-01.
Normal load for this hour is 1-3. Explain the most likely operational causes
(a stuck process, a cron job, a traffic spike, a memory leak), and list the
three shell commands I should run first to investigate. Rows: ..."

The model contributes the runbook knowledge; the detector contributes the timing. Together they turn a mysterious graph spike into a short investigation plan.

Troubleshooting

Everything is flagged as an anomaly. Your training data is too short or too uniform. Collect at least a full week including weekends, and lower contamination.

Real incidents are missed. Add features the incident would move: disk I/O wait, network throughput, or per-service metrics. A model can only see the columns you give it.

The nightly backup gets flagged. It is genuinely unusual — but expected. The hour feature usually fixes this after enough training data; if not, exclude known maintenance windows from alerting (not from training).

Results drift over months. Servers change. Retrain monthly on a rolling window of recent data, and version your model files so you can roll back.

Conclusion

Anomaly detection brings statistical judgment to monitoring: learn normal, flag different, explain with AI. The stack in this guide — a 20-line collector, Isolation Forest and an LLM explainer — runs on a single small server and already outperforms a wall of hand-tuned thresholds. Start by shadowing your existing alerts for a month, compare what each system catches, and you will quickly see which pages were signal and which were noise all along.

You may also like

KbLinux

Typically replies within a day

Hello, Welcome to the site. Please click below button for chatting me through Telegram.