Local Outlier Factor (LOF) anomaly detection algorithm.
Classes
class algorithms.anomaly.local_outlier_factor.LocalOutlierFactorDetector(Classifier)
Local Outlier Factor for density-based anomaly detection.
__init__( self, n_neighbors: int = 20, contamination: float = 0.1, metric: str = 'euclidean', novelty: bool = False, )
Overview
The algorithm works through four main steps:
- Find the k-nearest neighbors for each point
- Compute the reachability distance (smoothed distance to neighbors)
- Calculate Local Reachability Density (LRD) for each point
- Compute the LOF score as the ratio of neighbor densities to point density
Theory
For a point A with k-nearest neighbors N_k(A):
1. k-distance: Distance to the k-th nearest neighbor
2. Reachability distance:
This "smooths" distances to prevent instability when points are very close.
3. Local Reachability Density (LRD):
Higher LRD → point is in a denser region.
4. Local Outlier Factor:
Score interpretation:
- \text{LOF} \approx 1 → Normal point (similar density to neighbors)
- \text{LOF} < 1 → Denser than neighbors (inlier)
- \text{LOF} > 1 → Sparser than neighbors (outlier)
- \text{LOF} \gg 1 → Strong outlier
Parameters
n_neighbors
contamination
(0, 0.5]. Used to set the decision threshold.
metric
Distance metric for computing neighbor distances:
- •
"euclidean": Euclidean (L2) distance - •
"manhattan": Manhattan (L1) distance - •
"chebyshev": Chebyshev (L∞) distance
novelty
Detection mode:
- •
False: Outlier detection (fit and predict on same data) - •
True: Novelty detection (predict on new, unseen data)
Attributes
X_train_
neighbors_indices_
neighbors_distances_
lrd_
lof_scores_
threshold_
n_features_in_
fit().
Notes
Complexity:
- Training: O(n^2 \log n) where n = number of samples
- Prediction: O(n \cdot k) where k = n_neighbors
- Data with varying local densities (clusters of different densities)
- When global outlier detection is insufficient
- Medium-sized datasets (becomes slow for very large datasets)
- When you want interpretable density-based scores
- Quadratic complexity limits scalability to large datasets
-
Sensitive to choice of
n_neighborsparameter - Requires storing training data for novelty detection
- Performance degrades in very high dimensions (curse of dimensionality)
References
See Also
Basic usage for outlier detection:
>>> from tuiml.algorithms.anomaly import LocalOutlierFactorDetector
>>> import numpy as np
>>>
>>> # Create data with one clear outlier
>>> X = np.array([[1, 2], [2, 3], [3, 3], [2, 2], [10, 10]])
>>>
>>> # Fit and predict on training data
>>> clf = LocalOutlierFactorDetector(n_neighbors=3, contamination=0.2)
>>> predictions = clf.fit_predict(X)
>>> print(predictions)
[ 1 1 1 1 -1]
Novelty detection on new data:
>>> # Train on normal data
>>> X_train = np.array([[1, 2], [2, 3], [3, 3], [2, 2]])
>>> X_test = np.array([[2.5, 2.5], [10, 10]])
>>>
>>> # Use novelty mode to predict on new data
>>> clf = LocalOutlierFactorDetector(n_neighbors=3, novelty=True)
>>> clf.fit(X_train)
>>> predictions = clf.predict(X_test)
>>> print(predictions)
[ 1 -1]
>>>
>>> # Get LOF scores
>>> scores = clf.decision_function(X_test)
Methods
fit
(self, X: np.ndarray, y: Optional[np.ndarray]=None) -> 'LocalOutlierFactorDetector'
fit
(self, X: np.ndarray, y: Optional[np.ndarray]=None) -> 'LocalOutlierFactorDetector'
Fit the LOF model.
Parameters
X
y
Returns
self
fit_predict
(self, X: np.ndarray, y: Optional[np.ndarray]=None) -> np.ndarray
fit_predict
(self, X: np.ndarray, y: Optional[np.ndarray]=None) -> np.ndarray
Fit and predict anomalies in training data.
Parameters
X
y
Returns
predictions