In transaction fraud detection, a payment can look ordinary on its own yet become suspicious when viewed alongside transactions linked by a user or device. Neural message passing lets a graph neural network update each transaction’s representation with information aggregated from its neighbors. This replaces some manually specified relationship features with learned representations. section 9.4 section 9.4.2
A simplified PyTorch workflow makes the exchange explicit:
- Create one node per transaction. Use amount and transaction-time components as node features; connect transactions that share a user ID or device ID, then row-normalize the adjacency matrix. section 9.4.2
- Transform node features with a linear layer and ReLU. Multiply the result by the adjacency matrix to aggregate neighboring features, then add the node’s own transformed features. Repeat with a second layer and classify each node as Normal or Fraud. section 9.4.2
- Train with fraud labels when available; otherwise run inference. Convert output scores to fraud probabilities and inspect the five highest-scoring transactions. section 9.4.2
Listing 9.7 Defining the GNN model
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
from scipy.sparse import csr_matrix
# Simple GNN Model
class FraudGNN(nn.Module):
def __init__(self, input_dim, hidden_dim=32):
super(FraudGNN, self).__init__()
self.conv1 = nn.Linear(input_dim, hidden_dim)
self.conv2 = nn.Linear(hidden_dim, hidden_dim)
self.classifier = nn.Linear(hidden_dim, 2) # Normal/Fraud
def forward(self, x, adj):
# First GNN layer: Aggregate neighbor information
h1 = torch.relu(self.conv1(x))
h1_agg = torch.mm(adj, h1) # Average neighbors' information
h1 = h1 + h1_agg
# Second GNN layer
h2 = torch.relu(self.conv2(h1))
h2_agg = torch.mm(adj, h2)
h2 = h2 + h2_agg
# Classification
out = self.classifier(h2)
return out
The model listing shows the central operation directly: adjacency-matrix multiplication gathers neighboring representations, and addition retains the node’s own transformed information. section 9.4.2
This is a conceptual bridge, not a complete large-scale fraud system. The graph builder can keep its adjacency matrix sparse, while the demonstration conditionally converts it for the PyTorch model. Larger, changing financial graphs call for more specialized graph tooling and techniques; temporal or dynamic GNNs address evolving relationships. section 9.4.2 section 9.4
