Fraud Detection Project Breakdown
An in-depth look at graph machine learning models, point-in-time feature engineering, streaming bandits, and GNN robustness against fraud camouflage.
Fraud detection has always been something that fascinated me, because of my interest in fintech and the payments sector especially. In this project, I decided to explore different types of graph machine learning models to see how they work and identify which ones are well suited for fraud detection.
This fraud detection system was intentionally split into two parts: Track A, which uses the PaySim dataset and utilizes feature engineering to transform the raw transaction data into a live decision loop. This track includes point-in-time features, a gradient-boosted classifier and a contextual multi-arm bandit that chooses between approving, challenging, reviewing or declining each transaction that comes through. Track B uses the YelpChi and Amazon datasets and answers another question: when fraud rings try to make transactions through camouflage or otherwise, which graph neural network still finds them?
The key takeaways that I got through this project are as follows:
- A plain graph convolution network will fail against fraud, as seen when the results collapsed to near random in Track B, because most of the relations were camouflaged.
- GraphSAGE’s performance won GAT (graph attention networks) and matched a simplified version of CARE-GNN (camouflage resistant graph neural networks) which was unexpected, and this breakdown will dive into the reasons below.
- In Track A, a cost-tuned GBDT threshold reached 99.5% of the oracle reward and beat the multi-arm bandit, which only came close to the GBDT in terms of performance when it learned per-dollar rates and used the GBDT score as context.
In general, fraud detection is more complex than just classification because of a few reasons:
- Extreme imbalance: Fraud usually only holds a tiny share of all transactions, and so mere accuracy does not reveal anything. Evaluations need to rely on AUC, PR-AUC, F1 of G-Mean instead, and the models use class weights.
- Camouflage: Fraudsters intentionally connect to legitimate accounts/transactions to try and blend in. A model that averages over all neighboring nodes equally gets diluted by noise.
- Labels arriving late: A chargeback/dispute outcome only arrives days after the transaction has been made. To model this, labels are produced later than transactions, and the reward join waits for them, with a timeout that assumes the transaction is legitimate if no label arrives.
- Decision making after getting the fraud detection score: A fraud probability score does not say whether to approve, ask for a second factor, send for manual review or to decline. Each action has a different cost, which is why Track A adds a cost model and a bandit on top of the classifier.
Now, I’ll be diving into the features that I included in Track A. This dataset includes over 2.7 million transactions.
Data and Graph EDA
The fraudulent transactions of this dataset only appear in the categories “TRANSFER” and “CASH_OUT”, and so I needed to filter the dataset to those two categories. I then built an account graph, with accounts as nodes and transactions as edges, choosing to use plain integer arrays over networks due to the size of the dataset which would affect the speed of computation. This EDA measures degree distributions of the nodes, connected components and whether the destination of fraudulent transfers ever originates a cash-out (a common mule pattern). It also checks how sparse my graph is, which allows me to see if the different graph methods have anything to work with on this dataset.
Point-in-time features
Every feature for a transaction only uses transactions strictly before it, which matches what a live system in the real world knows. The features cover rolling counts and amounts per origin and per destination over 1-hour, 24-hour and 168-hour windows, flags for a new origin-destination pair and a new destination, the amount and its log, a drain ratio (current amount vs old balance), the hour of day and transaction type. I deliberately excluded the post-transaction balances, because in this PaySim dataset they leak the label: a fully drained origin account would show a zero new balance.
Temporal split
Train, validation and test are split into 60/20/20 by simulation step, and never random as random splits would allow the model to see the future.
Baseline
Lastly, a LightGBM classifier with 300 trees and balanced class weights are trained on the train split. The feature scaler is also fit on train only and saved, so that the bandit evaluation and scoring service use one frozen scaler instead of recomputing statistics on whatever batch they use.
Decision choices, rewards and the bandit: Track A
On top of the baseline classifier, a contextual bandit picks one of four actions per transaction: approve, challenge (a second factor), manual review and decline. To learn from outcomes, the bandit needs a reward for every action that it decides to take. Since PaySim did not have any real costs, I added some assumptions of my own as seen below:

