Somebody steals your card, buys a television at 3 a.m., and your bank’s fraud system waves it through because its model is 99% accurate. That is what happens when you measure the wrong thing — and credit card fraud detection machine learning keeps measuring the wrong thing and printing the number on a slide like it means something.
Here is the real number. I built a fraud catcher and tested it on transactions it had never seen. It caught 24 out of 40 fraud cases: 60.00% recall. It also flagged 35 innocent shoppers, so its precision was 40.68%. Its accuracy was 97.45%. And a model that does literally nothing — one that says “looks fine to me” to every transaction — scored 98.00% accuracy. Higher, if you only read the one number everyone quotes. Completely useless, because it caught zero fraud.
Every number here comes from the demo you can run in about a minute: a built-in sample of 10,000 transactions with 200 fraud cases, a 2.00% fraud rate. That is NOT the full Kaggle dataset — the real one has 284,807 transactions and only 492 fraud cases, a 0.172% fraud rate. My sample is deliberately easier, more than ten times more fraud and five features instead of twenty-eight, and the model still only catches 60% of the fraud.

Why accuracy lies
Picture a street with 10,000 houses, 200 of them on fire. You hire a fire spotter who says “no fires here” every day. He is right 9,800 times out of 10,000: 98.00% accuracy — and the worst fire spotter in history, because 200 houses burned down while he was being 98% correct.
That is exactly what happens with card fraud. In my sample, 9,800 transactions are legitimate and 200 are fraud. A model that predicts “legitimate” for every transaction gets 9,800 right and 200 wrong: 98.00% accuracy. It is a brick. It has never caught a thief and never will, because catching thieves was never part of what accuracy rewards — accuracy rewards agreeing with the majority, and the majority is always “nothing bad is happening.”
The demo proves it in one command: the training script prints the lazy baseline right under the real model’s scores — accuracy 98.00%, recall 0.00%. The real model scores lower on accuracy, 97.45%, and higher on everything that matters. Pick a model by accuracy alone and you pick the brick.
The fix is asking a better question: not “how often was it right?” but “of the fraud that happened, how much did it catch?” and “of the transactions it flagged, how many were actually fraud?” Those two questions have names — recall and precision.
What you need
You need Python 3.10 or newer, a terminal, and about five minutes. No Kaggle account, no download, no cloud anything — the demo runs completely offline on its own sample data.
The stack is Python with pandas, scikit-learn, and XGBoost. If XGBoost is missing, the code says so and falls back to a RandomForest. No GPU, no server: training on 8,000 rows takes a few seconds.
Each file has one job: config.py holds the settings (seed 42, 10,000 rows, 2.00% fraud, 80/20 split, threshold 0.5), generate_sample.py builds the sample CSV, data.py loads it, train.py trains and reports the honest metrics, predict.py scores one transaction, and requirements.txt lists the four dependencies.
Install it the normal way:
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txtNo API keys, no accounts. The hard part was never the setup — it is understanding what the numbers mean.
How it works
A transaction arrives: a time, an amount, and five anonymised features called V1 to V5. The real Kaggle data has twenty-eight V-features, produced by PCA, which squashes the original card details into numbers hiding anything personal. My sample keeps five: fraud transactions have V-values shifted away from zero and amounts skewed higher, while legitimate transactions cluster around ordinary spending.

