Velamuvi AIAcademy

Lesson 6 of 8 · Techniques

Anomaly Detection

Find unusual data without labels: z-score and IQR baselines, IsolationForest, LocalOutlierFactor, OneClassSVM, the contamination setting and precision at k.

  • 16 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Explain what an anomaly is and why it is usually found without labels
  • Flag outliers in a single column with the z-score and IQR rules
  • Detect anomalies across several features with IsolationForest and LocalOutlierFactor
  • Set the contamination parameter, knowing what it changes and what it doesn't
  • Compare detectors with only a few labels, using precision at k

The idea in plain words

An anomaly is a data point that doesn't fit the pattern of the rest: a payment fifty times bigger than usual, a server whose CPU races while nobody is using it, a temperature sensor reading −40 °C in a heated room.

In Handling Imbalanced Classes you caught a rare class, fraud, using labels. Often there are no labels: fraud is confirmed weeks later, if ever, and a new kind of fault has never been seen before. Anomaly detection learns what normal looks like from unlabelled data and gives every point an anomaly score: the higher the score, the stranger the point. You then decide how many of the strangest points someone should look at.

Two warnings before any code. Unusual isn't the same as bad: a big purchase may be for a wedding. And bad isn't always unusual: careful fraudsters copy normal behaviour. A detector produces a ranked list for people to review, not verdicts.

Baselines for one column: z-score and IQR

Start simple. For a single column, two classic rules flag values far from the middle:

z-score rule:  z = (value − mean) ÷ standard deviation; flag z above 3 or below −3
IQR rule:      Q1 and Q3 are the 25th and 75th percentiles, and IQR = Q3 − Q1;
               flag values below Q1 − 1.5 × IQR or above Q3 + 1.5 × IQR

The IQR rule is the one box plots use to draw outliers as dots. Here are 200 ordinary payments of about 50, plus four unusual ones:

Try it yourselfPython
import numpy as np

rng = np.random.RandomState(0)
amounts = rng.normal(50, 10, 200).round(2)                    # 200 ordinary payments, around 50 each
amounts = np.append(amounts, [130.0, 150.0, 400.0, 2000.0])   # 4 unusual ones

# z-score: how many standard deviations a value is from the mean
mean, std = amounts.mean(), amounts.std()
z = (amounts - mean) / std
print(f"mean {mean:.1f}, standard deviation {std:.1f}")
print("z-score rule (|z| > 3) flags:", amounts[np.abs(z) > 3])

# IQR rule: outside the fences 1.5 IQR beyond the quartiles
q1, q3 = np.percentile(amounts, [25, 75])
iqr = q3 - q1
low, high = q1 - 1.5 * iqr, q3 + 1.5 * iqr
print(f"Q1 {q1:.1f}, Q3 {q3:.1f}, IQR {iqr:.1f}, fences {low:.1f} to {high:.1f}")
print("IQR rule flags:", amounts[(amounts < low) | (amounts > high)])
Output
mean 62.9, standard deviation 138.8
z-score rule (|z| > 3) flags: [2000.]
Q1 43.1, Q3 58.6, IQR 15.5, fences 19.8 to 81.8
IQR rule flags: [ 130.  150.  400. 2000.]

The z-score rule finds only the 2,000. That one huge payment drags the mean up to 62.9 and inflates the standard deviation to 138.8, so the payments of 130, 150 and even 400 get z-scores below 3. This is called masking: big outliers hide smaller ones. The IQR rule uses quartiles, which a few extreme values barely move, so it flags all four and nothing else. Prefer the robust rule whenever outliers may be present, which is exactly when you are looking for them.

Many features: IsolationForest

One-column rules miss anomalies that are only strange in combination. The next program simulates 500 normal minutes of a web server, where CPU use rises with traffic, and 12 odd minutes: a busy CPU with little traffic (perhaps a runaway process) or an idle CPU under heavy traffic (perhaps a stuck queue). Each value is ordinary on its own.

