Unsupervised LearningAnomaly DetectionAnomaly Detection

Local Outlier Factor (LOF)

Primary task · Anomaly Detection

Local Outlier Factor (LOF) is an unsupervised learning method in the anomaly detection family. This page summarizes its mechanism, practical uses, important trade-offs, and a browser-based concept explorer.

← Directory
Visual intuition

From data to learned behaviour

Local Outlier Factor (LOF) converts patterns in observed data into a reusable prediction or representation rule. The most useful way to understand it is to watch what internal structure changes during training and how that learned structure changes outputs.

Infographic
1Data2Initial state3Optimise4Validate5InferenceTraining transforms evidence into a reusable model state
Conceptual simulation

Watch the learning mechanism form

The structure below is synchronized with the same training state used by the prediction simulation.

Mechanism view
Training control centre

Control both simulations together

Reset regenerates the synthetic data and model state. Train animates to completion. Pause freezes the animation. Train Step advances one learning stage.

Step 0 / 12
Model simulation

Inspect the learned prediction / representation

Synthetic data are generated locally in your browser.

Model description

Understand Local Outlier Factor (LOF) after watching it learn

This section connects the animation to the actual statistical or computational idea behind the model.

Deep description

Local Outlier Factor (LOF) Local Outlier Factor (LOF) is an unsupervised learning method in the anomaly detection family. This page summarizes its mechanism, practical uses, important trade-offs, and a browser-based concept explorer.

What is learned. During training, the algorithm builds or adjusts the parameters and internal representation used by Local Outlier Factor (LOF). The core learning mechanism is: Measures the local density of an observation relative to its k-nearest neighbors; points with significantly lower density than neighbors are anomalies.

How training becomes inference. Prepare data → initialise the model state → evaluate the current objective → update parameters or structure → validate progress → use the final state for inference. Once training stops, the fitted state is reused on unseen inputs rather than being reconstructed from scratch. The resulting output is: An anomaly/outlier score and, after thresholding, an inlier/outlier decision.

Why practitioners use it. Identifies anomalies in datasets with varying density regimes where global methods fail. Typical fits include Network intrusion detection, localized sensor malfunction detection.

What to verify before trusting it. Memory-intensive at test time; struggles to generalize to new streaming instances without recomputing neighbor graphs. The visual simulation is intentionally simplified, so real use should still validate preprocessing, data independence, hyperparameters, uncertainty and task-appropriate metrics.

Internal statethe parameters and internal representation used by Local Outlier Factor (LOF)
Typical outputAn anomaly/outlier score and, after thresholding, an inlier/outlier decision.
Good fitNetwork intrusion detection, localized sensor malfunction detection.
Main cautionMemory-intensive at test time; struggles to generalize to new streaming instances without recomputing neighbor graphs.
1Training data→
2Learning objective→
3Internal model state→
4Prediction / representation→
5Evaluation
Intuition

What the model is trying to learn

Local Outlier Factor (LOF) converts patterns in observed data into a reusable prediction or representation rule. The most useful way to understand it is to watch what internal structure changes during training and how that learned structure changes outputs.

Mathematical lens

Core logic

Measures the local density of an observation relative to its k-nearest neighbors; points with significantly lower density than neighbors are anomalies. The mathematical objective determines which model states are considered better, while regularisation and validation constrain how much complexity should be trusted.

Training sequence

How learning progresses

Prepare data → initialise the model state → evaluate the current objective → update parameters or structure → validate progress → use the final state for inference.

Original mechanism

Taxonomy description

Measures the local density of an observation relative to its k-nearest neighbors; points with significantly lower density than neighbors are anomalies.

Evaluation guide

How to evaluate this model responsibly

ValidationChoose validation that matches the independence assumptions of the data.
MetricsUse task-specific primary and complementary metrics.
HPOEstablish a baseline first, then search the parameters that materially change capacity.
Post-processingValidate any downstream transformation on held-out data.
Hyperparameters

Key parameters

n_neighborsTypical: 20

Neighborhood size used for local density.

contaminationTypical: auto

Expected anomaly fraction.

noveltyTypical: False

Whether unseen observations can be scored after fitting.

metricTypical: minkowski

Distance metric.

Use & trade-offs

Where it fits

Typical applications

Network intrusion detection, localized sensor malfunction detection.

Strengths

Identifies anomalies in datasets with varying density regimes where global methods fail.

Limitations

Memory-intensive at test time; struggles to generalize to new streaming instances without recomputing neighbor graphs.

Code example

Minimal Python implementation

# Purpose: demonstrate Local Outlier Factor (LOF) with a small, inspectable example.
# Follow the comments and printed stages to connect each operation with its result.
# Import the library or helper used in this example.
import numpy as np
# Import the library or helper used in this example.
from sklearn.neighbors import LocalOutlierFactor

# Print this intermediate result so you can verify the workflow step by step.
print("STEP 1 · Create normal points plus a few extremes")
# Store this intermediate value with a descriptive name for the next step.
rng = np.random.default_rng(42)
X = np.r_[rng.normal(0, .8, size=(36,2)), [[4.5,4.2],[-4.0,4.3],[4.1,-4.2]]]
# Print this intermediate result so you can verify the workflow step by step.
print("Samples:", len(X))
# Print this intermediate result so you can verify the workflow step by step.
print("STEP 2 · Compare each point's local density with neighbours")
# Configure the estimator or pipeline with the chosen settings.
model = LocalOutlierFactor(n_neighbors=10, contamination=.08)
# Store this intermediate value with a descriptive name for the next step.
labels = model.fit_predict(X)
# Print this intermediate result so you can verify the workflow step by step.
print("STEP 3 · Inspect flagged outliers")
# Print this intermediate result so you can verify the workflow step by step.
print("Detected outliers:", int(np.sum(labels == -1)))
# Print this intermediate result so you can verify the workflow step by step.
print("Most abnormal LOF scores:", np.round(np.sort(model.negative_outlier_factor_)[:3], 2).tolist())
Expected / representative output
STEP 1 · Create normal points plus a few extremes
Samples: 39
STEP 2 · Compare each point's local density with neighbours
STEP 3 · Inspect flagged outliers
Detected outliers: 4
Most abnormal LOF scores: [-8.15, -7.61, -6.84]