Fraud detection with machine learning means training a model to score each transaction by how likely it is to be fraudulent, then deciding which scores are worth an alert. Most of the difficulty sits outside the model: fraud is rare, the two kinds of mistake cost very different amounts, and the data changes over time.
This tutorial builds a complete fraud detection pipeline in Python on 284,807 real card transactions. Every number below comes from running the code on a 2-core CPU, and the full script is included. Along the way you will see a model that is 99.87% accurate while catching zero fraud, a popular library collapse under one setting, and why the threshold you pick matters as much as the model.

Key takeaways
- Accuracy is useless for fraud detection. Predicting “legit” for everything scores 99.87% on this data and catches nothing.
- Use PR-AUC to compare models and money to choose a threshold.
- Split by time. The model will only ever score future transactions, so test it that way.
- Gradient boosting (XGBoost, LightGBM) beat logistic regression here, 0.805 PR-AUC against 0.709.
- Class weights can break LightGBM on extreme imbalance. Regularisation fixed it in this run.
What is fraud detection in machine learning?
Fraud detection in machine learning is a binary classification task. Each row is an event (a card payment, a login, an insurance claim) and the label says whether it turned out to be fraud. The model learns patterns from labelled history and assigns new events a probability. A threshold then turns that probability into an action such as block, review or allow.
The demand is real. In the United States alone, consumers reported $15.9 billion in fraud losses for 2025 to the Federal Trade Commission, up from $12.5 billion in 2024. That figure covers only what people reported, and it includes scams where no card model would ever fire. Card fraud, account takeover and payment fraud are the parts where machine learning does most of the work.
Here is how the FTC figures break down, as reported in April 2026:
| FTC Consumer Sentinel figure | 2025 value |
|---|---|
| Total reported fraud losses | $15.9 billion |
| Total reported losses in 2024 | $12.5 billion |
| Fraud reports filed | about 3 million |
| Losses to investment scams | $7.9 billion |
| Losses to impostor scams | more than $3.5 billion |
Bank transfers and cryptocurrency carried the largest losses, while credit cards were the payment method people reported most often, according to Crowdfund Insider’s summary of the FTC data.
Why fraud detection is harder than ordinary classification
Most tutorials treat fraud like any other classification problem. It has five properties that change how you should build and judge the model:
- Extreme imbalance. Here 0.17% of transactions are fraud. A model can ignore the minority class and still look excellent on accuracy.
- Unequal costs. Missing a $2,000 fraud costs far more than one analyst reviewing a harmless payment.
- Drift. Fraudsters change tactics when they get caught, so patterns from last month may not hold next month.
- Label delay. A transaction is often confirmed as fraud days or weeks later, after a chargeback.
- Adversaries. Unlike weather or house prices, the thing you predict is actively trying to look normal.
Each step below handles at least one of these.
The dataset: 284,807 real card transactions
The tutorial uses the public credit card fraud dataset released by the Machine Learning Group at ULB (Université Libre de Bruxelles), first described in Dal Pozzolo and colleagues’ 2015 paper on calibrating probabilities under undersampling. It is the standard benchmark for credit card fraud detection because it is real, large and very imbalanced.
| Property | Value |
|---|---|
| Transactions | 284,807 |
| Fraud cases | 492 (0.173%) |
| Time span | two days in September 2013, European cardholders |
| Features | V1 to V28 (PCA components), Time, Amount |
| Label | Class (1 = fraud) |
The 28 V columns are principal components of the original features. The bank anonymised them, so you cannot see what they mean, which is a limitation worth keeping in mind. Time is the number of seconds since the first transaction in the file, not a clock time, so it cannot tell you the hour of day.
Step 1: Set up the environment
You need Python 3.10 or later and five libraries. These are the versions I ran:
| Package | Version |
|---|---|
| scikit-learn | 1.9.1 |
| pandas | 3.0.5 |
| LightGBM | 4.7.0 |
| XGBoost | 3.4.1 |
| imbalanced-learn | 0.14.2 |
python -m venv fraud-env
source fraud-env/bin/activate # Windows: fraud-env\Scripts\activate
pip install scikit-learn pandas lightgbm xgboost imbalanced-learn joblib
Download creditcard.csv from the dataset page and put it next to your script. Everything else runs on a laptop; the slowest model here fits in about 6 seconds on two cores.
Step 2: Load the data and look at the imbalance
Start by measuring how rare fraud is and what accuracy a lazy model would get.
import sys
import time
import numpy as np
import pandas as pd
import lightgbm as lgb
import xgboost as xgb
from imblearn.over_sampling import SMOTE
from imblearn.pipeline import make_pipeline as make_imb_pipeline
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, average_precision_score, roc_auc_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
df = pd.read_csv(sys.argv[1] if len(sys.argv) > 1 else "creditcard.csv")
df = df.sort_values("Time").reset_index(drop=True)
print(f"Rows: {len(df):,} | frauds: {df.Class.sum()} | fraud rate: {df.Class.mean():.3%}")
Output:
Rows: 284,807 | frauds: 492 | fraud rate: 0.173%
A few more facts from exploring the file, worth knowing before you model it:
- Fraudulent amounts are smaller on the median: $9.25 against $22.00 for legitimate payments.
- Their mean is higher ($122.21 against $88.29), because a handful of large frauds pull it up. The largest single fraud is $2,125.87.
- 27 frauds have an amount of zero, which often means a card test before a real attempt.
- All 492 frauds add up to $60,127.97.
- 1,081 rows are exact duplicates. I kept them so the numbers match other work on this dataset, but in a production system you would investigate them.
The small median is typical. Fraudsters often test a stolen card with a tiny payment before trying a large one, so “small amount” alone is a weak signal.
Step 3: Split the data by time, not at random
This is the step most fraud detection tutorials skip. A random split mixes early and late transactions, so the model trains on the future and is tested on the past. Real fraud detection always runs forward in time, so the test should too.
I split the sorted data into three consecutive blocks:
| Block | Share | Purpose | Frauds |
|---|---|---|---|
| Fit | first 70% | train the models | 384 |
| Validation | next 10% | pick the best model and the threshold | 33 |
| Test | last 20% | report final numbers, used once | 75 |
# Split by time: fit on the first 70%, tune the threshold on the next 10%, test on the last 20%
n = len(df)
fit_df, val_df, test_df = df.iloc[: int(n * 0.7)], df.iloc[int(n * 0.7): int(n * 0.8)], df.iloc[int(n * 0.8):]
FEATURES = [c for c in df.columns if c not in ("Class", "Time")]
X_fit, y_fit = fit_df[FEATURES], fit_df["Class"]
X_val, y_val = val_df[FEATURES], val_df["Class"]
X_test, y_test = test_df[FEATURES], test_df["Class"]
print(f"Frauds per split: fit {y_fit.sum()}, validation {y_val.sum()}, test {y_test.sum()}")
Output:
Frauds per split: fit 384, validation 33, test 75
I dropped Time from the features. As seconds since the start of the file, it only tells the model where a row sits in this particular recording, which would not generalise to next month. The validation block is small (33 frauds), and you will see later how that limits threshold tuning.
How much does the split choice matter? In a separate test with the same XGBoost settings, a random split gave a PR-AUC of 0.851 and the time split gave 0.779. The random split flatters the model by about 0.07, and our data leakage guide walks through that experiment and five other leaks.
Step 4: Choose metrics that fit fraud detection
Before training anything, decide how you will score it. Here is what the “always legit” model gets:
print(f"Accuracy of predicting 'legit' for everything: {accuracy_score(y_test, np.zeros(len(y_test))):.3%}")
Accuracy of predicting 'legit' for everything: 99.868%
That model catches no fraud at all and still beats 99.8%. Accuracy rewards the majority class, so it tells you almost nothing here. These metrics are more useful:
| Metric | What it measures | Use it for |
|---|---|---|
| PR-AUC (average precision) | Precision and recall across all thresholds, focused on the fraud class | Comparing models on imbalanced data |
| ROC-AUC | How well scores rank fraud above legit across all thresholds | A secondary check; it looks good too easily when negatives dominate |
| Precision at a threshold | Share of alerts that are real fraud | Analyst workload |
| Recall at a threshold | Share of all fraud you catch | Losses avoided |
| Expected cost | Review costs plus fraud you miss, in money | Choosing the threshold |
PR-AUC is the main model metric in this tutorial. ROC-AUC is reported alongside it, and you will see why it can mislead: several models score 0.98 ROC-AUC while their PR-AUC differs by almost 0.1.
Step 5: Train baselines and gradient boosting models
I trained seven fraud detection models on the fit block, all with fixed seeds:
- three logistic regressions: plain, with balanced class weights, and with SMOTE oversampling
- XGBoost with 400 trees
- three versions of LightGBM: defaults, weighted, and weighted plus regularised
models = {
"Logistic regression": make_pipeline(StandardScaler(), LogisticRegression(max_iter=2000)),
"Logistic regression, balanced": make_pipeline(
StandardScaler(), LogisticRegression(max_iter=2000, class_weight="balanced")),
"Logistic regression + SMOTE": make_imb_pipeline(
StandardScaler(), SMOTE(random_state=42), LogisticRegression(max_iter=2000)),
"XGBoost": xgb.XGBClassifier(
n_estimators=400, learning_rate=0.05, max_depth=6, n_jobs=2, random_state=42),
"LightGBM, defaults": lgb.LGBMClassifier(
n_estimators=400, learning_rate=0.05, verbose=-1, random_state=42),
"LightGBM, weighted": lgb.LGBMClassifier(
n_estimators=400, learning_rate=0.05, scale_pos_weight=10, verbose=-1, random_state=42),
"LightGBM, weighted + regularised": lgb.LGBMClassifier(
n_estimators=400, learning_rate=0.05, scale_pos_weight=10, min_child_samples=100,
reg_lambda=5, subsample=0.8, subsample_freq=1, colsample_bytree=0.8,
verbose=-1, random_state=42),
}
scores = {}
print(f"{'Model':<34}{'PR-AUC':>8}{'ROC-AUC':>9}{'Fit (s)':>9}")
for name, model in models.items():
start = time.perf_counter()
model.fit(X_fit, y_fit)
seconds = time.perf_counter() - start
p_val, p_test = model.predict_proba(X_val)[:, 1], model.predict_proba(X_test)[:, 1]
scores[name] = (p_val, p_test)
print(f"{name:<34}{average_precision_score(y_test, p_test):>8.3f}"
f"{roc_auc_score(y_test, p_test):>9.3f}{seconds:>9.1f}")
Results on the test block (last 20% of the timeline):
| Model | PR-AUC | ROC-AUC | Fit time (s) |
|---|---|---|---|
| Logistic regression | 0.709 | 0.975 | 0.3 |
| Logistic regression, balanced | 0.746 | 0.983 | 0.4 |
| Logistic regression + SMOTE | 0.757 | 0.982 | 1.1 |
| XGBoost | 0.805 | 0.983 | 5.0 |
| LightGBM, defaults | 0.791 | 0.984 | 6.1 |
| LightGBM, weighted | 0.311 | 0.859 | 5.3 |
| LightGBM, weighted + regularised | 0.801 | 0.981 | 5.8 |

