Skip to main content

Lesson 6 of 9

Anomaly & Outlier Detection: Isolation Forest, Local Outlier Factor & One-Class SVM

Unsupervised anomaly detection identifies rare observations that differ significantly from the majority of data, without requiring ground truth fraud labels. Three dominant algorithms govern production anomaly detection: Isolation Forest (isolates anomalies via random partitioning trees; anomalies have short path lengths), Local Outlier Factor (LOF; measures local density deviation relative to k-nearest neighbors), and One-Class SVM (fits a tight support vector boundary around the nominal data distribution).

25 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Benchmarking Isolation Forest vs Local Outlier Factor

Benchmarking Isolation Forest vs Local Outlier Factor
import numpy as np
import pandas as pd
from sklearn.ensemble import IsolationForest
from sklearn.neighbors import LocalOutlierFactor
from sklearn.preprocessing import StandardScaler

# Generate synthetic normal transactions + 2% anomalous fraud injections
np.random.seed(42)
n_normal = 1000
amount = np.random.normal(50, 15, n_normal)
frequency = np.random.poisson(3, n_normal)

# Injected anomalies: high amount OR high frequency OR unusual combination
n_anom = 20
anom_amount = np.random.uniform(150, 300, n_anom)
anom_freq = np.random.uniform(10, 20, n_anom)

X = np.column_stack([
    np.concatenate([amount, anom_amount]),
    np.concatenate([frequency, anom_freq])
])
X_scaled = StandardScaler().fit_transform(X)

# 1. ISOLATION FOREST
# Contamination specifies expected proportion of anomalies in the dataset
iso = IsolationForest(contamination=0.02, random_state=42)
# -1 indicates anomaly, 1 indicates normal
iso_preds = iso.fit_predict(X_scaled)
iso_scores = iso.decision_function(X_scaled) # Lower score = more anomalous

# 2. LOCAL OUTLIER FACTOR (LOF)
lof = LocalOutlierFactor(n_neighbors=20, contamination=0.02)
lof_preds = lof.fit_predict(X_scaled)
lof_scores = -lof.negative_outlier_factor_ # Higher score = more anomalous

df_results = pd.DataFrame({
    'Actual Anomaly': [0]*n_normal + [1]*n_anom,
    'IsoForest Predicted': (iso_preds == -1).astype(int),
    'LOF Predicted': (lof_preds == -1).astype(int),
    'Iso Score': iso_scores.round(3),
    'LOF Score': lof_scores.round(3)
})

print("=== ANOMALY DETECTION BENCHMARK ===")
print(f"Total True Injected Anomalies: {n_anom}")
print(f"Isolation Forest Caught      : {df_results[df_results['Actual Anomaly'] == 1]['IsoForest Predicted'].sum()} / {n_anom}")
print(f"Local Outlier Factor Caught  : {df_results[df_results['Actual Anomaly'] == 1]['LOF Predicted'].sum()} / {n_anom}")

Pro Tip: When to Choose Isolation Forest Over LOF

Isolation Forest has O(N log N) time complexity and linear memory scaling, making it ideal for large-scale production scoring. Local Outlier Factor (LOF) has O(N²) neighbor search complexity and slow inference latency. Default to Isolation Forest for real-time APIs.

Diagram
Loading diagram…

MlAnomalyDetection Visual Representation

Hands-On Challenge: Build a Semi-Supervised Anomaly Detector

Train a `OneClassSVM(kernel='rbf', nu=0.05)` on 100% clean normal data. Evaluate its ability to detect anomalies in a corrupted test stream, plotting the support vector boundary contours.

Quick Quiz & Key Concept Checks

Common Pitfall: Setting Contamination to an Arbitrary Number

The `contamination` parameter directly sets the threshold for classifying anomalies. Setting `contamination=0.10` guarantees that exactly 10% of your data will be flagged as anomalies, regardless of how clean the data actually is. In production, inspect raw decision scores rather than hard thresholded labels.

Topics in This Module

0/9 done