Project 6: Credit Card Fraud Detection
A card issuer's fraud team has five analysts. Each day they can review about 10 alerts: call the customer, block the card if it was stolen, refund the money. Today the alerts come from hand-written rules, which flag hundreds of payments a day and miss the fraud that does not look like the rules. This intermediate project replaces the rules with a model and, more importantly, with a decision policy that fits the team's daily capacity. The skills are those of imbalanced learning: a time-based split, metrics that see the rare class, resampling and class weights compared honestly, and a threshold set by costs and an alert budget.
Each technique has its own lesson, and this project only uses them: class imbalance (why accuracy lies, PR-AUC), resampling and SMOTE, class weights, lag and group features and LightGBM. Those lessons work on make_classification points with a fixed threshold. New here: transactions with a history, per-card features computed from the past only, a split by time, and the question the fraud team actually asks: given 10 reviews a day, which 10?
Goal and success criteria
Agreed with the fraud team before any model is trained:
| Criterion | Target | Measured on |
|---|---|---|
| alerts per day | at most 10 (the team's capacity) | the test fortnight |
| frauds caught | at least 0.75 of the fraudulent payments | test, used once |
| fraud money caught | at least 0.80 of the fraudulent amount | test |
| net value | caught fraud amount minus 5 EUR per review, positive and above the rules | test |
| probabilities | usable as probabilities: mean predicted p within a factor of 2 of the fraud share | validation |
The success measure is money and analyst time, not accuracy: at 0.46 % fraud, "never fraud" is 99.5 % accurate.
The data
make_transactions simulates 1,500 cards over 90 days. Each card has a usual amount and a payment rate; a quarter of payments are online; 10 % of cards go on a five-day trip, so far-away payments are not always fraud. Then 120 cards (8 %) are compromised, and each produces a burst of 1 to 6 fraudulent payments within a day, of one of two kinds:
- online fraud (60 %): card details used on a website, often from a new device, for electronics or gaming, at several times the card's usual amount;
- skimmed card (40 %): a copied card used in person, far from home, mostly at night, for fuel, restaurants and electronics.
add_history_features adds what the bank knows at the moment of payment, from the card's earlier payments only: the amount divided by the card's average so far, hours since its previous payment, and the number of its payments in the last 24 hours. Computing them with shift and a sorted search keeps today's payment out of its own history; computing them over the whole table at once would leak the future into the past (lag, rolling and group features).
Real data: the public "Credit Card Fraud Detection" dataset of the Université Libre de Bruxelles on Kaggle (284,807 card payments by European cardholders over two days in September 2013, 492 of them fraud, 0.17 %; 28 of its features are anonymised PCA components, only the time and the amount are raw; the Open Data Commons Database Contents License (DbCL) 1.0, as stated on its Kaggle page). Real transaction data is personal and financial data: access is restricted, its use is limited to fraud prevention, and when a decision with legal or similarly significant effects is fully automated, the GDPR (Article 22) gives customers the right to human intervention and to contest it, plus meaningful information about the logic involved (Articles 13 to 15) (privacy and consent, governance). Every score here describes this generator.
The split is by day: training days 0 to 55, validation 56 to 72, test 73 to 89.
A random split would put payments of the same burst, minutes apart, on both sides, and it would let the model train on the future. In production there is one more delay: fraud labels come from chargebacks, often weeks after the payment, so the last weeks before a training run are under-labelled and should be left out or waited for. The generator's labels are complete, a simplification.
Step 1: explore
import numpy as np
import pandas as pd
CATS = ["grocery", "fuel", "restaurant", "travel", "electronics", "gaming"]
def make_transactions(seed=4, n_cards=1500, days=90):
"""Card payments over 90 days, about 0.5 % fraud: bursts of online fraud and of skimmed-card fraud."""
rng = np.random.default_rng(seed)
typical = rng.lognormal(3.3, 0.5, n_cards) # each card's usual amount, EUR
card = np.repeat(np.arange(n_cards), rng.poisson(rng.uniform(0.2, 1.0, n_cards) * days).astype(int))
m = len(card)
online = rng.random(m) < 0.25
trip = rng.uniform(-200, days, n_cards) # 10 % of cards travel for 5 days
df = pd.DataFrame({"card": card, "day": rng.integers(0, days, m), "hour": np.clip(rng.normal(14, 4, m), 0, 23.9),
"amount": typical[card] * rng.lognormal(0, 0.6, m), "online": online,
"category": rng.choice(CATS, m, p=[0.35, 0.15, 0.25, 0.05, 0.12, 0.08]),
"new_device": online & (rng.random(m) < 0.03), "fraud": 0})
away = ~online & (df["day"] >= trip[card]) & (df["day"] < trip[card] + 5)
df["distance_km"] = np.where(online, rng.lognormal(5, 1, m), np.where(away, rng.lognormal(6, 0.5, m), rng.lognormal(1.5, 1, m)))
rows = []
for c in rng.choice(n_cards, int(0.08 * n_cards), replace=False): # compromised cards
start, skimmed = rng.uniform(0, days - 1), rng.random() < 0.4
for _ in range(rng.integers(1, 7)): # a burst of 1-6 payments within a day
t = start + rng.uniform(0, 1)
rows.append({"card": c, "day": int(t), "hour": (rng.normal(2, 3) % 24) if skimmed else rng.uniform(0, 23.9),
"amount": typical[c] * rng.lognormal(0.7 if skimmed else 1.0, 0.7), "online": not skimmed,
"category": rng.choice(CATS, p=[0.05, 0.3, 0.2, 0.2, 0.25, 0.0] if skimmed else [0.05, 0, 0.05, 0.2, 0.4, 0.3]),
"new_device": (not skimmed) and rng.random() < 0.5, "fraud": 1,
"distance_km": rng.lognormal(6, 0.7) if skimmed else rng.lognormal(5, 1)})
df = pd.concat([df, pd.DataFrame(rows)], ignore_index=True)
df["t"] = df["day"] + df["hour"] / 24 # time in days
return df.sort_values(["card", "t"], ignore_index=True)
def add_history_features(df):
"""Per-card features from the card's EARLIER payments only."""
g = df.groupby("card")
df["amount_ratio"] = (df["amount"] / g["amount"].transform(lambda a: a.shift().expanding().mean())).fillna(1.0)
df["hours_since_prev"] = (g["t"].diff() * 24).fillna(24 * 30)
key = df["card"].to_numpy() * 1000.0 + df["t"].to_numpy() # sorted by card, then time
df["n_last_24h"] = np.arange(len(df)) - np.searchsorted(key, key - 1.0, side="left")
return df
pd.set_option("display.width", 120)
df = add_history_features(make_transactions())
df["split"] = np.where(df["day"] < 56, "train", np.where(df["day"] < 73, "val", "test"))
print(f"{len(df)} payments on {df['card'].nunique()} cards over 90 days, fraud share {df['fraud'].mean():.4f}")
print(df.groupby("split", sort=False)["fraud"].agg(payments="size", frauds="sum", share="mean").round(4))
print("fraud share online / in person:", df.groupby("online")["fraud"].mean().round(4).tolist()[::-1],
"| new device:", round(df.loc[df["new_device"], "fraud"].mean(), 3))
cols = ["amount", "amount_ratio", "distance_km", "hours_since_prev", "n_last_24h"]
print(df.groupby("fraud")[cols].median().round(1))
bursts = df[df["fraud"] == 1].groupby("card").size()
print("compromised cards:", len(bursts), "| frauds per card:", bursts.value_counts().sort_index().to_dict())81850 payments on 1500 cards over 90 days, fraud share 0.0048
payments frauds share
split
train 50984 248 0.0049
val 15357 71 0.0046
test 15509 71 0.0046
fraud share online / in person: [0.0119, 0.0024] | new device: 0.171
amount amount_ratio distance_km hours_since_prev n_last_24h
fraud
0 27.3 0.9 7.1 24.7 0.0
1 66.5 1.9 215.8 7.4 2.0
compromised cards: 120 | frauds per card: {1: 21, 2: 31, 3: 17, 4: 19, 5: 12, 6: 20}
The three periods have nearly the same fraud share (0.46 % to 0.49 %), with 71 frauds each in validation and test: small numbers, which will matter when comparing models. Online payments are five times as risky as in-person ones (1.19 % against 0.24 %), and 17.1 % of new-device payments are fraud. The medians show the signals: frauds are larger relative to the card's habit (ratio 1.9 against 0.9), much further away (216 km against 7 km), and come in quick succession (7.4 hours since the previous payment, 2 payments in the last 24 hours).
Step 2: baselines on validation
Three candidates against the "never fraud" baseline: the current rules, a logistic regression and LightGBM, both on the same raw features. Each is measured three ways on validation: PR-AUC, ROC-AUC, and the operational number, recall and precision when the 10 highest scores of each day become alerts.
import numpy as np
import pandas as pd
CATS = ["grocery", "fuel", "restaurant", "travel", "electronics", "gaming"]
def make_transactions(seed=4, n_cards=1500, days=90):
"""Card payments over 90 days, about 0.5 % fraud: bursts of online fraud and of skimmed-card fraud."""
rng = np.random.default_rng(seed)
typical = rng.lognormal(3.3, 0.5, n_cards) # each card's usual amount, EUR
card = np.repeat(np.arange(n_cards), rng.poisson(rng.uniform(0.2, 1.0, n_cards) * days).astype(int))
m = len(card)
online = rng.random(m) < 0.25
trip = rng.uniform(-200, days, n_cards) # 10 % of cards travel for 5 days
df = pd.DataFrame({"card": card, "day": rng.integers(0, days, m), "hour": np.clip(rng.normal(14, 4, m), 0, 23.9),
"amount": typical[card] * rng.lognormal(0, 0.6, m), "online": online,
"category": rng.choice(CATS, m, p=[0.35, 0.15, 0.25, 0.05, 0.12, 0.08]),
"new_device": online & (rng.random(m) < 0.03), "fraud": 0})
away = ~online & (df["day"] >= trip[card]) & (df["day"] < trip[card] + 5)
df["distance_km"] = np.where(online, rng.lognormal(5, 1, m), np.where(away, rng.lognormal(6, 0.5, m), rng.lognormal(1.5, 1, m)))
rows = []
for c in rng.choice(n_cards, int(0.08 * n_cards), replace=False): # compromised cards
start, skimmed = rng.uniform(0, days - 1), rng.random() < 0.4
for _ in range(rng.integers(1, 7)): # a burst of 1-6 payments within a day
t = start + rng.uniform(0, 1)
rows.append({"card": c, "day": int(t), "hour": (rng.normal(2, 3) % 24) if skimmed else rng.uniform(0, 23.9),
"amount": typical[c] * rng.lognormal(0.7 if skimmed else 1.0, 0.7), "online": not skimmed,
"category": rng.choice(CATS, p=[0.05, 0.3, 0.2, 0.2, 0.25, 0.0] if skimmed else [0.05, 0, 0.05, 0.2, 0.4, 0.3]),
"new_device": (not skimmed) and rng.random() < 0.5, "fraud": 1,
"distance_km": rng.lognormal(6, 0.7) if skimmed else rng.lognormal(5, 1)})
df = pd.concat([df, pd.DataFrame(rows)], ignore_index=True)
df["t"] = df["day"] + df["hour"] / 24 # time in days
return df.sort_values(["card", "t"], ignore_index=True)
def add_history_features(df):
"""Per-card features from the card's EARLIER payments only."""
g = df.groupby("card")
df["amount_ratio"] = (df["amount"] / g["amount"].transform(lambda a: a.shift().expanding().mean())).fillna(1.0)
df["hours_since_prev"] = (g["t"].diff() * 24).fillna(24 * 30)
key = df["card"].to_numpy() * 1000.0 + df["t"].to_numpy() # sorted by card, then time
df["n_last_24h"] = np.arange(len(df)) - np.searchsorted(key, key - 1.0, side="left")
return df
import lightgbm as lgb
from sklearn.metrics import average_precision_score, roc_auc_score
df = add_history_features(make_transactions())
X = pd.get_dummies(df[["amount", "amount_ratio", "hours_since_prev", "n_last_24h", "online", "new_device",
"distance_km", "hour", "category"]], columns=["category"], dtype=float).astype(float)
y = df["fraud"].to_numpy()
train, val = (df["day"] < 56).to_numpy(), ((df["day"] >= 56) & (df["day"] < 73)).to_numpy()
BUDGET = 10 # alerts the team can review per day
def at_budget(score, mask):
"""Recall and precision when the BUDGET highest scores of each day become alerts."""
d = df.loc[mask, ["day"]].assign(s=score, y=y[mask])
top = d.sort_values("s", ascending=False, kind="stable").groupby("day").head(BUDGET)
return top["y"].sum() / d["y"].sum(), top["y"].mean()
def gbm(**kw):
return lgb.LGBMClassifier(**{"n_estimators": 200, "learning_rate": 0.08, "num_leaves": 15, "verbose": -1, "random_state": 0, **kw})
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
print(f"validation: {val.sum()} payments, {y[val].sum()} frauds; always 'legit' is {1 - y[val].mean():.4f} accurate")
rule = ((df["amount_ratio"] > 3) | df["new_device"] | (df["distance_km"] > 500)).to_numpy()[val]
print(f"rule (ratio > 3 or new device or > 500 km): {rule.sum()} alerts, recall {rule[y[val] == 1].mean():.3f}, "
f"precision {y[val][rule].mean():.3f}")
for name, model in [("logistic regression", make_pipeline(StandardScaler(), LogisticRegression(max_iter=2000))),
("LightGBM", gbm())]:
p = model.fit(X[train], y[train]).predict_proba(X[val])[:, 1]
r, prec = at_budget(p, val)
print(f"{name:19s} PR-AUC {average_precision_score(y[val], p):.3f} ROC-AUC {roc_auc_score(y[val], p):.3f} "
f"top {BUDGET}/day: recall {r:.3f}, precision {prec:.3f}")validation: 15357 payments, 71 frauds; always 'legit' is 0.9954 accurate
rule (ratio > 3 or new device or > 500 km): 905 alerts, recall 0.620, precision 0.049
logistic regression PR-AUC 0.469 ROC-AUC 0.956 top 10/day: recall 0.577, precision 0.241
LightGBM PR-AUC 0.702 ROC-AUC 0.990 top 10/day: recall 0.817, precision 0.341
The rules flag 905 payments in 17 days (53 a day, five times the capacity) at precision 0.049. LightGBM is the strongest model: PR-AUC 0.702 (the chance level of PR-AUC is the fraud share, 0.0046), and its 10 daily alerts find 0.817 of the frauds with a third of the alerts being real fraud. ROC-AUC barely separates the two models (0.956 and 0.990) because it is dominated by the 15,000 easy negatives; PR-AUC and the budget metric show the difference (why PR curves for rare positives). The logistic regression's gap is partly unfair: it gets raw amounts and hours, while trees cope with skew and with "night" being both 23:00 and 02:00 without help (see Practice 1).
Step 3: does rebalancing help?
The lab shows what rebalancing does to a classifier with a fixed threshold of 0.5. With 10 minority points, no rebalancing finds 20 of the 50 minority test points (recall 0.400) at precision 0.833; class weights find 42 (recall 0.840) at precision 0.372, and SMOTE 40 at precision 0.426. Rebalancing moves the boundary, buying recall with precision, which a lower threshold also does.
When the decision is "the top 10 of the day", the threshold is set by the budget anyway, so a remedy only helps if it ranks better. Four LightGBM variants on the same training days, with resampling inside the pipeline so it touches training rows only:
import numpy as np
import pandas as pd
CATS = ["grocery", "fuel", "restaurant", "travel", "electronics", "gaming"]
def make_transactions(seed=4, n_cards=1500, days=90):
"""Card payments over 90 days, about 0.5 % fraud: bursts of online fraud and of skimmed-card fraud."""
rng = np.random.default_rng(seed)
typical = rng.lognormal(3.3, 0.5, n_cards) # each card's usual amount, EUR
card = np.repeat(np.arange(n_cards), rng.poisson(rng.uniform(0.2, 1.0, n_cards) * days).astype(int))
m = len(card)
online = rng.random(m) < 0.25
trip = rng.uniform(-200, days, n_cards) # 10 % of cards travel for 5 days
df = pd.DataFrame({"card": card, "day": rng.integers(0, days, m), "hour": np.clip(rng.normal(14, 4, m), 0, 23.9),
"amount": typical[card] * rng.lognormal(0, 0.6, m), "online": online,
"category": rng.choice(CATS, m, p=[0.35, 0.15, 0.25, 0.05, 0.12, 0.08]),
"new_device": online & (rng.random(m) < 0.03), "fraud": 0})
away = ~online & (df["day"] >= trip[card]) & (df["day"] < trip[card] + 5)
df["distance_km"] = np.where(online, rng.lognormal(5, 1, m), np.where(away, rng.lognormal(6, 0.5, m), rng.lognormal(1.5, 1, m)))
rows = []
for c in rng.choice(n_cards, int(0.08 * n_cards), replace=False): # compromised cards
start, skimmed = rng.uniform(0, days - 1), rng.random() < 0.4
for _ in range(rng.integers(1, 7)): # a burst of 1-6 payments within a day
t = start + rng.uniform(0, 1)
rows.append({"card": c, "day": int(t), "hour": (rng.normal(2, 3) % 24) if skimmed else rng.uniform(0, 23.9),
"amount": typical[c] * rng.lognormal(0.7 if skimmed else 1.0, 0.7), "online": not skimmed,
"category": rng.choice(CATS, p=[0.05, 0.3, 0.2, 0.2, 0.25, 0.0] if skimmed else [0.05, 0, 0.05, 0.2, 0.4, 0.3]),
"new_device": (not skimmed) and rng.random() < 0.5, "fraud": 1,
"distance_km": rng.lognormal(6, 0.7) if skimmed else rng.lognormal(5, 1)})
df = pd.concat([df, pd.DataFrame(rows)], ignore_index=True)
df["t"] = df["day"] + df["hour"] / 24 # time in days
return df.sort_values(["card", "t"], ignore_index=True)
def add_history_features(df):
"""Per-card features from the card's EARLIER payments only."""
g = df.groupby("card")
df["amount_ratio"] = (df["amount"] / g["amount"].transform(lambda a: a.shift().expanding().mean())).fillna(1.0)
df["hours_since_prev"] = (g["t"].diff() * 24).fillna(24 * 30)
key = df["card"].to_numpy() * 1000.0 + df["t"].to_numpy() # sorted by card, then time
df["n_last_24h"] = np.arange(len(df)) - np.searchsorted(key, key - 1.0, side="left")
return df
import lightgbm as lgb
from sklearn.metrics import average_precision_score, roc_auc_score
df = add_history_features(make_transactions())
X = pd.get_dummies(df[["amount", "amount_ratio", "hours_since_prev", "n_last_24h", "online", "new_device",
"distance_km", "hour", "category"]], columns=["category"], dtype=float).astype(float)
y = df["fraud"].to_numpy()
train, val = (df["day"] < 56).to_numpy(), ((df["day"] >= 56) & (df["day"] < 73)).to_numpy()
BUDGET = 10 # alerts the team can review per day
def at_budget(score, mask):
"""Recall and precision when the BUDGET highest scores of each day become alerts."""
d = df.loc[mask, ["day"]].assign(s=score, y=y[mask])
top = d.sort_values("s", ascending=False, kind="stable").groupby("day").head(BUDGET)
return top["y"].sum() / d["y"].sum(), top["y"].mean()
def gbm(**kw):
return lgb.LGBMClassifier(**{"n_estimators": 200, "learning_rate": 0.08, "num_leaves": 15, "verbose": -1, "random_state": 0, **kw})
from imblearn.over_sampling import SMOTE
from imblearn.under_sampling import RandomUnderSampler
from imblearn.pipeline import make_pipeline
ratio = (y[train] == 0).sum() / y[train].sum()
variants = {"none": gbm(), f"class weight x{ratio:.0f}": gbm(scale_pos_weight=ratio),
f"class weight x{ratio:.0f}, lr 0.02": gbm(scale_pos_weight=ratio, learning_rate=0.02),
"SMOTE to 1:1": make_pipeline(SMOTE(random_state=0), gbm()),
"undersample to 1:10": make_pipeline(RandomUnderSampler(sampling_strategy=0.1, random_state=0), gbm())}
print(f"validation fraud share {y[val].mean():.4f}")
hits = {}
for name, model in variants.items():
p = model.fit(X[train], y[train]).predict_proba(X[val])[:, 1] # resampling happens inside fit, on train only
r, prec = at_budget(p, val)
d = df.loc[val, ["day"]].assign(s=p, y=y[val])
hits[name] = d.sort_values("s", ascending=False, kind="stable").groupby("day").head(BUDGET).groupby("day")["y"].sum()
print(f"{name:26s} PR-AUC {average_precision_score(y[val], p):.3f} top {BUDGET}/day recall {r:.3f} "
f"mean predicted p {p.mean():.4f}")
# is any difference real? resample the 17 validation days (bootstrap) and compare frauds caught with "none"
rng = np.random.default_rng(0)
days = hits["none"].index.to_numpy()
boot = [rng.choice(days, len(days)) for _ in range(1000)]
for name in list(variants)[1:]:
diff = np.array([hits[name][b].sum() - hits["none"][b].sum() for b in boot])
print(f"{name:26s} vs none: {int(hits[name].sum() - hits['none'].sum()):+d} frauds caught, "
f"90 % bootstrap interval {np.percentile(diff, 5):+.0f} to {np.percentile(diff, 95):+.0f}")validation fraud share 0.0046
none PR-AUC 0.702 top 10/day recall 0.817 mean predicted p 0.0038
class weight x205 PR-AUC 0.107 top 10/day recall 0.197 mean predicted p 0.0313
class weight x205, lr 0.02 PR-AUC 0.748 top 10/day recall 0.845 mean predicted p 0.0234
SMOTE to 1:1 PR-AUC 0.757 top 10/day recall 0.817 mean predicted p 0.0066
undersample to 1:10 PR-AUC 0.737 top 10/day recall 0.831 mean predicted p 0.0149
class weight x205 vs none: -44 frauds caught, 90 % bootstrap interval -62 to -27
class weight x205, lr 0.02 vs none: +2 frauds caught, 90 % bootstrap interval -2 to +6
SMOTE to 1:1 vs none: +0 frauds caught, 90 % bootstrap interval -3 to +3
undersample to 1:10 vs none: +1 frauds caught, 90 % bootstrap interval -2 to +4
Three lessons in one table. First, class weights of 205 (the ratio of legitimate to fraudulent training payments) at the same learning rate wreck the model (PR-AUC 0.107, 44 fewer frauds caught): every fraud now counts 205 times in the gradient, the first trees fit the few frauds with huge leaf values, and boosting overfits. The run is also numerically unstable: the same code gave 0.072 in CPython on a laptop, a warning sign in itself. At learning rate 0.02 the same weights work (0.748). A weight is not a free switch; it changes the effective step size, so retune after setting it. Second, the working variants differ by at most 2 frauds out of 71 at the budget, and the bootstrap over validation days puts every difference inside an interval that contains zero (the bootstrap resamples whole days, not single payments, because the payments of a burst fall on the same day; external validation makes the same point about small evaluation sets). PR-AUC differences of 0.05 on 71 positives are not evidence. Third, the probabilities: without rebalancing the mean predicted probability is 0.0038 against a real share of 0.0046; with the working class weights it is 0.0234, 5 times too high, with undersampling 3 times and with SMOTE 1.4 times. A rebalanced model's scores are not probabilities until they are recalibrated (calibration).
Decision: no rebalancing. It ranks as well as any variant here, it is the simplest, and its probabilities can be used in a cost rule.
Step 4: the decision policy, and the test fortnight
With a calibrated probability that a payment of amount is fraud, and a cost per review, reviewing pays off on average when the expected loss it can prevent exceeds the review cost:
That gives a third policy next to "top 10 by " and "top 10 by ": alert whenever with EUR, with no daily cap. The policies are compared on validation by the net value
the fraud money stopped minus the cost of the reviews (a simplification: blocking a card early also stops the rest of the burst, and false alerts annoy customers). The best policy on validation is then applied once to the test fortnight.
import numpy as np
import pandas as pd
CATS = ["grocery", "fuel", "restaurant", "travel", "electronics", "gaming"]
def make_transactions(seed=4, n_cards=1500, days=90):
"""Card payments over 90 days, about 0.5 % fraud: bursts of online fraud and of skimmed-card fraud."""
rng = np.random.default_rng(seed)
typical = rng.lognormal(3.3, 0.5, n_cards) # each card's usual amount, EUR
card = np.repeat(np.arange(n_cards), rng.poisson(rng.uniform(0.2, 1.0, n_cards) * days).astype(int))
m = len(card)
online = rng.random(m) < 0.25
trip = rng.uniform(-200, days, n_cards) # 10 % of cards travel for 5 days
df = pd.DataFrame({"card": card, "day": rng.integers(0, days, m), "hour": np.clip(rng.normal(14, 4, m), 0, 23.9),
"amount": typical[card] * rng.lognormal(0, 0.6, m), "online": online,
"category": rng.choice(CATS, m, p=[0.35, 0.15, 0.25, 0.05, 0.12, 0.08]),
"new_device": online & (rng.random(m) < 0.03), "fraud": 0})
away = ~online & (df["day"] >= trip[card]) & (df["day"] < trip[card] + 5)
df["distance_km"] = np.where(online, rng.lognormal(5, 1, m), np.where(away, rng.lognormal(6, 0.5, m), rng.lognormal(1.5, 1, m)))
rows = []
for c in rng.choice(n_cards, int(0.08 * n_cards), replace=False): # compromised cards
start, skimmed = rng.uniform(0, days - 1), rng.random() < 0.4
for _ in range(rng.integers(1, 7)): # a burst of 1-6 payments within a day
t = start + rng.uniform(0, 1)
rows.append({"card": c, "day": int(t), "hour": (rng.normal(2, 3) % 24) if skimmed else rng.uniform(0, 23.9),
"amount": typical[c] * rng.lognormal(0.7 if skimmed else 1.0, 0.7), "online": not skimmed,
"category": rng.choice(CATS, p=[0.05, 0.3, 0.2, 0.2, 0.25, 0.0] if skimmed else [0.05, 0, 0.05, 0.2, 0.4, 0.3]),
"new_device": (not skimmed) and rng.random() < 0.5, "fraud": 1,
"distance_km": rng.lognormal(6, 0.7) if skimmed else rng.lognormal(5, 1)})
df = pd.concat([df, pd.DataFrame(rows)], ignore_index=True)
df["t"] = df["day"] + df["hour"] / 24 # time in days
return df.sort_values(["card", "t"], ignore_index=True)
def add_history_features(df):
"""Per-card features from the card's EARLIER payments only."""
g = df.groupby("card")
df["amount_ratio"] = (df["amount"] / g["amount"].transform(lambda a: a.shift().expanding().mean())).fillna(1.0)
df["hours_since_prev"] = (g["t"].diff() * 24).fillna(24 * 30)
key = df["card"].to_numpy() * 1000.0 + df["t"].to_numpy() # sorted by card, then time
df["n_last_24h"] = np.arange(len(df)) - np.searchsorted(key, key - 1.0, side="left")
return df
import lightgbm as lgb
from sklearn.metrics import average_precision_score, roc_auc_score
df = add_history_features(make_transactions())
X = pd.get_dummies(df[["amount", "amount_ratio", "hours_since_prev", "n_last_24h", "online", "new_device",
"distance_km", "hour", "category"]], columns=["category"], dtype=float).astype(float)
y = df["fraud"].to_numpy()
train, val = (df["day"] < 56).to_numpy(), ((df["day"] >= 56) & (df["day"] < 73)).to_numpy()
BUDGET = 10 # alerts the team can review per day
def at_budget(score, mask):
"""Recall and precision when the BUDGET highest scores of each day become alerts."""
d = df.loc[mask, ["day"]].assign(s=score, y=y[mask])
top = d.sort_values("s", ascending=False, kind="stable").groupby("day").head(BUDGET)
return top["y"].sum() / d["y"].sum(), top["y"].mean()
def gbm(**kw):
return lgb.LGBMClassifier(**{"n_estimators": 200, "learning_rate": 0.08, "num_leaves": 15, "verbose": -1, "random_state": 0, **kw})
REVIEW_COST = 5.0 # EUR per alert an analyst reviews
test = (df["day"] >= 73).to_numpy()
model = gbm().fit(X[train], y[train]) # frozen: the validated "none" model
def run_policy(policy, mask):
d = df.loc[mask, ["day", "card", "hour", "amount", "category", "distance_km", "fraud"]].copy()
d["p"] = model.predict_proba(X[mask])[:, 1]
d["expected_loss"] = d["p"] * d["amount"]
if policy == "top 10/day by p":
alerts = d.sort_values("p", ascending=False, kind="stable").groupby("day").head(BUDGET)
elif policy == "top 10/day by p x amount":
alerts = d.sort_values("expected_loss", ascending=False, kind="stable").groupby("day").head(BUDGET)
else: # no cap: alert when the expected loss pays for a review
alerts = d[d["expected_loss"] > REVIEW_COST]
caught = alerts["amount"][alerts["fraud"] == 1].sum()
total = d["amount"][d["fraud"] == 1].sum()
return d, alerts, {"alerts/day": len(alerts) / d["day"].nunique(), "frauds caught": int(alerts["fraud"].sum()),
"of": int(d["fraud"].sum()), "EUR caught": caught / total, "net EUR": caught - REVIEW_COST * len(alerts)}
results = {}
for policy in ["top 10/day by p", "top 10/day by p x amount", "expected loss > 5 EUR"]:
s = results[policy] = run_policy(policy, val)[2]
print(f"val {policy:25s} {s['alerts/day']:5.1f} alerts/day, {s['frauds caught']}/{s['of']} frauds, "
f"{s['EUR caught']:.3f} of fraud EUR, net {s['net EUR']:7.0f} EUR")
best = max(results, key=lambda k: results[k]["net EUR"])
d, alerts, s = run_policy(best, test) # the choice, on the test fortnight once
print(f"TEST {best}: {s['frauds caught']}/{s['of']} frauds, {s['EUR caught']:.3f} of fraud EUR, "
f"precision {alerts['fraud'].mean():.3f}, net {s['net EUR']:.0f} EUR")
missed = d[(d["fraud"] == 1) & ~d.index.isin(alerts.index)]
first = df[df["fraud"] == 1].groupby("card").cumcount() == 0 # first fraud on each card
print(f"missed: {len(missed)}; first fraud of a burst: {int(first[missed.index].sum())} "
f"(of {int(first[d.index[d['fraud'] == 1]].sum())} bursts in the test fortnight), "
f"in person: {int((~df.loc[missed.index, 'online']).sum())}, median amount {missed['amount'].median():.0f} EUR")
print(alerts[alerts["day"] == 80].head(5)[["card", "hour", "amount", "category", "distance_km", "p", "fraud"]].round(2).to_string(index=False))val top 10/day by p 10.0 alerts/day, 58/71 frauds, 0.923 of fraud EUR, net 5978 EUR
val top 10/day by p x amount 10.0 alerts/day, 56/71 frauds, 0.917 of fraud EUR, net 5933 EUR
val expected loss > 5 EUR 5.2 alerts/day, 53/71 frauds, 0.855 of fraud EUR, net 5877 EUR
TEST top 10/day by p: 57/71 frauds, 0.872 of fraud EUR, precision 0.335, net 5060 EUR
missed: 14; first fraud of a burst: 6 (of 18 bursts in the test fortnight), in person: 2, median amount 41 EUR
card hour amount category distance_km p fraud
43 2.29 83.38 electronics 389.54 1.00 1
43 1.89 21.41 fuel 712.91 1.00 1
43 1.81 173.32 restaurant 434.60 1.00 1
506 1.33 85.57 fuel 243.89 1.00 1
43 3.14 18.22 electronics 233.00 0.99 1
On validation the three policies are within 2 % of each other in net value. "Top 10 by " wins narrowly (5,978 EUR); ranking by expected loss catches 2 fewer frauds, and the uncapped cost rule needs only 5.2 alerts a day for nearly the same net value, which is worth telling the team: half the review time buys almost the same result. On the test fortnight the chosen policy catches 57 of 71 frauds (0.803) and 0.872 of the fraud money with 10 alerts a day, precision 0.335 and a net value of 5,060 EUR. All criteria are met; a third of the alerts being real fraud is a good day for a fraud team used to 5 %.
The misses explain themselves: 6 of the 14 are the first fraud of a burst (6 of 18 bursts start undetected), when the card has no suspicious history yet; once a burst has started, n_last_24h and hours_since_prev give it away. The queue for day 80 shows card 43 in four of the top five places: one card's burst fills the queue, which suggests a product change, one alert per card, so a single block stops the burst and frees review slots.
Extensions
- Alert per card: deduplicate the queue by card and measure how many more bursts the freed slots catch.
- Recalibrate a rebalanced model with isotonic regression on validation data and check whether the class-weighted model then works with the cost rule (calibration).
- Label delay: hide fraud labels for the last 14 training days (as chargebacks would) and measure the cost of training on immature labels.
- Drift: fraudsters change tactics; monitor the score distribution and the precision of the alerts weekly (concept drift and delayed labels).
- Anomaly detection for patterns never seen in labels: an isolation forest score as an extra feature.
- Explanations for analysts: show the top features of each alert, so a reviewer knows why the payment is suspicious.
Write-up template
| This run | Yours | |
|---|---|---|
| Data | 81,850 payments, 1,500 cards, 90 days, fraud share 0.0048 | |
| Split | by day: 0-55 / 56-72 / 73-89 | |
| Budget and costs | 10 alerts/day, 5 EUR per review | |
| Baselines (validation) | rules: 53 alerts/day, precision 0.049; logistic PR-AUC 0.469 | |
| Model | LightGBM, no rebalancing, PR-AUC 0.702 on validation | |
| Rebalancing | no variant better beyond noise (bootstrap); weights need a lower learning rate | |
| Policy | top 10/day by p (chosen on validation) | |
| Test fortnight (once) | 57/71 frauds, 0.872 of fraud EUR, precision 0.335, net 5,060 EUR | |
| Main weakness | first fraud of a burst (6 of 18 missed) |
Practice
- Give the logistic regression of Step 2 what trees find on their own: log amount, log distance and a night flag (
hour < 6orhour > 22) in aFunctionTransformerbefore the scaler. How close does it get to LightGBM?
Answer
from sklearn.preprocessing import FunctionTransformer
logit = make_pipeline(
FunctionTransformer(lambda Z: Z.assign(amount=np.log(Z.amount), distance_km=np.log(Z.distance_km),
night=((Z.hour < 6) | (Z.hour > 22)).astype(float))),
StandardScaler(), LogisticRegression(max_iter=2000))PR-AUC rises from 0.469 to 0.720 (LightGBM: 0.702), and the top-10 recall from 0.577 to 0.803 (LightGBM: 0.817). With three engineered features the linear model is as good as the trees on this generator, and it is easier to explain to a regulator. Always give the simple model a fair chance before declaring the complex one necessary.
- A colleague reports "SMOTE improved PR-AUC from 0.702 to 0.757, a 7.8 % gain". What do you answer?
Answer
That the frauds caught at the operating point did not change at all (+0, bootstrap interval from -3 to +3 frauds), and that with 71 positives a PR-AUC difference of 0.05 can come from a handful of payments ranked a little differently. Report the metric the decision uses, with an uncertainty interval, and prefer the simpler model when the difference is not distinguishable from noise.
- Why must
amount_ratiodivide by the mean of the card's earlier payments, and what would happen to validation scores with the mean over all of the card's payments?
Answer
At payment time only the past exists. A mean over all payments includes the current payment and the future ones: a fraud's own large amount raises the mean of a card that otherwise looks normal, and a burst's later payments shape the feature of its first. The model would learn from information it will not have in production, so validation scores would be optimistic and the deployed model worse (the leakage rules).
Test yourself
The fraud share is 0.0046. What PR-AUC does a model with random scores get, roughly?
- 0.5
- 0.0046
- 0.9954
- 0
Class weights of 205 at learning rate 0.08 gave PR-AUC 0.107; at learning rate 0.02 they gave 0.748. What does that show?
- Class weights never work with boosting
- Weights change the effective step size, so the other hyperparameters must be retuned after setting them
- A lower learning rate always fixes imbalance
- The test set was used for tuning
Why was the uncapped rule 'alert when ' only usable with the unweighted model?
- It needs probabilities that are close to the real fraud rates
- It needs exactly 10 alerts a day
- Weighted models cannot rank
- It ignores the amount
Which payments of a fraud burst were hardest to catch?
- The last ones
- The first one, before the card has any suspicious history
- The largest ones
- Those on day 80