Skip to Content
OchreML
Clustering, Neighbors & NB

LocalOutlierFactor

Unsupervised outlier and novelty detection using local density deviation (LOF).

Overview & Backend Support

LocalOutlierFactor (LOF) measures the local density deviation of each sample relative to its n_neighbors nearest neighbors. Samples with substantially lower density than their neighbors are flagged as outliers (-1), while normal samples are labeled as inliers (1).

  • Modes:
    • Outlier detection (novelty=False, default): Call fit_predict(X) to detect outliers within the training set.
    • Novelty detection (novelty=True): Call fit(X_train) on clean data, then use predict(X_new), decision_function(X_new), and score_samples(X_new) on unseen queries.
  • Backend primitives: N3 (pairwise_l2_sq) and N4 (topk_argmin) across CPU (Rayon), CUDA, wgpu, and Google TPU for "euclidean" distance; "manhattan" and "cosine" metrics are also supported.
  • Incremental learning (partial_fit): Not supported.
  • Persistence: Supports binary .dit serialization via save(path), LocalOutlierFactor.load(path, device=...), ochreml.save(), and ochreml.load().

Import & Signature

from ochreml.neighbors import LocalOutlierFactor
# also available from:
from ochreml.cluster_advanced import LocalOutlierFactor
from ochreml import LocalOutlierFactor

LocalOutlierFactor(
    n_neighbors: int = 20,
    contamination: str | float | None = "auto",
    novelty: bool = False,
    metric: str = "euclidean",
    device: str | None = None,
)

Parameters

ParameterTypeDefaultDescription
n_neighborsint20Number of neighbors used for k-nearest-neighbor density estimation.
contamination"auto" | float | None"auto"Expected proportion of outliers in (0.0, 0.5]. When "auto" or None, the decision offset is set to -1.5.
noveltyboolFalseWhen False, enables fit_predict for training-set outlier detection. When True, enables predict, decision_function, and score_samples for unseen data.
metric{"euclidean", "manhattan", "cosine"}"euclidean"Distance metric used for neighbor queries.
devicestr | NoneNoneTarget compute device ("auto", "cpu", "cuda:0", "wgpu", "tpu:0"). Defaults to ochreml.get_default_device().

Attributes

AttributeTypeDescription
negative_outlier_factor_ndarray of shape (n_samples,) | NoneOpposite LOF scores (float64) of the training samples; lower values indicate stronger outliers (inliers tend to be close to -1.0).
offset_floatThreshold offset used to compute decision_function from score_samples (decision_function(X) = score_samples(X) - offset_).
n_neighbors_intActual number of neighbors used for queries (capped by training set size).
n_features_in_int | NoneNumber of features seen during fit.
device_str | NoneResolved hardware device string used by the underlying Rust model.

Methods

MethodSignatureDescription
fitfit(X, y=None) -> LocalOutlierFactorFit the LOF detector on X.
fit_predictfit_predict(X, y=None) -> ndarrayFit on X and return int64 labels (1 for inlier, -1 for outlier). Only available when novelty=False.
predictpredict(X) -> ndarrayPredict int64 labels (1 for inlier, -1 for outlier) on new queries. Only available when novelty=True.
decision_functiondecision_function(X) -> ndarrayShifted opposite LOF scores (float64); negative values are outliers, non-negative values are inliers. Only available when novelty=True.
score_samplesscore_samples(X) -> ndarrayOpposite LOF scores (float64) for each sample (lower means more abnormal). Only available when novelty=True.
savesave(path: str) -> NoneSave the fitted detector to a binary .dit file.
loadLocalOutlierFactor.load(path: str, device: str | None = None) -> LocalOutlierFactorLoad a fitted detector from a binary .dit file.
toto(device: str) -> LocalOutlierFactorMove estimator compute target to another hardware device.

Example

import numpy as np
from ochreml.neighbors import LocalOutlierFactor

X_train = np.array([
    [0.0, 0.0], [0.1, 0.2], [-0.1, 0.1], [0.2, -0.1],
    [-0.2, -0.1], [0.0, 0.2], [0.1, -0.2],
], dtype=np.float64)

# Novelty detection mode on unseen points
lof = LocalOutlierFactor(n_neighbors=3, novelty=True)
lof.fit(X_train)

X_test = np.array([[0.05, 0.05], [10.0, 10.0]], dtype=np.float64)
print("Predictions (1=inlier, -1=outlier):", lof.predict(X_test))
print("Decision scores:", lof.decision_function(X_test))

On this page