From Cuts to a Score

Anomaly DetectionMedium+20 XP+20

From Cuts to a Score

An isolation forest has been grown on a table of card payments. Every tree was built on a random sample of sample_size rows and split at random until each point stood alone. For each payment you want to score, you're given its path length in every tree: the number of cuts it took to isolate it.

Raw path lengths are hard to compare: a tree grown on 256 rows needs more cuts for everyone than a tree grown on 16. So the average path length is measured against c(n)c(n)c(n), the path length an ordinary point is expected to need in a random tree built on nnn rows:

c(n)=2H(n−1)−2(n−1)nc(n) = 2H(n-1) - \frac{2(n-1)}{n}c(n)=2H(n−1)−n2(n−1)​

where H(i)H(i)H(i) is the harmonic number

H(i)=1+12+13+⋯+1i,H(0)=0H(i) = 1 + \frac{1}{2} + \frac{1}{3} + \dots + \frac{1}{i}, \qquad H(0) = 0H(i)=1+21​+31​+⋯+i1​,H(0)=0

Use this exact sum, not an approximation of it. A point whose path lengths average hˉ\bar hhˉ gets the anomaly score

s=2−hˉ/c(n)s = 2^{-\bar h / c(n)}s=2−hˉ/c(n)

with nnn = sample_size. A score near 1 means the point was cut off far faster than an ordinary point; a score around 0.5 means it took about as many cuts as expected.

Task: write isolation_scores(path_lengths, sample_size). path_lengths[i] is the list of point i's path lengths, one per tree. Return one score per point, in order, each rounded to 4 decimal places. sample_size is at least 2.

$42 of the $48 range: 7 in 8 cuts land here$12$14$15$17$18$60
cuts: 0

Each cut lands at random between $12 and $60.

$60trees: 0 · average cuts: –
0
1.13
5 cuts
$15trees: 0 · average cuts: –
0
3.93
5 cuts

Dot: the average so far. Thin line: where it settles after thousands of trees.

Grow a few trees. Does $60 always need just one cut?

Examples

path_lengths = [[1, 2, 1], [5, 4, 6], [4, 5, 5], [6, 5, 4], [2, 1, 3]]
sample_size = 16
returns [0.8236, 0.4829, 0.5069, 0.4829, 0.7474]
path_lengths = [[2, 7, 1], [6, 6, 5], [3, 2, 4]]
sample_size = 8
returns [0.5104, 0.3188, 0.5459]

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