Skip to main content
MahiDev — Learn. Build. Become AI-ready.

Lesson 54

Local Outlier Factor

Compare a point's density with the density of its neighbors, and flag points that sit in a much thinner region. One example is on this page.

Intermediate12 min
Local Outlier Factor MahiDev

What You Will Learn

  • Idea
  • Example
  • When to use it

Idea

Local outlier factor looks at how crowded a point's neighborhood is, then compares that crowd with the neighborhoods of those neighbors. A point in a sparse pocket next to a tight group scores as an outlier even if the whole table has clusters of different sizes.

Example

python
import numpy as np
from sklearn.neighbors import LocalOutlierFactor

X = np.array([[1, 1], [1.1, 0.9], [0.9, 1.2], [1.2, 1.0], [8, 8]], dtype=float)
pred = LocalOutlierFactor(n_neighbors=2, contamination=0.2).fit_predict(X)
print(pred.tolist())

Output:

text
[1, 1, 1, 1, -1]

When to use it

  • Use it when normal data has clusters of different densities.
  • n_neighbors sets the local crowd. Too small and every point looks unique.
  • Again, -1 is the outlier and 1 is inlier.

Loading playground…