Forge
Skip to main content

Machine learning for fraud detection in banking

Machine learning for fraud detection in banking
Last updated: October 27, 2026
Machine learning fraud detection systems assess transactions, accounts, logins, and applications by comparing current activity with learned patterns across customer behavior, identity data, devices, merchants, and payment history. Unlike static rules that react to predefined conditions, models can combine several weak signals into a single risk score.
This tutorial explains how to design that scoring process for banking environments. It covers model selection, fraud data, feature engineering, threshold setting, experiment tracking, real-time deployment, and operational controls. The focus is on practical trade-offs, including detection performance, latency, customer friction, review capacity, explainability, and governance, rather than presenting a general survey of fraud algorithms.
Image by author

Table of contents



Introduction

A fraud model does not make a complete decision on its own. It produces a score that estimates the risk of an event, then a wider decision system applies thresholds, policy rules, review capacity, and customer-impact controls. The same score can lead to different actions depending on the use case. A card payment might trigger step-up authentication, while a high-value wire transfer could be held for analyst review.
This distinction shapes the rest of the system. Model quality depends on whether features were available at decision time, whether labels are reliable, and whether the threshold reflects the cost of missed fraud and legitimate declines. Production design also has to account for latency, monitoring, rollback, audit trails, and human overrides. The sections that follow examine those constraints through a concrete fraud-modeling workflow, with the model treated as one component of a broader decision system.

What fraud detection with machine learning and AI is

Machine learning fraud detection assigns a probability or risk score to an event such as a card payment, ACH transfer, login, application, or account change. The score estimates how closely the event matches patterns associated with confirmed fraud, unusual behavior, or known attack methods.
Rules-based systems work differently. A rule checks for a specific condition, such as a blocked country, a known compromised card, or a transaction above a defined velocity limit. Machine learning models evaluate many signals at once and can detect interactions that would be difficult to maintain as separate rules. Rules still remain necessary for sanctions controls, regulatory requirements, hard policy limits, and deterministic blocks.
Image by author

The difficulty with financial fraud data

Financial fraud data is difficult because the target class is rare and the evidence often arrives late. A model can achieve very high accuracy by predicting most transactions as legitimate while still missing the cases that cause the largest losses. Metrics such as precision, recall, and precision-recall AUC are more useful because they show how the model performs on the small fraud population.
Labels are also incomplete and noisy. Chargebacks, customer disputes, analyst investigations, and law enforcement outcomes can take days or weeks to confirm. Some legitimate transactions are disputed, while some fraud is never reported. This delay complicates training, validation, and retraining.
Fraud patterns do not remain stable. Attackers adjust after controls change, move to new payment channels, and use generative AI for phishing, deepfake impersonation, and synthetic identity schemes. Historical patterns can therefore lose value quickly.
Training data should only include information available when the transaction was checked. Using later details, such as chargebacks or analyst notes, causes data leakage.
Privacy rules, data minimization, and limits on sharing data between banks also reduce available features and make evaluation less complete.

Modeling approaches: Supervised, unsupervised, semi-supervised, and graph learning

Supervised learning is the usual starting point when confirmed fraud labels are available. Logistic regression provides an interpretable baseline, while gradient-boosted trees and random forests can capture nonlinear relationships between features. Neural networks may help when teams have large datasets or complex behavioral sequences. Whatever the model family, probability calibration matters because the output must support threshold and cost decisions.
Unsupervised methods are useful when fraud labels are limited or when teams need to detect new attack patterns. Isolation forests, autoencoders, clustering, and density-based methods identify events that differ from normal behavior. These methods can surface suspicious activity, but unusual does not always mean fraudulent, so their outputs often require review or additional checks.
Semi-supervised learning uses a small labeled dataset together with a much larger unlabeled dataset. Positive-unlabeled learning is a related setup where confirmed fraud cases are known, but the remaining transactions contain both legitimate and undiscovered fraud.
Graph methods become valuable when relationships carry more information than individual events. Shared devices, IP addresses, addresses, merchants, or beneficiaries can reveal mule accounts and coordinated fraud rings.
A practical approach is to begin with an interpretable supervised baseline. Add anomaly signals when attacks are new, or labels are sparse, and add graph features when fraud depends on networks of connected accounts or entities.
Image by author

Data and feature engineering for fraud detection in banking

