Learning path: End-to-End ML Use Cases: Fraud, Recommendations, Forecasting and Ticket Routing · Step 1 of 16
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.
What you will learn
- Ask the three questions a fraud system needs answered before any code
- Turn assumed mistake costs into a total_cost metric
- Write an evaluation contract file before any model exists
- Compute the never-flag and flag-everyone baselines and pick the number to beat
Before you start
- Basic Python and NumPy
- The Cost of Being Wrong: Baselines, a Price per Mistake and the Cheapest Threshold
This is the first part of an end-to-end use case: a real-time fraud score for card payments. Over four articles we go from an empty folder to a model behind an API, released in shadow and monitored. Today, though, we don't train anything. We write down what good means first.
The data is synthetic: 30,000 card transactions made by a small generator, with a fraud rate of 3.72%. The costs are assumed, not measured. Please read every number with that in mind.
Where this part sits
A fraud system has five stages. The first three happen before any model exists, and the middle one, the contract, is the piece to remember.
Think about airport security. Wave everyone through and the queue is lovely, until the one bag that mattered gets on the plane. Stop everyone and open every bag, and it's safe, but the queue goes out of the door. Both are terrible, in different ways. So before you argue about scanners, you agree on what a miss costs and what a false alarm costs. Fraud is exactly the same.
Why accuracy can't see the problem
We keep 6,000 transactions aside for checking (the validation rows, the middle slice in time). A rule that never flags anything is right on 96.13% of them. That looks wonderful.
Now look at what it let through. 232 of those rows are fraud, and every one rode straight past. If one missed fraud costs 100, the bill is 23,200. Accuracy can't see that, because fraud is such a small slice of the rows. That's why the metric gets picked first, before any model can flatter us. (The full story of why accuracy lies on imbalanced data is in The Confusion Matrix.)
Three questions before any code
These are the questions to ask on day one. In a company, somebody from the business gives you the answers. Here they are assumptions.
| Question | Answer in this project | Why it matters |
|---|---|---|
| How fast? | 50 ms at p99 (example target) | A card payment is waiting on our answer. |
| What does each mistake cost? | Miss 100, false alarm 5 (assumed) | One miss is worth 20 false alarms, and that ratio shapes everything after it. |
| When do we find out? | 30 days (assumed) | Fraud comes back as a chargeback, weeks after the payment. |
If you skip these questions, you still get answers. They just come from whatever the code happened to do. Write them down.
The metric as code: total_cost
The second question becomes code in threshold.py. Two constants at the top, both marked as assumed:
"""Pick a threshold by cost, not by 0.5."""
import numpy as np
MISS_COST = 100.0 # one missed fraud (assumed)
ALARM_COST = 5.0 # one false alarm (assumed)
def total_cost(y, score, thr):
flag = score >= thr
misses = int(((~flag) & (y == 1)).sum())
alarms = int((flag & (y == 0)).sum())
return misses * MISS_COST + alarms * ALARM_COST
A row is flagged when its score reaches the threshold. Misses are rows we let go that were fraud. Alarms are rows we stopped that were fine. The function returns one number, in money, and that's our metric. If the idea of a price per mistake is new, The Cost of Being Wrong builds it up from scratch.
contract.py: the rules, written first
The contract is a small file, and we write it before any model exists:
"""Evaluation contract: agreed before any model."""
import numpy as np
from data import make_transactions
from split import time_split
from threshold import ALARM_COST, MISS_COST, total_cost
CONTRACT = {
"metric": "total cost on later rows",
"miss_cost": MISS_COST, # assumed
"alarm_cost": ALARM_COST, # assumed
"p99_budget_ms": 50, # example target
"label_wait_days": 30, # assumed
}
def baselines(y):
never = total_cost(y, np.zeros(len(y)), 0.5)
everyone = total_cost(y, np.ones(len(y)), 0.5)
return never, everyone
if __name__ == "__main__":
for key, value in CONTRACT.items():
print(key, value)
_, va, _ = time_split(make_transactions())
y = va.fraud.values
never, everyone = baselines(y)
print("rows", len(y), "fraud", int(y.sum()))
print("never flag: accuracy", round(1 - y.mean(), 4),
"cost", never)
print("flag everyone: accuracy", round(y.mean(), 4),
"cost", everyone)
A few things to notice:
- The metric says later rows. The model has to be judged on transactions that came after the ones it learned from. The split that makes this true is in Part 2.
- The two costs are imported from
threshold.py, so there's only one place to change them. - The speed limit and the label wait sit here too, so the serving and monitoring parts read the same rules.
Why is this worth a file? Once a model looks good, it's tempting to change the rules. If the rules were written first, you can't quietly move them, and anybody on the team can read them.
The baselines: the number to beat
The last part of the contract is the number every model has to beat. The baselines function has no model in it. "Never" scores every row 0, so nothing is flagged. "Everyone" scores every row 1, so everything is flagged. Running python contract.py prints:
metric total cost on later rows
miss_cost 100.0
alarm_cost 5.0
p99_budget_ms 50
label_wait_days 30
rows 6000 fraud 232
never flag: accuracy 0.9613 cost 23200.0
flag everyone: accuracy 0.0387 cost 28840.0
Flagging everyone catches all 232 frauds, and it stops 5,768 honest customers at 5 each. That's 28,840, and accuracy falls to 3.87%.
So both extremes lose money, and on this data the lazy one is the cheaper of the two. That makes 23,200 our baseline. A model only earns its place if it comes in under that.
Common mistakes
- Reporting accuracy for fraud. 96.13% for a rule that catches nothing. Always report cost, or at least recall and precision (see Precision, Recall and F1).
- Picking costs after you see the model. Then the costs are chosen to make the model look good. Fix them in the contract first.
- Only checking one baseline. Which extreme is cheaper depends on the cost ratio, so compute both.
- Forgetting the label wait. If labels take 30 days, you can't grade yesterday's model today. Part 4 shows what goes wrong when you try.
Recap
| Step | Result on 6,000 validation rows |
|---|---|
| Never flag | accuracy 96.13%, cost 23,200 |
| Three questions | 50 ms p99 (example), miss 100 / alarm 5 (assumed), 30-day wait (assumed) |
| Flag everyone | accuracy 3.87%, cost 28,840 |
| Number to beat | 23,200 |
Try it yourself: set ALARM_COST to 1 in threshold.py, rerun contract.py, and see which baseline wins. The project files are in the community, free to join.
Next: Part 2, training with time splits and leak-free features.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →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 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.
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.