Judged by Its Own Crowd

Anomaly DetectionHard+30 XP+30

Judged by Its Own Crowd

The rough version of the Local Outlier Factor divides a point's reach by its neighbours' average reach. The full formula keeps that idea, but averages over all kkk neighbours and smooths the distances. Your job is to implement it exactly.

Points are lists of coordinates (any number of dimensions, no two identical), and d(p,o)d(p, o)d(p,o) is the Euclidean distance between them.

  1. k-distance. kdist(p)\text{kdist}(p)kdist(p) is the distance from ppp to its kkk-th nearest other point.
  2. Neighbourhood. N(p)N(p)N(p) is every other point whose distance from ppp is at most kdist(p)\text{kdist}(p)kdist(p). When several points tie, this can hold more than kkk points: keep them all.
  3. Reachability distance from ppp to one of its neighbours ooo:
reach(p,o)=max⁡(kdist(o), d(p,o))\text{reach}(p, o) = \max\big(\text{kdist}(o),\ d(p, o)\big)reach(p,o)=max(kdist(o), d(p,o))

This is the smoothing: any point inside ooo's own k-distance counts as exactly that far from ooo, so tiny distances inside a crowd don't swing the result.

  1. Local reachability density, one over the average reach:
lrd(p)=∣N(p)∣∑o∈N(p)reach(p,o)\text{lrd}(p) = \frac{|N(p)|}{\sum_{o \in N(p)} \text{reach}(p, o)}lrd(p)=∑o∈N(p)​reach(p,o)∣N(p)∣​
  1. Local Outlier Factor, the neighbours' average density compared with ppp's own:
LOF(p)=1∣N(p)∣∑o∈N(p)lrd(o)lrd(p)\text{LOF}(p) = \frac{1}{|N(p)|} \sum_{o \in N(p)} \frac{\text{lrd}(o)}{\text{lrd}(p)}LOF(p)=∣N(p)∣1​o∈N(p)∑​lrd(p)lrd(o)​

Task: write lof_scores(points, k) returning one LOF per point, in the order given, each rounded to 4 decimal places. You may assume 1≤k<1 \le k <1≤k< the number of points.

A score near 1 means the point is as crowded as its own neighbours, so it fits its region, however sparse that region is. A score well above 1 means it has far more empty space around it than they do.

fits inlooks odd
Neighbours: 84 or more other points in the circle: a dense region
Fewest neighbours+2 more tied

One circle and one cut-off of 4 other points, used everywhere. Every spread-out point reads 0, and even the grid's corners count as sparse.

Examples

points = [[0, 0], [1, 0], [0, 1], [1, 1], [3, 0], [10, 10], [16, 10], [10, 16]]
k = 2
returns [1.0, 1.0, 1.0, 1.0, 2.118, 1.1716, 0.9268, 0.9268]
points = [[0], [1], [2], [3], [7]]
k = 1
returns [1.0, 1.0, 1.0, 1.0, 4.0]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run