This tutorial shows how to simulate a fraud detection system that preserves privacy without the need for complex frameworks and infrastructure. In this tutorial, we demonstrate how to build a CPU-friendly, clean setup that simulates 10 independent banks. Each bank trains a fraud detection model locally on their own, highly unbalanced transactions. Through a FedAvg aggregated loop, we coordinate local updates to the global model. We ensure that raw transactional data never leaves our clients. OpenAI is integrated to provide post-training reporting and analysis, which shows how the federated outputs of learning can be turned into actionable insights. Visit the Full Codes here.
Openai with scikit-learn and torch
import time, random, json, os, getpass
Numpy can be imported as a np
Import torch
Buy torch.nn in nn
TensorDataset, DataLoader or torch.utils.data can be imported from this file
Import make_classification from sklearn.datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import roc_auc_score, average_precision_score, accuracy_score
OpenAI can be imported from OpenAI
SEED = 7.
random.seed(SEED); np.random.seed(SEED); torch.manual_seed(SEED)
DEVICE is the same as torch.device ("cpu")
print("Device:", DEVICE)
The execution environment is set up and all libraries are imported for the data generation, model, evaluation and reporting. Fixing random seeds, device configurations and other issues will ensure that our federated simulator remains reproducible. Visit the Full Codes here.
X, y = make_classification(
n_samples=60000,
n_features=30,
n_informative=18,
n_redundant=8,
weights=[0.985, 0.015],
class_sep=1.5,
flip_y=0.01,
random_state=SEED
)
X = astype(np.float32).
If y is a type, then y.astype (np.int64).
X_train_full, X_test, y_train_full, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=SEED
)
server_scaler = StandardScaler()
X_train_full_s = server_scaler.fit_transform(X_train_full).astype(np.float32)
X_test_s = server_scaler.transform(X_test).astype(np.float32)
test_loader = DataLoader(
TensorDataset(torch.from_numpy(X_test_s), torch.from_numpy(y_test)),
batch_size=1024,
shuffle=False
)
We generate a highly imbalanced, credit-card-like fraud dataset & split it into training & test sets. Standardizing the data on the server and preparing a test loader allows us to evaluate the aggregated models after every federated round. Visit the Full Codes here.
def dirichlet_partition(y, n_clients=10, alpha=0.35):
classes = np.unique(y)
idx_by_class = [np.where(y == c)[0] "for c" in classes]
client_idxs = [[] [for _ in the range(n_clients]]
For idxs, see idx_by_class
np.random.shuffle(idxs)
props = np.random.dirichlet(alpha * np.ones(n_clients))
cuts = (np.cumsum(props) * len(idxs)).astype(int)
prev = 0
Cut cid in the enumerate (cuts).
client_idxs[cid].extend(idxs[prev:cut].tolist())
prev = cut
Return to the Homepage [np.array(ci, dtype=np.int64) for ci in client_idxs]
NUM_CLIENTS = 10
client_idxs = dirichlet_partition(y_train_full, NUM_CLIENTS, 0.35)
Make_client_split (X, y and idxs).
Xi = yi[idxs]The 'y'[idxs]
if len(np.unique(yi))
By using Dirichlet Distribution, we partition the data for training across 10 clients to simulate realistic non IID behavior. Then, we create client-level loaders that are independent of each other to ensure that the simulated banks operate on their own local scaled data. Visit the Full Codes here.
class FraudNet(nn.Module):
def __init__(self, in_dim):
Supermarkets are a great way to buy goods and services.().__init__()
self.net = nn.Sequential(
nn.Linear(in_dim, 64),
nn.ReLU(),
nn.Dropout(0.1),
nn.Linear(64, 32),
nn.ReLU(),
nn.Dropout(0.1),
nn.Linear(32, 1)
)
def forward(self, x):
Return to the Homepage self.net(x).squeeze(-1)
def get_weights(model):
return [p.detach().cpu().numpy() for p in model.state_dict().values()]
Def Set_Weights(Model, Weights)
keys = list(model.state_dict().keys())
model.load_state_dict({k: torch.tensor(w) for k, w in zip(keys, weights)}, strict=True)
@torch.no_grad()
Def evaluate (model and loader)
model.eval()
BCEWithLogitsLoss()
ys, ps, losses = [], [], []
Loader for xb and yb:
Logits = Model(xb).Return
losses.append(bce(logits, yb.float()).item())
ys.append(yb.numpy())
ps.append(torch.sigmoid(logits).numpy())
y_true = np.concatenate(ys)
y_prob = np.concatenate(ps)
return {
"loss": float(np.mean(losses)),
"auc": roc_auc_score(y_true, y_prob),
"ap": average_precision_score(y_true, y_prob),
"acc": accuracy_score(y_true, (y_prob >= 0.5).astype(int))
}
Def Train_Local (model, Loader and Lr)
opt = torch.optim.Adam(model.parameters(), lr=lr)
BCEWithLogitsLoss()
model.train()
Loader for xb and yb:
opt.zero_grad()
loss = bce(model(xb), yb.float())
loss.backward()
opt.step()
We provide utility functions to train, evaluate, and exchange weights. Our lightweight optimizations are based on metric calculation and local optimization to make client-side update efficient. Visit the Full Codes here.
Weights and sizes:
total = sum(sizes)
Return to the Homepage [
sum(w[i] * (s / total) for w, s in zip(weights, sizes))
for i in range(len(weights[0]))
]
ROUNDS = 10
LR = 5e-4
global_model = FraudNet(X_train_full.shape[1])
global_weights = get_weights(global_model)
For r within range (1, ROUNDS + 1)
client_weights, client_sizes = [], []
For cid within range (NUM_CLIENTS), you can use:
local = FraudNet(X_train_full.shape[1])
set_weights(local, global_weights)
train_local(local, client_loaders[cid][0], LR)
client_weights.append(get_weights(local))
client_sizes.append(len(client_loaders[cid][0].dataset))
global_weights = fedavg(client_weights, client_sizes)
set_weights(global_model, global_weights)
metrics = evaluate(global_model, test_loader)
print(f"Round {r}: {metrics}")
FedAvg allows us to orchestrate a federated learning system by training client local models iteratively and then aggregating the parameters. After each iteration, we evaluate the global model to understand convergence and how collective learning can improve fraud detection. Click here to view the Full Codes here.
OPENAI_API_KEY = getpass.getpass("Enter OPENAI_API_KEY (input hidden): ").strip()
OPENAI_API_KEY
os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY
OpenAI clientSummary =()
summary = {
"rounds": ROUNDS,
"num_clients": NUM_CLIENTS,
"final_metrics": metrics,
"client_sizes": [len(client_loaders[c][0]".dataset" for client c within range (NUM_CLIENTS).
"client_fraud_rates": [float(client_data[c][1].mean()() for c within range(NUM_CLIENTS).
}
prompt = (
"Write a concise internal fraud-risk report.n"
"Include executive summary, metric interpretation, risks, and next steps.nn"
+ json.dumps(summary, indent=2)
)
resp = client.responses.create(model="gpt-5.2", input=prompt)
print(resp.output_text)
Our team transforms the technical report into a succinct analytical report by using an external language. The API key is securely accepted via keyboard and we generate insights for decision making that summarise performance, risk, and recommend next steps.
We concluded by showing how to achieve federated learning in Colab while being stable, interpretable and realistic. In fraud detection settings, we observed that extreme heterogeneity in data across clients can influence convergence. We also noted the importance of careful evaluation and aggregation. In addition, we extended the workflow to generate an automated risk-team document that demonstrates how analytics can translate into insights for decision making. Finally, we provided a concrete blueprint to experiment with fraud models federated that puts privacy, simplicity, real-world relevance, and ease of use at the forefront.
Take a look at the Full Codes here. Also, feel free to follow us on Twitter Join our Facebook group! 100k+ ML SubReddit Subscribe now our Newsletter. Wait! Are you using Telegram? now you can join us on telegram as well.
Asif Razzaq, CEO of Marktechpost Media Inc. is a visionary engineer and entrepreneur who is dedicated to harnessing Artificial Intelligence’s potential for the social good. Marktechpost was his most recent venture. This platform, which specializes in covering machine learning and deep-learning news, is both technically solid and understandable to a broad audience. This platform has over 2,000,000 monthly views which shows its popularity.