Training is showing the model 8,000 labelled transactions — 7,840 legitimate, 160 fraud — and letting it find the patterns that separate them. XGBoost builds 200 small decision trees, each correcting the last one’s mistakes, with a maximum depth of 4 and a learning rate of 0.08. Because fraud is rare, training uses a weight called scale_pos_weight, set to 49 — 7,840 divided by 160. Missing one fraud case counts about 49 times more than misjudging one normal purchase.
Then the model is tested on 2,000 transactions it has never seen: 1,960 legitimate, 40 fraud. Testing on data it already studied would be like giving a student the exam paper early. The 80/20 split keeps the 2.00% fraud rate the same in both halves, so the test is fair.
Scoring is a probability between 0 and 1: the model’s confidence that a transaction is fraud. The threshold is 0.5, so anything at 0.5 or above gets flagged. That threshold is a knob, not a law of nature — turn it down and you catch more fraud but annoy more innocent shoppers; turn it up and the false alarms stop but thieves slip through.
The maths
Here is the part most tutorials skip, which is strange, because it is the entire point. You need four numbers, and they all come from one little table called a confusion matrix — the exact table the demo printed for the test set:
Predicted legit Predicted fraud
Actually legit 1,925 35
Actually fraud 16 24Top left, 1,925: innocent transactions correctly left alone — true negatives. Top right, 35: innocent transactions wrongly flagged — false positives, real people getting their card declined while buying groceries. Bottom left, 16: fraud the model missed — false negatives. Bottom right, 24: fraud the model caught — true positives. Every metric is arithmetic on those four numbers.
Precision answers: when the model shouts “fraud!”, how often is it right? It flagged 24 real frauds and 35 innocent shoppers — 59 flags — so precision is 24 divided by 59, which is 0.4068, or 40.68%. More than half of what it flags is innocent. Auto-block every flagged transaction and you decline 35 real customers for every 24 thieves you stop, which is why banks send flagged transactions to human review. Precision is the price of the alarm.
Recall answers: of all the fraud that actually happened, how much did the model catch? It caught 24 of 40, so recall is 24 divided by 40, which is 0.6000, or 60.00%. The other 16 sailed through. Recall is the number you care about when you are the victim, because a missed fraud case is money gone.
F1 is the compromise: the harmonic mean of precision and recall, which punishes a model good at one and terrible at the other. With precision at 40.68% and recall at 60.00%, F1 is 0.4848, or 48.48% — 2 times 0.4068 times 0.6000, divided by 1.0068.
And accuracy? All the correct predictions divided by everything: 1,925 plus 24, divided by 2,000, which is 0.9745, or 97.45%. Compare that with the lazy baseline: predict “legitimate” for all 2,000 test transactions and you get 1,960 right — 98.00% accuracy with a recall of 0.00%. The brick beats the real model on accuracy and catches nothing. That is the imbalance trap: accuracy counts the 1,960 easy legitimate transactions and drowns out the 40 fraud cases that matter. On the real Kaggle data the trap is far worse — the fraud rate is 0.172%, so a do-nothing model would score 99.83% accuracy there. A 99% accuracy claim without precision and recall next to it is not a result, it is a warning sign.
Build it
Generate the sample data first — one command, deterministic, same file every time:
python3 generate_sample.pyIt prints Wrote 10,000 rows: 200 fraud (2.00%), 9,800 legitimate (98.00%). The generator is worth reading — the whole trick is visible in about thirty lines. Legitimate amounts come from a log-normal distribution centred low, fraud amounts from one centred higher, and the five V-features are centred at zero for legitimate transactions and shifted for fraud (V1 by minus 1.8, V2 by plus 1.2, V3 by minus 0.9, V4 by plus 0.7, V5 by minus 0.5). Then everything is shuffled with seed 42.
Next, train the model:
python3 train.pyThe script loads the CSV, splits it 80/20 with stratification, builds XGBoost with scale_pos_weight of 49, trains on 8,000 rows, and evaluates on the 2,000 it has never seen. It prints the confusion matrix, precision, recall, F1 and accuracy — then the lazy baseline, so you cannot walk away with only the flattering number — and saves the model to fraud_model.pkl.
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix, precision_score, recall_score, f1_score
from xgboost import XGBClassifier
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.20, random_state=42, stratify=y
)
model = XGBClassifier(
n_estimators=200, max_depth=4, learning_rate=0.08,
scale_pos_weight=49, eval_metric="logloss", random_state=42,
)
model.fit(X_train, y_train)
y_pred = (model.predict_proba(X_test)[:, 1] >= 0.5).astype(int)
tn, fp, fn, tp = confusion_matrix(y_test, y_pred).ravel()That last line is the whole evaluation. Four numbers; everything else is arithmetic on them.
Finally, score a transaction. With no arguments it scores three built-in examples:
python3 predict.pyOr score your own:
python3 predict.py --time 3600 --amount 499.99 --v1 -2.1 --v2 1.4 --v3 -1.0 --v4 0.8 --v5 -0.6The script loads the saved model (or trains one first if you deleted it) and prints a fraud probability plus a verdict: block or review above 0.5, allow below it. In a real system this runs in milliseconds while the customer is still at the till — which is why the model is small and the features are simple.
The folder structure is exactly what you would expect:
fraud-catcher/
├── config.py
├── generate_sample.py
├── data.py
├── train.py
├── predict.py
├── requirements.txt
├── README.md
└── sample_data/
└── transactions_sample.csv
One job per file, settings in one place, data in one folder. To swap in the real Kaggle data, the README explains how: download creditcard.csv, point config.py at it, extend the features from V1–V5 to V1–V28, and rerun train.py. Nothing else changes.
Expected outcome
You should see exactly what I saw — the seed is fixed and the data is generated, not downloaded. The dataset is 10,000 transactions with 200 fraud (2.00%): 8,000 training rows, and a 2,000-row test set with 40 fraud and 1,960 legitimate transactions. The model is XGBoost with 200 trees, and the threshold is 0.5.