The policies are judged through the harness, which compares everything on the held-out test period against an oracle which always picks the best option in hindsight. The competitors are a GDBT score with cost-tuned thresholds (tuned on validation only), always approve, always review and the other fixed actions, random, epsilon-greedy and LinUCB in several variants. Learners only see the reward of the action they took, which is real bandit feedback, while the oracle and threshold tuning use full information.
Variants worth knowing about in this project
- Normalized rewards: the learner predicts the per-dollar rate each action earns and decides with amount x (rate plus bonus) - known fixed cost. This bakes in the fact that rewards scale with the transaction amount.
- GDBT score as context: the classifier’s logit is added to the bandit’s features, so the bandit becomes a policy layer on top of the classifier.
- Safety floor: very large amounts can be forced to review but is turned off by default because with it on roughly 40% of rows were forced to review and the comparison ended up measuring the floor instead of the policies.
- Drift and delay: a synthetic drift option either degrades the GDBT score (a stale model) or lets fraudsters adapt to challenges, and a delay option hides each reward for N rows, and the threshold is deliberately not returned after drift.
Track A Streaming
The streaming layer replays PaySim through Kafka and runs the winning offline policy, with labels arriving late the way real chargebacks do.

A transaction flows left to right and is scored on arrival. Its reward comes back later through the join and the reward consumer into Redis, which the scoring container periodically reloads.
Each stage is its own service, and is elaborated on below:
- Replay producer: Sends transactions in step order at a configurable speedup (3600x means one simulated hour per real second). The payload leaves out the fraud label, because a live system does not know it at decision time. Every record carries a txn_id, the original CSV row number, and one shared function chooses the rows for both the transaction and label producers so the two always match.
- Feature service: One ordered process with one global state, calling the same point-in-time features class as the offline builder. It cannot be keyed by origin account the way a Flink job usually would be, because the destination-side counts and the new-pair and new-destination flags depend on state keyed by destination and by pair. That also means a single-partition topic.
- Scoring service: Builds the context vector from the log-scaled features and the GDBT logit and lets the normalized LinUCB pick an action before republishing the record with the action, the fraud probability as an audit reason code, and the exact context used.
- Label producer: Emits labels later than the transactions (6 simulated hours by default, with a separate day available for fraud).
- Delayed feedback join: Keyed by txn_id, it holds each scored transaction until its label arrives, then emits a reward record. If no label comes within a timeout (168 steps, 7 simulated days), the transaction is treated as legitimate and flagged as such. A label that arrives before its transaction is buffered instead of dropped.
- Reward consumer: Ignores duplicate txn_ids, so reprocessing after a restart cannot double-count, and applies each update to the bandit state in Redis with WATCH/MULTI optimistic locking, so several consumers cannot overwrite each other. The learning target is the per-dollar rate, matching the offline normalized model.
Live run
I started the Docker stack (Kafka, Zookeeper, Redis, Flink), created the five topics, ran the features, scoring and reward services, submitted the PyFlink join, and replayed the first 30,000 PaySim rows at 3600x through both producers. When I checked, Redis held 18,646 distinct transaction ids in the reward consumer’s dedupe set, the bandit state key existed, and the bandit-rewards topic contained reward records written by the Flink job, each with the action taken, the amount, the reward, the true label and the exact context vector. The first record shows the loop working in miniature: the policy approved a 181-dollar transaction that turned out to be fraud, so the reward was -181 and the bandit learned from it. The 168-step timeout path was not reached, because the replay covered only a few simulated hours, so that branch is covered by the unit tests only.