Each tree picks a random feature and a random split value, again and again, until every point is alone. A point in the middle of the crowd needs many splits; a point out on its own is isolated after a few. Averaged over 100 random trees, a short path means a high anomaly score. IsolationForest needs no scaling, because each split looks at one feature at a time, and it is fast on large data.

Try it yourselfPython
import numpy as np
from sklearn.ensemble import IsolationForest

rng = np.random.RandomState(0)
requests = rng.uniform(100, 1000, 500)                      # 500 normal minutes of a web server
cpu = 5 + 0.08 * requests + rng.normal(0, 4, 500)           # CPU use (%) rises with traffic
odd_requests = np.r_[rng.uniform(100, 350, 6), rng.uniform(700, 1000, 6)]
odd_cpu = np.r_[rng.uniform(60, 80, 6), rng.uniform(5, 20, 6)]   # busy CPU, little traffic, or the reverse
X = np.column_stack([np.r_[requests, odd_requests], np.r_[cpu, odd_cpu]])
is_odd = np.arange(len(X)) >= 500                           # the 12 odd minutes, used only to check

# One column at a time, nothing looks extreme
z = np.abs((X - X.mean(axis=0)) / X.std(axis=0))
print("minutes with a z-score above 3 in either column:", (z > 3).any(axis=1).sum())

forest = IsolationForest(n_estimators=100, random_state=0).fit(X)
score = -forest.score_samples(X)               # score_samples is lower for stranger points
top12 = np.argsort(-score)[:12]
print("odd minutes among the 12 highest scores:", is_odd[top12].sum())
flag = forest.predict(X) == -1                 # predict: -1 = anomaly, 1 = normal
print(f"predict flags {flag.sum()} of {len(X)} minutes")
Output
minutes with a z-score above 3 in either column: 0
odd minutes among the 12 highest scores: 11
predict flags 108 of 512 minutes

No single column looks extreme: not one minute has a z-score above 3. IsolationForest puts 11 of the 12 odd minutes among its 12 highest scores. But predict, which turns the scores into −1 for anomaly and 1 for normal, flags 108 minutes, a fifth of the data. That is the contamination setting at work, which you'll meet below.

LocalOutlierFactor: strange for the neighbourhood

Some data has crowds of different density. A point that would be ordinary in a loose crowd can be very strange next to a tight one.

Try it yourselfPython
import numpy as np
from sklearn.neighbors import LocalOutlierFactor, NearestNeighbors

rng = np.random.RandomState(0)
dense = rng.normal(0, 0.3, size=(200, 2))        # a tight crowd around (0, 0)
sparse = rng.normal(10, 3, size=(200, 2))        # a loose crowd around (10, 10)
X = np.vstack([dense, sparse, [[1.5, 1.5]]])     # plus one point just outside the tight crowd

lof = LocalOutlierFactor(n_neighbors=20)
labels = lof.fit_predict(X)                      # -1 = anomaly, 1 = normal
lof_score = -lof.negative_outlier_factor_        # the LOF itself: about 1 means normal
far = NearestNeighbors(n_neighbors=21).fit(X).kneighbors(X)[0][:, -1]   # distance to 20th neighbour

def rank(score):                                 # 1 = the most unusual point
    return (score > score[-1]).sum() + 1

print(f"LOF of the odd point: {lof_score[-1]:.1f} (typical point: {np.median(lof_score):.2f})")
print("rank of the odd point among", len(X), "points")
print("  by distance to its 20th neighbour:", rank(far))
print("  by LOF:                           ", rank(lof_score))
print("flagged by fit_predict:", (labels == -1).sum(), "points, odd point included:", labels[-1] == -1)
Output
LOF of the odd point: 5.3 (typical point: 1.06)
rank of the odd point among 401 points
  by distance to its 20th neighbour: 116
  by LOF:                            1
flagged by fit_predict: 21 points, odd point included: True

The odd point sits about 2 units from the centre of the tight crowd, whose points almost all lie within 1 unit of it. Judged by a global yardstick, the distance to its 20th neighbour, it ranks only 116th, because ordinary points in the loose crowd have neighbours that far away too. LOF compares it with its own neighbours instead, gives it 5.3 against a typical 1.06, and ranks it first.