Fraud models are only as useful as the features available at decision time. Core inputs include transaction amount, merchant category, payment channel, geography, device fingerprint, IP address, login history, account age, KYC data, recent transaction counts, and past disputes.
Behavioral features add context by comparing the current event with the customer’s normal activity. A payment becomes more suspicious when it differs from usual spending amounts, locations, merchants, beneficiaries, devices, or session behavior.
Teams also build aggregations across entities such as customers, cards, accounts, merchants, devices, emails, phone numbers, addresses, and counterparties. These features are calculated over different windows, from a few minutes to several months. Examples include transactions per device in ten minutes or new beneficiaries added in one day.
Real-time fraud models need recent data, fast feature lookups, and reliable fallback values when information is delayed or missing. Teams must also check whether features such as geography, account type, or customer segment create unfair differences in how groups are approved, reviewed, or declined.

Worked example: Build a transaction fraud model

This walkthrough uses the Kaggle Credit Card Fraud Detection dataset, which contains 284,807 transactions and 492 confirmed fraud cases. Features V1 to V28 are anonymized PCA components, while Time and Amount remain interpretable. The dataset is therefore useful for demonstrating class imbalance, model training, probability scoring, and threshold selection.

The transactions were sorted by Time. The earliest 80 percent formed the training set, and the latest 20 percent formed the test set. This chronological split better represents a model trained on past activity and evaluated on later transactions. Time and Amount were standardized, while the existing PCA features were kept unchanged.


LOAD and validate transaction data SORT transactions BY time SPLIT earliest 80% for training SPLIT latest 20% for testing FOR EACH model: APPLY class weighting FIT model GENERATE fraud probabilities CALCULATE PR AUC EVALUATE top 1% review capacity SWEEP thresholds LOG metrics, charts, tables, and model artifact TO W&B
Two baselines were compared: logistic regression and gradient boosting. Both produced probabilities rather than fixed class labels. Transactions were ranked by predicted fraud risk, and the highest-scoring 1 percent were sent to the simulated manual review queue.
W&B makes the experiment traceable rather than leaving the results scattered across notebook cells. Each run stores the model settings, time-based split, class-weighting method, PR AUC, ROC AUC, recall, precision at the 1 percent review rate, and selected thresholds. This makes it easy to compare logistic regression with gradient boosting and identify which model offers the better operational trade-off.
Weave adds another layer of visibility by tracing the experiment function itself. It records the model inputs, parameters, and returned metrics in one place, which helps connect the code that produced a result with the result shown in W&B. In the gradient-boosting run, W&B recorded a PR AUC of 0.766, a recall of about 86.7 percent at the 1 percent review capacity, and a precision of about 11.4 percent. Logistic regression produced nearly identical recall and precision, with a slightly lower PR AUC of 0.761.
Image by author
Image by author
The W&B charts make threshold selection easier to explain. The precision-recall curve compares overall model behavior, while the threshold plots show how recall falls and precision rises as the cutoff becomes stricter. The confusion matrix then shows the customer and fraud consequences of the chosen threshold.

2 selected runs

The code used to create the charts:
threshold_table = wandb.Table(dataframe=sweep)

run.log({
"threshold_precision": wandb.plot.line(
threshold_table, "threshold", "precision",
title="Precision by threshold"
),
"threshold_recall": wandb.plot.line(
threshold_table, "threshold", "recall",
title="Recall by threshold"
),
})
W&B also stores the trained pipeline and dataset metadata as versioned artifacts. This links every result to the exact model and data configuration that produced it, which supports reproducibility, review, and later rollback. In production, the same tracking pattern remains useful, although point-in-time feature pipelines and delayed-label backfills would replace the static dataset.

Evaluation: Optimize for losses, not accuracy

Fraud models should be evaluated as decision systems, not by accuracy alone. In a highly imbalanced dataset, a model can classify nearly every transaction as legitimate and still report excellent accuracy. PR AUC is more useful because it measures the balance between finding fraud and limiting false alerts across thresholds.
Operational metrics matter as well. Recall at review capacity shows how much fraud the team can catch within a fixed investigation limit, while precision at top-k shows how many of the highest-risk cases are actually fraudulent. Calibration checks whether predicted fraud probabilities match observed fraud rates. Reliable probabilities help teams choose thresholds based on expected fraud loss, review cost, and customer friction.
The confusion matrix translates model errors into business outcomes. False positives interrupt legitimate customers. False negatives allow fraud losses. True positives prevent losses, while true negatives preserve frictionless service.
These outcomes do not carry the same cost. Missing a fraudulent card payment, wire transfer, account takeover, or synthetic identity case can lead to very different financial and operational losses. Manual review also uses analyst time, so threshold selection should balance expected fraud loss, customer friction, and review cost rather than optimize a single metric.

Offline results can still differ from production because labels arrive late, fraud patterns change, policies are updated, and blocked transactions create selection bias. W&B Tables and Reports can expose these gaps through slice analysis across channel, geography, merchant category, customer segment, model version, and time window.



Real-time serving architecture for banking fraud decisions

