python 14 lines · 1 tab

Anomaly detection with isolation forest and robust thresholds

1 tab
import pandas as pd
from sklearn.ensemble import IsolationForest

df = pd.read_csv('service_metrics.csv')
features = df[['latency_p95', 'error_rate', 'throughput', 'cpu_utilization']]

detector = IsolationForest(
    n_estimators=300,
    contamination=0.02,
    random_state=42,
)
df['anomaly_score'] = detector.fit_predict(features)
anomalies = df[df['anomaly_score'] == -1]
print(anomalies.head())
1 file · python Explain with highlit

Anomaly detection is mostly about defining normal behavior well enough that deviations matter. I usually combine a model like IsolationForest with feature windows and operational thresholds that the business can interpret. Without that calibration, anomaly alerts just become background noise.

Share this code

Here's the card — post it anywhere.

Anomaly detection with isolation forest and robust thresholds — share card
Link copied