LocalOutlierFactor scores the data it was fitted on, through fit_predict and negative_outlier_factor_ (the LOF with a minus sign). To score new data later, create it with novelty=True, fit it on normal data, then call predict or score_samples. Because it measures distances, scale the features first.

OneClassSVM, briefly

OneClassSVM, from the support vector machine family, learns a smooth boundary around the normal data and calls points outside it anomalies. Its setting nu is roughly the share of training points allowed to fall outside. It needs scaled features, is sensitive to its settings, and slows down a lot beyond tens of thousands of rows, so IsolationForest is usually the first detector to try.

The contamination parameter

Try it yourselfPython
import numpy as np
from sklearn.ensemble import IsolationForest

rng = np.random.RandomState(0)
requests = rng.uniform(100, 1000, 500)
cpu = 5 + 0.08 * requests + rng.normal(0, 4, 500)
odd_requests = np.r_[rng.uniform(100, 350, 6), rng.uniform(700, 1000, 6)]
odd_cpu = np.r_[rng.uniform(60, 80, 6), rng.uniform(5, 20, 6)]
X = np.column_stack([np.r_[requests, odd_requests], np.r_[cpu, odd_cpu]])
is_odd = np.arange(len(X)) >= 500

base = IsolationForest(random_state=0).fit(X).score_samples(X)
for contamination in [0.01, 0.02, 0.1, "auto"]:
    forest = IsolationForest(contamination=contamination, random_state=0).fit(X)
    flag = forest.predict(X) == -1
    same = np.array_equal(forest.score_samples(X), base)
    print(f"contamination {contamination!s:<5}: {flag.sum():3d} flagged, "
          f"{(flag & is_odd).sum():2d} of the 12 odd minutes, same scores: {same}")
Output
contamination 0.01 :   6 flagged,  6 of the 12 odd minutes, same scores: True
contamination 0.02 :  11 flagged, 10 of the 12 odd minutes, same scores: True
contamination 0.1  :  52 flagged, 12 of the 12 odd minutes, same scores: True
contamination auto : 108 flagged, 12 of the 12 odd minutes, same scores: True

The scores never change; only the cut-off moves. With contamination=0.01 the forest flags 6 minutes, all of them odd. At 0.1 it flags 52 and catches all 12, along with 40 false alarms. The default, "auto", uses a cut-off from the original IsolationForest paper and flags 108 here. Two consequences:

  • Contamination is your assumption, not a discovery. Set it to 0.05 and the model flags 5% of the training data, whether it contains anomalies or not.
  • In practice, set the cut-off from capacity: if the team can check 20 alerts a day, send it the 20 highest scores.

OneClassSVM's nu is different: it changes the boundary itself, and with it the scores, as the next section shows.

Evaluating with few labels: precision at k

How good is a detector? Without labels you can't measure its recall over the whole dataset. But you can afford to check its top alerts, and those are what the team will read.

The program scores the server minutes with every detector in this lesson and computes precision at 5, 10 and 20. Here we know the 12 odd minutes because we made them; in real work, the labels come from experts who review the top of each list.

Try it yourselfPython
import numpy as np
from sklearn.ensemble import IsolationForest
from sklearn.neighbors import LocalOutlierFactor
from sklearn.preprocessing import StandardScaler
from sklearn.svm import OneClassSVM

rng = np.random.RandomState(0)
requests = rng.uniform(100, 1000, 500)
cpu = 5 + 0.08 * requests + rng.normal(0, 4, 500)
odd_requests = np.r_[rng.uniform(100, 350, 6), rng.uniform(700, 1000, 6)]
odd_cpu = np.r_[rng.uniform(60, 80, 6), rng.uniform(5, 20, 6)]
X = np.column_stack([np.r_[requests, odd_requests], np.r_[cpu, odd_cpu]])
is_odd = np.arange(len(X)) >= 500
X_scaled = StandardScaler().fit_transform(X)     # distance-based detectors need scaled features