The test-set confusion matrix is 1,925 true negatives, 35 false positives, 16 false negatives, and 24 true positives. Precision is 40.68%, recall is 60.00%, F1 is 48.48%, and accuracy is 97.45%. The lazy baseline — predict “legitimate” for everything — scores 98.00% accuracy and 0.00% recall. The model that does nothing beats the real model on accuracy, 98.00% to 97.45%, while catching zero of the 40 fraud cases.
The scorer tells the same story in miniature. A textbook fraud case — $812.40, V1 at minus 2.6, V2 at plus 1.9 — scores 99.93% and gets blocked. An ordinary $24.99 purchase scores 0.02% and goes through. A borderline case, a $1,499.00 purchase with normal-looking V-features, scores just 1.43% and is allowed: amount alone is not enough to convict a transaction.
Do not expect better numbers on the real data. On the full Kaggle set, with a 0.172% fraud rate instead of 2.00%, precision and recall will both drop — finding 492 fraud cases among 284,807 transactions is a much harder search. Anyone promising 95% precision and recall there is either leaking the answer into the training data or selling something.
What broke
The first thing that broke was the environment, before a single line of my code ran. The machine had pandas and numpy, but no scikit-learn and no XGBoost. pip install scikit-learn was refused — the system Python is externally managed and pip will not touch it. pip install --user reported success, and then Python still could not find the package: it had landed in a user site directory this Python does not put on its path. Two installs, zero working imports. The fix was a system-wide install with --break-system-packages, which put scikit-learn 1.9.1 and XGBoost 3.4.1 where Python actually looks.
The second thing that broke was my own assumption. I assumed the trained model would obviously beat the do-nothing baseline on every metric. It does not. It loses on accuracy, 97.45% against 98.00%, because it tries: every false alarm — 35 innocent transactions flagged — costs it accuracy points the lazy model never spends, because the lazy model never flags anything. The model is better in every way that matters and worse on the one number people quote most. If you feel a small sting when you see the baseline win on accuracy, good. That sting is the project working.
Download the full project
Everything in this article is in the project zip:
Premium Download
Get the complete project code
Unzip it, install the four dependencies, run generate_sample.py, then train.py, then predict.py, and you will see the same confusion matrix, the same 40.68% precision, the same 60.00% recall, and the same 98.00% accuracy for a model that catches nothing. Then change the threshold in config.py — try 0.3, try 0.7 — and watch precision and recall trade places like they are on a seesaw. That is credit card fraud detection machine learning without the fairy tale.