What the table says:
- Gradient boosting wins. XGBoost and the two working LightGBM models land around 0.79 to 0.81 PR-AUC, roughly 0.05 to 0.1 above logistic regression.
- Class weights and SMOTE help logistic regression. Both lift it by about 0.04 to 0.05 PR-AUC over the plain version.
- ROC-AUC hides the differences. Six of the seven models sit between 0.975 and 0.984 ROC-AUC, while their PR-AUC ranges from 0.709 to 0.805.
- One model failed badly, and it is worth understanding why.
Why weighted LightGBM collapsed
Setting scale_pos_weight=10 tells LightGBM to count each fraud ten times. With only 384 frauds among about 200,000 rows, that pushes the trees to build tiny leaves around a few heavily weighted points, and their leaf values become extreme. The result was a PR-AUC of 0.311, worse than plain logistic regression.
The score was also unstable. Across earlier runs on a busy machine, the same configuration gave 0.212 and 0.311. In a separate three-seed benchmark with LightGBM’s out-of-the-box settings (100 trees, learning rate 0.1) and random splits, fraud PR-AUC ranged from 0.02 to 0.31. A score that swings that much between runs points to the training setup.
Adding regularisation fixed it:
| Setting | Value | Effect |
|---|---|---|
| min_child_samples | 100 | each leaf needs at least 100 rows |
| reg_lambda | 5 | L2 penalty on leaf values |
| subsample and subsample_freq | 0.8 and 1 | each tree sees 80% of rows |
| colsample_bytree | 0.8 | each tree sees 80% of features |
With those four settings the weighted model scored 0.801, close to XGBoost. The practical lesson: when you weight or resample for imbalance, regularise at the same time and check stability across several seeds.
Class weights or SMOTE?
On this data both gave similar lifts to logistic regression (0.746 with balanced weights, 0.757 with SMOTE). Class weights are simpler, faster and add no synthetic rows, so I would start there. If you do use SMOTE, put it inside an imbalanced-learn pipeline as above, so synthetic rows are created from training data only. Oversampling before the split produced a fake 100% fraud recall in our leakage tests.
Step 6: Choose the threshold by cost
A model outputs probabilities. The business needs a yes or no. Picking the threshold is where fraud detection meets money, so I scored each threshold with a simple cost model:
- every flagged transaction costs one analyst review, assumed at $5
- every missed fraud costs its full amount
First the best model is picked by PR-AUC on the validation block. Then the threshold is chosen on the same validation block. The test block is used only to report results.
REVIEW_COST = 5.0 # assumed cost of one analyst review, in dollars
def money(p, y, amount, threshold):
flagged = p >= threshold
missed = (~flagged) & (y == 1)
return flagged.sum() * REVIEW_COST + amount[missed].sum()
best = max(scores, key=lambda m: average_precision_score(y_val, scores[m][0])) # pick on validation
p_val, p_test = scores[best]
print(f"\nBest model on the validation slice: {best}")
grid = np.round(np.arange(0.01, 1.0, 0.01), 2)
costs = [money(p_val, y_val.to_numpy(), val_df["Amount"].to_numpy(), t) for t in grid]
t_star = grid[int(np.argmin(costs))]
y, amount = y_test.to_numpy(), test_df["Amount"].to_numpy()
print(f"\n{best}, judged on the test period (${amount[y == 1].sum():,.2f} of fraud in total):")
for label, t in [("0.50 (default)", 0.50), (f"{t_star:.2f} (cost-tuned on validation)", t_star)]:
flagged = p_test >= t
tp = int((flagged & (y == 1)).sum())
fp = int((flagged & (y == 0)).sum())
print(f" threshold {label}: caught {tp}/{int(y.sum())} frauds, {fp} false alarms, "
f"fraud $ missed {amount[(~flagged) & (y == 1)].sum():,.2f}, "
f"total cost ${money(p_test, y, amount, t):,.2f}")
Output:
Best model on the validation slice: LightGBM, weighted + regularised
LightGBM, weighted + regularised, judged on the test period ($7,729.26 of fraud in total):
threshold 0.50 (default): caught 57/75 frauds, 6 false alarms, fraud $ missed 2,638.27, total cost $2,953.27
threshold 0.42 (cost-tuned on validation): caught 57/75 frauds, 8 false alarms, fraud $ missed 2,638.27, total cost $2,963.27
The validation block picked the regularised LightGBM model, slightly ahead of XGBoost there even though XGBoost was marginally better on the test block. That is normal: you choose on validation and accept whatever the test says.
The cost-tuned threshold (0.42) did no better than 0.50 on the test period. It caught the same 57 frauds and raised two extra alarms, costing $10 more. With only 33 frauds in the validation block, the cost curve is too noisy to tune finely. In a real system you would tune on weeks of validation data, not a few hours.
How precision and recall trade off
To see the whole range, I scored the same model at several thresholds on the test block:
| Threshold | Flagged | Precision | Recall |
|---|---|---|---|
| 0.05 | 83 | 0.70 | 0.77 |
| 0.10 | 77 | 0.75 | 0.77 |
| 0.20 | 75 | 0.77 | 0.77 |
| 0.30 | 67 | 0.85 | 0.76 |
| 0.50 | 63 | 0.90 | 0.76 |
| 0.70 | 58 | 0.93 | 0.72 |
| 0.90 | 52 | 0.96 | 0.67 |
Recall barely moves between 0.05 and 0.50, while precision climbs from 0.70 to 0.90. The model is confident about most frauds it catches, and the 18 it misses at 0.50 mostly score very low. Dropping the threshold to 0.05 catches one more fraud for 20 more alerts.
Thinking in alert budgets
Many fraud teams do not set a probability threshold at all. They have a fixed number of analysts and review the riskiest cases first. Here is what that looks like on the test period:
| Review the top… | Frauds found | Share of all 75 |
|---|---|---|
| 50 transactions | 49 | 65% |
| 100 transactions | 58 | 77% |
| 250 transactions | 62 | 83% |
| 500 transactions | 66 | 88% |
Reviewing 50 alerts finds 49 frauds. After that, returns fall off: the next 450 reviews find only 17 more. This table is often the most useful one to show a fraud operations manager, because it answers “what do we get for each extra analyst hour?”
Step 7: Save the model and score new transactions
Once you have a fraud detection model you trust, save it and load it wherever scoring happens:
import joblib
joblib.dump(model, "fraud_model.joblib")
loaded = joblib.load("fraud_model.joblib")
one = test_df[FEATURES].iloc[[0]]
print(f"Score for one transaction: {loaded.predict_proba(one)[0, 1]:.4f}")
Score for one transaction: 0.0000
The first transaction of the test period is legitimate and scores close to zero. In production you would wrap this in an API, log every score with the model version, and record the decision taken so you can audit it later.
What the model learned
LightGBM can report how much each feature reduced the loss (gain importance). On this fraud detection model one component dominates:
| Feature | Share of total gain |
|---|---|
| V14 | 84.3% |
| V4 | 2.1% |
| V17 | 1.8% |
| V10 | 1.8% |
| V12 | 1.0% |
| V25 | 0.6% |
V14 alone separates fraud from legit with a ROC-AUC of 0.949, the highest of any single column. Because the features are anonymised PCA components, we cannot say what V14 means in banking terms. In a real project you would have named features and could explain declined payments to customers and regulators.
Explaining a single fraud detection decision
Global importance tells you what the model relies on overall. Analysts and customers usually ask a narrower question: why was this payment flagged? LightGBM can answer it without extra libraries. Passing pred_contrib=True returns each feature’s contribution to the score, in log-odds, for one row. These are SHAP values computed by the tree model itself.
import joblib
import numpy as np
import pandas as pd
model = joblib.load("fraud_model.joblib")
fraud_row = test_df[test_df.Class == 1][FEATURES].iloc[[0]]
contrib = model.predict(fraud_row, pred_contrib=True)[0] # per-feature log-odds contributions + bias
parts = pd.Series(contrib[:-1], index=FEATURES).sort_values(key=np.abs, ascending=False)
print(f"Fraud probability: {model.predict_proba(fraud_row)[0, 1]:.3f}")
print(f"Baseline (bias) log-odds: {contrib[-1]:.2f}")
print(parts.head(5).round(2).to_string())
Output for the first fraud in the test period:
Fraud probability: 0.999
Baseline (bias) log-odds: -11.77
V14 8.32
V4 2.44
V10 1.76
V12 1.42
V7 1.10
The model starts from a very low baseline (fraud is rare) and five features push this transaction up until it scores 0.999. V14 alone adds 8.32 log-odds. With named features, this output becomes a reason code an analyst can read, such as “amount far above this card’s average” or “first purchase from a new device”. Storing the top contributions with every alert makes reviews faster and gives you an audit trail when a customer disputes a block.
Fraud detection beyond card payments
The same pipeline shape works for most fraud detection problems, although the features and labels change. A few common cases:
| Domain | What one row is | Where the label comes from | Typical delay |
|---|---|---|---|
| Card payments | one transaction | chargebacks, customer reports | days to weeks |
| Account takeover | one login or session | confirmed compromise, password resets | hours to days |
| Insurance claims | one claim | investigator findings | weeks to months |
| E-commerce returns | one order or return | return audits, repeat abuse | days |
| Promotion abuse | one sign-up | duplicate identity checks | days |
Two things carry over every time. First, the split must follow time, because the system always scores future events. Second, labels arrive late and incompletely, so the most recent weeks of data look cleaner than they really are. When you train a fraud detection model on data that ends yesterday, many of yesterday’s frauds are still labelled legitimate. A common fix is to leave a gap: train only on events old enough for their labels to have settled.
Insurance and claims fraud detection adds a twist. Labels come from investigations, and investigators only look at claims that something flagged. The labelled frauds are therefore biased toward whatever the old system already caught, which is the feedback loop described below in a stronger form.
Moving fraud detection to production
A notebook model is the start. A production fraud detection system needs more than the classifier.
Features that real systems use
The public dataset hides its raw features. With your own data, these feature families usually carry most of the signal:
| Feature family | Examples |
|---|---|
| Velocity | transactions per card in the last 1 hour, 24 hours, 7 days |
| Amount behaviour | amount compared with the card’s own average, first purchase above a limit |
| Novelty | new device, new merchant, new country for this customer |
| Merchant risk | merchant’s historical fraud rate (target-encoded with care) |
| Network | shared devices, emails or addresses across accounts |
Every one of these must be computed as of the transaction time. A velocity count that includes later transactions is a leak.
Rules and models together
Most teams keep rules alongside machine learning. Rules handle hard policy (blocked countries, sanctioned merchants) and brand-new attack patterns before enough labels exist. The model ranks everything else. A common pattern is: rules first, model score second, analyst review for the grey zone.
Monitoring
Track three things from the day your fraud detection model goes live:
- Input drift: are feature distributions moving away from training?
- Score drift: is the share of transactions above the threshold changing?
- Label-based performance: once chargebacks arrive, compare live precision and recall with your offline numbers.
Plan to retrain on a fixed schedule and whenever performance drops. Keep the time-based evaluation for every retrain.
Feedback loops
Transactions you block never get a true label, because the fraud never completes. Over time, your training data under-represents the patterns your model already catches. Some teams let a tiny random sample of medium-risk transactions through with extra checks, purely to keep labels honest. Whether that is acceptable depends on your risk appetite and regulators.
Which model should you use for fraud detection?
| Approach | Good for | Weak spots |
|---|---|---|
| Rules | policy, known patterns, day-one coverage | brittle, many false alarms, easy to learn around |
| Logistic regression | explainable baseline, fast scoring | misses non-linear patterns (0.709 to 0.757 PR-AUC here) |
| Gradient boosting (XGBoost, LightGBM, CatBoost) | tabular transaction data, best accuracy here | needs care with imbalance settings |
| Anomaly detection (Isolation Forest, autoencoders) | new fraud types with few labels | high false-alarm rate on its own |
| Graph models | fraud rings, shared devices and accounts | needs relationship data and more engineering |
For card transactions with labels, gradient boosting is the usual first choice. Our XGBoost vs LightGBM vs CatBoost benchmark runs all three on this same fraud data with three seeds. CatBoost scored highest there (0.878 PR-AUC when tuned) and was by far the slowest to train. For small tabular problems you may also want to try TabPFN, although its limits on rows and its licence make it a poor fit for full-scale transaction scoring.
Common fraud detection mistakes
- Reporting accuracy. Use PR-AUC, precision and recall.
- Splitting at random. Split by time.
- Oversampling before the split. Resample inside a pipeline, training data only.
- Choosing the threshold on the test set. Choose it on validation.
- Using features that only exist after the fact, such as a chargeback flag or an analyst decision.
- Weighting the minority class without regularising, which broke LightGBM in this test.
- Ignoring label delay. Recent transactions may look legitimate only because their chargebacks have not arrived yet.
FAQ
Which machine learning algorithm is best for fraud detection?
For labelled tabular transaction data, gradient boosted trees such as XGBoost, LightGBM and CatBoost usually perform best. In this tutorial XGBoost reached 0.805 PR-AUC on a time-based test, against 0.709 for logistic regression. Start with a logistic regression baseline and a boosted model, then compare them on PR-AUC.
Why is accuracy a bad metric for fraud detection?
Because fraud is rare. On this dataset only 0.17% of transactions are fraud, so a model that labels everything legitimate reaches 99.87% accuracy and catches nothing. PR-AUC, precision, recall and expected cost reflect what matters.
Should I use SMOTE for fraud detection?
You can, but try class weights first. On this data both lifted logistic regression by a similar amount (0.746 with balanced weights, 0.757 with SMOTE). If you use SMOTE, apply it inside an imbalanced-learn pipeline so it only sees training data.
How do I pick a threshold for fraud alerts?
Assign a cost to each review and to each missed fraud, then choose the threshold that minimises total cost on a validation period. If your team has a fixed number of analysts, rank transactions by score and review the top k instead.
Can I use unsupervised learning for fraud detection?
Yes, anomaly detection methods such as Isolation Forest can flag unusual events when you have few or no labels. On their own they tend to raise many false alarms, so most teams combine them with a supervised model once labels build up.
Build it, then question it
You now have a fraud detection pipeline that splits by time, compares models on PR-AUC, survives the LightGBM imbalance trap and picks its threshold with money in mind. The final model caught 57 of 75 frauds in the test period with 6 false alarms, and its top 50 alerts contained 49 real frauds.
The model itself was the easy part. Most of the gains came from evaluating honestly. If you are new to the field, the machine learning roadmap for 2026 shows where this kind of project fits in a learning plan.