scores = {                                       # for every detector, higher = more unusual
    "z-score (larger of the two)": np.abs(X_scaled).max(axis=1),
    "IsolationForest": -IsolationForest(random_state=0).fit(X).score_samples(X),
    "LocalOutlierFactor": -LocalOutlierFactor(n_neighbors=20).fit(X_scaled).negative_outlier_factor_,
    "OneClassSVM, nu=0.02": -OneClassSVM(nu=0.02).fit(X_scaled).score_samples(X_scaled),
    "OneClassSVM, nu=0.1": -OneClassSVM(nu=0.1).fit(X_scaled).score_samples(X_scaled),
}

def precision_at_k(score, k):
    top = np.argsort(-score)[:k]                 # the k highest scores
    return is_odd[top].mean()                    # the share of them that are real problems

print(f"{'':<29}{'P@5':>6}{'P@10':>6}{'P@20':>6}")
for name, score in scores.items():
    print(f"{name:<29}" + "".join(f"{precision_at_k(score, k):6.2f}" for k in [5, 10, 20]))
Output
                                P@5  P@10  P@20
z-score (larger of the two)    0.00  0.10  0.10
IsolationForest                1.00  0.90  0.60
LocalOutlierFactor             1.00  1.00  0.60
OneClassSVM, nu=0.02           0.40  0.30  0.30
OneClassSVM, nu=0.1            1.00  1.00  0.60
  • The z-score baseline, using the larger of the two columns' z-scores, finds almost nothing: these anomalies hide in the combination.
  • IsolationForest and LocalOutlierFactor put real problems at the top: 9 and 10 of their top 10. With only 12 odd minutes, 0.60 is the best possible precision at 20, so both have found all 12 by then.
  • OneClassSVM depends heavily on nu. With nu=0.02 its boundary stretches around many of the odd minutes, which were part of its training data; with nu=0.1 it matches the best.

To estimate what a detector misses, also label a small random sample of the points it didn't flag. Keep the reviews going: every checked alert is a new label, and once you have enough, a supervised model trained on them (Handling Imbalanced Classes) usually beats any detector on the kinds of problems you have seen, while the detector keeps watch for new kinds.

Common mistakes

Practice

Practice exercise

Your fraud team checked 10 payments and labelled them. Finish precision_at_k() to find which detector puts real fraud at the top of its list.

Your solutionPython
# Anomaly scores from two detectors for the same 10 payments (higher = stranger),
# and what the analysts found when they checked each payment (1 = real fraud)
scores_a = [0.91, 0.15, 0.62, 0.08, 0.77, 0.33, 0.95, 0.41, 0.58, 0.12]
scores_b = [0.40, 0.85, 0.30, 0.10, 0.90, 0.20, 0.70, 0.95, 0.60, 0.05]
fraud = [1, 0, 0, 0, 1, 0, 1, 0, 1, 0]

def precision_at_k(scores, labels, k):
    # Take the k payments with the highest scores and return the share that are fraud
    return 0

for name, scores in [("detector A", scores_a), ("detector B", scores_b)]:
    print(f"{name}: precision at 3 = {precision_at_k(scores, fraud, 3):.2f}, "
          f"at 5 = {precision_at_k(scores, fraud, 5):.2f}")
Knowledge check

You fit IsolationForest(contamination=0.05) to 1,000 payments, and it flags 50 of them. What does that tell you?

Summary

  • An anomaly is a point that doesn't fit the rest. Detectors give scores that rank points for review, not verdicts.
  • For one column, the IQR rule is safer than the z-score rule, which big outliers can mask.
  • IsolationForest isolates odd points with few random splits and needs no scaling; LocalOutlierFactor compares each point's density with its neighbours'; OneClassSVM draws a boundary and is sensitive to its settings.
  • contamination only moves the cut-off: choose it from your team's capacity to review alerts.
  • With few labels, compare detectors by precision at k on the alerts people actually check.

Next: Association Rules.

Finished reading? Tick it off to track your progress.