Track B
Track B tests whether graph neural networks can see through fraudsters who hide amongst honest users, using the YelpChi and Amazon review-fraud graphs. Both are multiplex graphs: one set of nodes connected by several relation types. There are 3 types of relations: R-U-R, R-T-R, and R-S-R. They stand for Review-User-Review (two different reviews posted by the same user), Review-Time-Review (two different reviews for the same product within the same month), and Review-Star-Review (same product that shares the same star rating).
For each relation, I computed label homophily, which checks the share of edges that connect two nodes with the same label, once over all edges and another time over only outgoing edges from fraud nodes. A fraud-side figure that sits well below the overall figure is camouflaged as fraud nodes are deliberately well connected to benign ones under it.
Next, I used a histogram gradient-boosted classifier on the provided features, and the node’s degree and the mean of its neighbors’ features for each relation as my baseline. This is what one untrained mean aggregation layer would compute, and acts as the baseline that every subsequent model must beat.
Models used
- Graph Convolutional Network (GCN): Used as my naive baseline, which averages over every neighbor of every relation equally.
- GraphSAGE: Used a mean aggregation convolution per relation, concatenated with a projection of the node’s own features.
- Graph Attention Networks (GAT): Used next, with 4 attention heads per relation, so attention can down-weight bad neighbors in principle.
- CARE-GNN (simplified): A simplified version of Camouflage-Resistant graph neural networks (CARE-GNN), where a similarity network embeds the nodes and each node only keeps the top 50% most similar incoming edges per relation for its mean aggregation. The similarity network is trained with an auxiliary loss that predicts whether two training nodes share a label. The original reinforcement learning threshold controller and its label-based neighbor under-sampling were intentionally removed for simplification.
For training and metrics, I used a stratified 40/20/40 train, validation and test splits. The models were trained over 100 epochs, with class-weighted cross-entropy and Adam at 0.01 with weight decay. AUC, F1 and G-Mean (geometric mean of fraud recall and legitimate recall) were used, because accuracy alone is meaningless with this level of imbalance found in the dataset.
Aggregate AUC can hide details, so two extra experiments were used. A per relation ablation trains each of these models on each camouflaged relation alone, on the camouflaged relations together, on clean relations only as well as on everything. A homophily-bucketed recall then splits the fraud test nodes into thirds by their local camouflaged-relation homophily and reports recall per third, which shows whether a model wins on the hard, well-camouflaged nodes or only uniformly.
Results

GCN collapsed as expected, with GraphSAGE leading narrowly and CARE-GNN surprisingly not beating it. The homophily diagnostic found two of the three relations, R-S-R and R-T-R to be heavily camouflaged. Fraud-node homophily was 0.18, compared to 0.77 overall.

From the tables above, GAT is the most camouflage-sensitive, being 10 points behind GraphSAGE on well-camouflaged nodes, which shows that attention did not learn to down-weight the camouflaged relations in this case.
On the hardest bucket GraphSAGE is ahead of CARE-GNN, but leads the other two buckets slightly.

For Track A, every policy is scored as a percentage against the oracle’s total reward on the held-out test period. The raw reward bandit lost mostly by over-reviewing legitimate transactions. Learning per-dollar rates fixed much of that, and adding the classifier’s score closed most of the gap between the cost-tuned GBDT. Without the score, the same learner only managed 76% of the oracle’s reward, which shows that the 96.8% is mostly the classifier’s work, with the bandit acting as a policy layer on top of it. The PaySim dataset is highly separable and fully labelled, which could explain why a supervised classifier is close to optimal in this context.
Insights and takeaways
The most useful lesson that I took away from this project was that a strong, well-specified baseline sets the bar, and extra features must earn its place. The best solutions are not always the most complex ones, but rather are the ones that fit the use case the best. Besides that, there are a few other points that I would like to mention:
- Diagnosing the failure before choosing a model: The homophily diagnostic check told me which relations were camouflaged and correctly predicted the collapse of GCN before I even trained anything. Knowing which contexts would cause a model to fail is critical and is what made the ablation interpretable.
- Complexity only helps when it matches the failure: CARE-GNN was built for camouflage, but did not perform significantly better than a GraphSAGE model. Giving each relation its own aggregator was enough, and the extra filtering did not add much performance boost for this setup.
- Aggregates can hide areas where a model wins: The bucketed recall showed GAT’s weakness on well-camouflaged nodes, which the overall AUC alone would have blurred. However, it also has its own limitations. Using recall at a fixed threshold rewards a model that predicts more positives, so a threshold-free metric per bucket would be a better next step for improvement.
Limitations and future implementations
- Single seed: All the results from Track B were only taken from a single test run, and so the ranking of GraphSAGE, CARE-GNN and GAT is not reliable.
- Undertrained models: Both GraphSAGE and CARE-GNN were still improving at the 100 epoch cap, and so the results are not fully representative of their performance.
- Simplified version of CARE-GNN: A simplified version was used, which would no doubt have affected its performance against GraphSAGE.
- The Track A cost constants are assumptions, and are not calibrated to a real portfolio.