A production fraud system follows a decision path that begins when an event enters the bank’s platform. The system identifies the customer and related entities, retrieves fresh features, generates a model score, applies policy rules, compares the score with decision thresholds, and selects an action. The final decision and its inputs are logged so analysts can review outcomes and feed confirmed cases back into the system.
Possible actions include approving the event, declining it, holding it for review, requesting step-up authentication, reducing limits, notifying the customer, or monitoring the account after the event.
Latency requirements depend on the use case. Card authorizations and login checks often need fast responses, while wire transfers, loan applications, and batch AML reviews can allow more time for external lookups or deeper analysis. Not every fraud workflow requires sub-100 millisecond scoring.
Deployment controls are as important as the model. Teams need a model registry, fresh feature storage or streaming aggregates, shadow scoring, canary releases, rollback, audit logs, and monitoring for data and prediction drift.
Most tabular fraud models can train and serve efficiently on CPUs. GPUs are more useful for deep graph models or large batch-training workloads where their extra compute materially improves throughput.
Image by author

Trade-offs: Accuracy vs latency, cost vs throughput, and flexibility vs determinism

Fraud detection is not a search for the most complex model. Richer graph analysis, model ensembles, and external data checks can improve detection, but they may be too slow for card authorizations or login decisions that require an immediate response.
Cost creates another constraint. Fresh streaming features, real-time scoring, frequent retraining, and analyst review improve coverage, but they require more compute and operational capacity. A cheaper system may process more transactions while missing coordinated or fast-changing attacks.
Machine learning is flexible because it can detect subtle patterns and adapt to new behavior. Rules are deterministic, easier to audit, and simpler to test. Most production systems need both: models for probabilistic risk scoring and rules for hard policies and known threats. Thresholds then create a direct trade-off between fraud loss and customer friction. Lower thresholds catch more fraud but also flag more legitimate activity, while higher thresholds reduce customer friction but may allow more fraud to pass.
Before choosing model complexity, teams should define the use case’s latency limit, potential loss, explainability requirement, and available review capacity.

Governance, explainability, and regulatory compliance

In banking, a fraud model must be defensible as well as predictive. Financial institutions need audit trails that record the input data, model version, threshold, policy rules, final decision, analyst override, and later outcome. These records allow teams to reconstruct why a transaction was approved, reviewed, or declined.
Explanations should match the audience. Analysts may need reason codes or feature-level evidence, while customers need a simpler explanation of the decision. Monotonic constraints can keep selected model relationships predictable, and surrogate models can summarize complex behavior. These methods show what influenced a prediction, not what caused the fraud.
Governance also covers privacy, data retention, fair lending risk, AML monitoring, adverse action requirements where applicable, and model risk management. Operational controls should include approval gates, independent validation, periodic review, challenger models, access control, incident response, and rollback procedures.
W&B supports this workflow by preserving model lineage. Artifacts can store versioned datasets and model files, the Registry can identify approved versions, and Reports can organize validation evidence for regular review by engineering, compliance, and risk teams. Together, these records connect a production decision to the experiment, data, model, and threshold that produced it.

When not to use machine learning for fraud detection

Machine learning is not appropriate when there are too few events, labels are unreliable, no feedback loop exists, or the institution cannot act on model scores. Rules are often safer for sanctioned entities, blocked countries, known compromised cards, regulatory prohibitions, and simple velocity limits with clear thresholds.
ML should also be avoided when false positives could cause serious harm, and the team cannot provide explanations, appeals, monitoring, or rapid rollback. Generative AI should not invent fraud labels or make customer decisions without controls. Synthetic data can support testing, but it cannot replace ground truth.
A safer rollout starts with rules, then adds shadow scoring. Automated actions should be introduced gradually only after labels, monitoring, and governance processes are reliable.
Image by author

Designing fraud systems that survive contact with production

A fraud system survives production when its decisions remain reliable under changing data, delayed labels, operational limits, and customer impact. Point-in-time features, calibrated probabilities, cost-aware thresholds, monitoring, and governance usually matter more than model complexity.
The strongest design is often hybrid. Rules enforce deterministic controls, supervised models detect known fraud patterns, anomaly methods surface emerging behavior, and analysts review uncertain cases.
Start with an interpretable baseline. Measure precision-recall and cost curves, log the data, model, metrics, and threshold, then run the model in shadow mode. Enforce customer-facing decisions only after model performance has been validated, rollback and review procedures have been tested.

Conclusion

Fraud detection should be judged by the decisions it improves, not by model scores alone. A useful system catches meaningful risk without creating unnecessary friction for legitimate customers or overwhelming analysts with alerts. The next step is to treat every deployment as an ongoing operating process: review outcomes, update thresholds, investigate failures, and refine the system as fraud patterns and business conditions change.