Isolating a point
Ordito’s head of loss prevention suspects that some cashiers ring up fake returns and keep the cash. He has no examples of fraud to train a classifier on. He can, however, look for those who do not resemble the others.
Isolating is easier than describing
Many methods first describe normality, with a centre and a spread, and then measure how far each point departs from it. Isolation Forest turns the problem around. It picks a random column and a random threshold, divides the points in two, and repeats until the point of interest is left alone.
A point in a dense area has many neighbours, and it takes many cuts to separate it from all of them. An isolated point lies beyond a large empty space, and a random cut has a good chance of falling right there. The number of cuts, averaged over many trees, is the measure: little depth, much anomaly.
In the lab, the 382 cashiers with at least 500 receipts, on two habits: how often they give a manual discount and how many returns they ring up without a receipt.
Three experiments
A random cut. Click a cashier in the middle of the cloud and press “Isola” (isolate): it takes ten cuts or more. Try one far from the group: two or three are often enough.
The average of the cuts. A single tree is luck. With 200 trees the average depth becomes stable, and the points are coloured from the most normal to the most isolated.
The check. Turn on the truly dishonest cashiers, which the repository keeps in a separate folder only for verification. With these two columns the twelve most isolated cashiers are exactly the twelve dishonest ones. On individual returns, in the chapter, the task is much harder: there the frauds blend in with the honest cases.
The same experiment in Python
import numpy as np
import pandas as pd
from sklearn.ensemble import IsolationForest
URL = "https://raw.githubusercontent.com/mid079/machine-learning-teoria-pratica/main/dati/"
scontrini = pd.read_parquet(URL + "scontrini.parquet", columns=["canale", "id_cassiere", "sconto_manuale_pct"])
resi = pd.read_parquet(URL + "resi.parquet")
s = scontrini[scontrini["canale"] == "negozio"]
profilo = pd.DataFrame({
"scontrini": s.groupby("id_cassiere").size(),
"quota_sconto_manuale": (s["sconto_manuale_pct"] > 0).groupby(s["id_cassiere"]).mean(),
"quota_senza_scontrino": resi["id_riga_origine"].isna().groupby(resi["id_cassiere"]).mean()}).fillna(0)
profilo = profilo[profilo["scontrini"] >= 500] # with few receipts the shares are noise
X = profilo[["quota_sconto_manuale", "quota_senza_scontrino"]]
anomalia = -IsolationForest(n_estimators=200, random_state=0).fit(X).score_samples(X) # higher = stranger
infedeli = pd.read_parquet(URL + "verita/cassieri_infedeli.parquet")["id_cassiere"] # only to check
primi = profilo.index[np.argsort(-anomalia)[:12]]
print(primi.isin(infedeli).sum(), "dishonest cashiers among the 12 most isolated")
In the book
This lab accompanies chapter 13, “Anomalies”: the z-score and its robust version, the masking effect, the Mahalanobis distance with the minimum covariance determinant, Isolation Forest from scratch, LOF and evaluation without labels, with precision in the top N.
The “Inside Ordito” series
- Chapter 1 The line of the five stores
- Chapter 2 A simulated store
- Chapter 3 Where the leak hides
- Chapter 4 The valley of the five stores
- Chapter 5 The threshold
- Chapter 6 Why was it returned?
- Chapter 7 Build a tree
- Chapter 8 Boosting step by step
- Chapter 9 The margin
- Workshop A Price is place
- Chapter 10 Shapley by hand
- Chapter 11 Rotate the cloud
- Chapter 12 Groups and dense areas
- Chapter 13 Isolating a point
- Chapter 14 Naive forecasts
- Workshop B A year in production
- Chapter 15 The ink stain
- Chapter 16 Backpropagation