Learning path: End-to-End ML Use Cases: Fraud, Recommendations, Forecasting and Ticket Routing · Step 2 of 16
Fraud Scoring, Part 2: Training With Time Splits, Leak-Free Features and a Cost-Picked Threshold
Train the fraud model against its contract: a time split of 30,000 synthetic transactions, a card_n_1h feature that never looks ahead, XGBoost that pays 23,200 at 0.5, and a cost-picked threshold of 0.045 that brings validation to 14,955 and test to 16,765.
What you will learn
- Split fraud transactions by time into train, validation and test
- Build a last-hour velocity feature that only looks backwards, and test that it ignores the future
- Train XGBoost in a pipeline and see why the 0.5 threshold flags nothing
- Pick the threshold from the cost table, then check calibration and score the test rows once
Before you start
- Fraud Scoring, Part 1: The Problem, the Metric and the Baseline
- Time Splits and Group Splits
- Boosting: AdaBoost, Gradient Boosting and XGBoost
In Part 1 we wrote the contract: total cost on later rows, a miss costs 100, a false alarm costs 5 (both assumed), and the number to beat is 23,200, what a rule that never flags pays. Now we train against it.
It's the same synthetic data, 30,000 card transactions, with the same assumed costs. Read the results with that in mind, because a couple of them are not what you'd hope.
The rule for today: remember the past, never look ahead
Picture a bank teller. A card comes across the counter, and she remembers it was used twice in the last hour. She can't know about the swipe that happens tomorrow, because it hasn't happened yet. A model is easy to cheat that way, though. Build its features from the full table and it's allowed to peek at tomorrow.
So does breaking that rule show up in the score? I tried it with a plain logistic regression and measured PR-AUC (average precision) on the validation rows:
| Setup | PR-AUC |
|---|---|
| Time split, safe features | 0.111 |
| Leaky feature (each card's average uses the whole table, future included) | 0.111 |
| Shuffled split | 0.116 |
Cheating did not blow up the score here. This synthetic fraud comes from the amount and the hour, so there's no card history to leak. We keep the rule anyway, because a clean score doesn't prove there's no leak. A test is what guards it.
Split by time, not by shuffle
The split lives in split.py. Sort by t, the time of the transaction, cut at 60% and 80%, and never shuffle:
"""Time-ordered train / validation / test split."""
def time_split(df, train=0.6, valid=0.2):
df = df.sort_values("t")
a = int(len(df) * train)
b = int(len(df) * (train + valid))
return df.iloc[:a], df.iloc[a:b], df.iloc[b:]
More on choosing a split that matches how the model is used is in Time Splits and Group Splits.
The teller's memory: card_n_1h
Now a feature that remembers: how many earlier transactions this card had in the last hour. It's in train_xgb.py:
def add_velocity(df, window=3600):
"""Earlier rows on this card in the last hour."""
df = df.sort_values("t").copy()
t = df["t"].values
out = np.zeros(len(df), dtype=int)
for idx in df.groupby("card").indices.values():
start = np.searchsorted(t[idx], t[idx] - window)
out[idx] = np.arange(len(idx)) - start
df["card_n_1h"] = out
return df
For each card, we take its transaction times in order, and searchsorted finds the first one inside the last hour. The row's position minus that start is the count of earlier rows in the window. It only ever looks backwards.
Card 650 shows it. Its first row has nothing behind it, so 0. About 24 minutes later another row comes in, and it counts 1.
The other features in features.py follow the same rule: card_n_before uses cumcount(), and the card's mean amount before this row uses a cumulative sum minus the current amount. The project's test checks it by rebuilding features on the first 1,000 rows alone and comparing:
def test_features_ignore_the_future():
df = make_transactions(2000)
full = add_features(df)
part = add_features(df.iloc[:1000])
k = part.index
assert np.allclose(full.loc[k, "ratio"], part["ratio"])
If a feature peeked at later rows, the values would differ and the test would fail. That's the general idea behind point-in-time correctness.
Here's what running python train_xgb.py sqlite:///mlflow.db said about the velocity feature:
rows with a card_n_1h above 0 280 of 30000
same on the first 1000 rows True
without velocity: PR-AUC 0.105
with velocity: PR-AUC 0.109
To be honest about it: this feature barely fires. Only 280 of 30,000 rows are above zero, and PR-AUC moves from 0.105 to 0.109. This data has no bursts of card use for it to find.
A pipeline, and the 0.5 trap
def fit_score(tr, va, cols):
model = make_pipeline(
SimpleImputer(strategy="median"),
XGBClassifier(n_estimators=150, max_depth=3,
learning_rate=0.1, n_jobs=1,
random_state=7))
model.fit(tr[cols].values, tr.fraud)
scores = model.predict_proba(va[cols].values)
return model, scores[:, 1]
An imputer, then XGBoost with 150 small trees. The imputer learns its fill values on training rows only, and it travels with the model, so serving does the same thing. There's nothing missing in this data, so today it simply passes through.
PR-AUC with velocity is 0.109. The plain logistic regression had 0.111, so all those trees didn't buy better ranking here.
Now the default threshold. The highest score in validation is about 0.41, so at 0.5 nothing gets flagged:
cost at 0.5 23200.0
That's exactly what the rule that does nothing pays. The model isn't the issue. The threshold is.
Choose the threshold from the cost table
best_threshold in threshold.py tries 190 values and keeps the cheapest:
def best_threshold(y, score):
grid = np.linspace(0.005, 0.95, 190)
costs = [total_cost(y, score, t) for t in grid]
i = int(np.argmin(costs))
return float(grid[i]), float(costs[i])
Way down at 0.005, alarms push the bill to 27,190. Move right and it falls: 16,970 at 0.025, and the bottom is 0.045 at 14,955. Past that it climbs again, 20,650 at 0.105, and drifts back toward 23,200.
Open up the bottom. We miss 79 frauds, that's 7,900, and we raise 1,411 false alarms, that's 7,055. We took a lot of alarms to save 8,245 against the baseline, and that only pays because one alarm is so much cheaper than one miss.
Calibrated, tested once, tracked
When this model says 10%, is it about 10%? calibration_table sorts the scores into five equal groups:
best threshold 0.045 cost 14955.0
predicted 0.0058 actual 0.01
predicted 0.0133 actual 0.0075
predicted 0.0221 actual 0.03
predicted 0.039 actual 0.0375
predicted 0.1064 actual 0.1091
test cost once 16765.0
logged run
The top group predicts 0.1064 and the actual rate is 0.1091. That's close. The second lowest is weaker, 0.0133 against 0.0075, and that rests on a handful of frauds. So reasonably calibrated, not perfectly. (Fixing calibration is covered in Probability Calibration.)
Then the test rows, once, with the threshold already fixed: 16,765. MLflow logs it beside the threshold and the validation cost (see Experiment Tracking with MLflow).
And here's the part worth remembering:
| Model | Validation cost | Test cost (once) |
|---|---|---|
| XGBoost + velocity, threshold 0.045 | 14,955 | 16,765 |
| Logistic regression, threshold 0.04 | 15,340 | 16,040 |
| Never flag (baseline) | 23,200 | - |
On validation, XGBoost beat the plain model. On test, the plain model was cheaper. That small validation win didn't hold, and on this simple synthetic data, more trees didn't earn their place. Both beat the baseline comfortably.
Common mistakes
- Shuffling transaction data before splitting. The model then trains on the future. Sort by time and cut.
- Building per-card aggregates over the whole table. Use cumulative or windowed versions that only see earlier rows, and keep a test that proves it.
- Keeping the 0.5 threshold. With 3.72% fraud, scores rarely get near 0.5. Here it flagged nothing.
- Tuning on test. Pick the threshold on validation, then score test once. Looking at test twice turns it into a second validation set.
Recap
| Step | Result |
|---|---|
| Time split | 18,000 / 6,000 / 6,000 rows, 649 / 232 / 235 fraud |
| card_n_1h | backward only, 280 of 30,000 rows above 0, PR-AUC 0.105 to 0.109 |
| XGBoost at 0.5 | nothing flagged, cost 23,200 |
| Cost-picked threshold | 0.045, validation 14,955 (79 misses, 1,411 alarms) |
| Test, once | 16,765 (logistic regression: 16,040) |
Try it yourself: set ALARM_COST to 20, rerun train_xgb.py, read only the validation lines, and see where the threshold moves.
Next: Part 3, serving it with FastAPI, Docker and a 50 ms budget.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Fraud Scoring, Part 1: The Problem, the Metric and the Baseline
Next →Fraud Scoring, Part 3: Serving It With FastAPI, Docker and a 50 ms Budget
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Project: Car Price Predictor End to End, from CSV to a FastAPI Price API
The whole ML workflow on 205 cars: clean the brand out of CarName, split first, audition five regressors on the same folds, tune the random forest, test once (RMSE 2,195, R2 0.939), save it and serve prices with FastAPI.
Fraud Scoring, Part 1: The Problem, the Metric and the Baseline
Before training a fraud model, write down what good means. On 6,000 synthetic validation transactions, a rule that never flags is 96.13% accurate and costs 23,200, flagging everyone costs 28,840, and a small contract.py fixes the rules first.
Fraud Scoring, Part 3: Serving It With FastAPI, Docker and a 50 ms Budget
A payment is waiting on the fraud score. Time each stage (the model takes 0.43 ms of a 3.3 ms request), then load test: p99 is 6.1 ms with one client and 163.3 ms with 32, against an example 50 ms budget. Then a Dockerfile, built and run once.
Fraud Scoring, Part 4: Release and Monitoring With Shadow, Drift and Late Labels
A challenger fraud model runs in shadow beside the champion. Background shadow costs about a millisecond at p50, simulated drift takes PSI from 0.007 to 0.181, and a recall of 1.00 on day 35 turns into 0.41 by day 80 once the chargebacks arrive.