Gradient LabOpen in Gradient Lab

Lessons › Projects

Spot fraud with anomaly detection

A detector that learns what normal card payments look like and flags the strange ones, without ever seeing a fraud label.

No setup needed. Run every step in your browser on Gradient Lab, or download it.

Open the notebook

Level: Intermediate · Time: 25 min · You’ll practise: Isolation Forest, unsupervised scoring, checking against hidden labels

Steps

1. 1,000 normal payments + 15 odd ones

Generate 1,000 normal payments and plant 15 strange ones (huge amounts, at night, far from home).

rng = np.random.default_rng(11)
normal = pd.DataFrame({
    "amount": rng.lognormal(6.5, 0.6, 1000).round(),          # usually a few hundred to a few thousand
    "hour": rng.normal(15, 3.5, 1000).clip(6, 23).round(),     # daytime
    "km_from_home": rng.exponential(4, 1000).round(1),         # close to home
})
fraud = pd.DataFrame({
    "amount": rng.uniform(15000, 60000, 15).round(),
    "hour": rng.integers(1, 5, 15),
    "km_from_home": rng.uniform(300, 5000, 15).round(1),
})
data = pd.concat([normal.assign(is_fraud=0), fraud.assign(is_fraud=1)], ignore_index=True).sample(frac=1, random_state=0)
print(data.describe().round(1))

2. Learn what "normal" looks like - no fraud labels are used!

Train an Isolation Forest on the features only. No fraud labels are used.

features = ["amount", "hour", "km_from_home"]
detector = IsolationForest(contamination=0.02, random_state=0).fit(data[features])

3. Score every payment (lower = stranger) and flag the oddest

Score every payment and flag the strangest 2%.

data["score"] = detector.score_samples(data[features])
data["flagged"] = detector.predict(data[features]) == -1
print(f"\nFlagged {data.flagged.sum()} of {len(data)} payments")

4. Now peek at the hidden labels to see how we did

Peek at the hidden labels to see how many planted frauds were caught and how many false alarms there were.

caught = int((data.flagged & (data.is_fraud == 1)).sum())
false_alarms = int((data.flagged & (data.is_fraud == 0)).sum())
print(f"Caught {caught} of 15 planted frauds, with {false_alarms} false alarms")
print("\nThe 5 strangest payments:")
print(data.nsmallest(5, "score")[features + ["is_fraud"]].to_string(index=False))

Expected output

$ python fraud_detector.py
        amount    hour  km_from_home  is_fraud
count   1015.0  1015.0        1015.0    1015.0
mean    1366.8    14.8          53.8       0.0
std     4918.8     3.7         425.8       0.1
min      125.0     1.0           0.0       0.0
25%      445.5    13.0           1.1       0.0
50%      699.0    15.0           2.9       0.0
75%     1017.0    17.0           5.9       0.0
max    58384.0    23.0        4722.8       1.0

Flagged 21 of 1015 payments
Caught 15 of 15 planted frauds, with 6 false alarms

The 5 strangest payments:
 amount  hour  km_from_home  is_fraud
57469.0   2.0        4179.5         1
50162.0   4.0        4536.4         1
54909.0   4.0        3002.6         1
58384.0   1.0        1792.5         1
47956.0   2.0        4469.6         1

Stretch goals

Download p10-fraud-detector.zip