Creating a federated Convolutional Neural Network (CNN) model for credit card fraud detection involves these steps: preprocessing the dataset, building the CNN model, and defining a federated learning workflow using a framework like PySyft and PyTorch. Here's an outline of how it can be done:
- Import necessary libraries and frameworks.
import pandas as pd
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader
!pip install syft
import syft as sy
-
Load the Simulated Credit Card dataset and preprocess the data.
(Make sure to follow the preprocessing steps mentioned in the previous responses)
-
For CNN, you'll need to reshape your data to a (batch, channels, height, width) format. Normally, you would perform this step using 2D image data, but with tabular data, you have to get creative with the input shape.
class TabularDataset(Dataset):
def __init__(self, X, y):
self.X = X
self.y = y
def __len__(self):
return len(self.X)
def __getitem__(self, idx):
return self.X[idx], self.y[idx]
def create_data_loaders(X_train, X_test, y_train, y_test):
train_ds = TabularDataset(X_train, y_train)
test_ds = TabularDataset(X_test, y_test)
train_dl = DataLoader(train_ds, batch_size=64, shuffle=True)
test_dl = DataLoader(test_ds, batch_size=64, shuffle=True)
return train_dl, test_dl
- Define the CNN model.
class CNN(nn.Module):
def __init__(self):
super(CNN, self).__init__()
self.conv1 = nn.Conv2d(1, 32, 3, padding=1)
self.relu1 = nn.ReLU()
self.pool1 = nn.MaxPool2d(2)
self.conv2 = nn.Conv2d(32, 64, 3, padding=1)
self.relu2 = nn.ReLU()
self.pool2 = nn.MaxPool2d(2)
self.fc1 = nn.Linear(64, 32)
self.relu3 = nn.ReLU()
self.fc2 = nn.Linear(32, 2)
self.softmax = nn.LogSoftmax(dim=1)
def forward(self, x):
x = self.pool1(self.relu1(self.conv1(x)))
x = self.pool2(self.relu2(self.conv2(x)))
x = x.view(-1, 64)
x = self.relu3(self.fc1(x))
x = self.softmax(self.fc2(x))
return x
- Define a function for training and evaluation.
def train_epoch(data_loader, model, optimizer, device):
model.train()
running_loss = 0
for batch_idx, (X, y) in enumerate(data_loader):
X, y = X.to(device), y.to(device)
optimizer.zero_grad()
output = model(X.float())
loss = loss_function(output, y)
loss.backward()
optimizer.step()
running_loss += loss.item()
def evaluate_dataloader(data_loader, model, device):
model.eval()
total_correct = 0
with torch.no_grad():
for X, y in data_loader:
X, y = X.to(device), y.to(device)
output = model(X.float())
total_correct += output.argmax(dim=1).eq(y).sum().item()
return total_correct / len(data_loader.dataset)
- Define a function to run federated training using PySyft.
def federated_training_and_evaluation(model, X_train, X_test, y_train, y_test, num_rounds, num_devices):
hook = sy.TorchHook(torch)
devices = [sy.VirtualWorker(hook, id=str(i)) for i in range(num_devices)]
# Split the dataset and send to the virtual devices
X_train_parts = np.array_split(X_train, num_devices)
y_train_parts = np.array_split(y_train, num_devices)
for round in range(num_rounds):
round_accuracy = []
for device in devices:
data_idx = int(device.id)
X_train_device, y_train_device = X_train_parts[data_idx], y_train_parts[data_idx]
X_train_device = torch.Tensor(X_train_device)
y_train_device = torch.Tensor(y_train_device)
train_dl, test_dl = create_data_loaders(X_train_device, X_test, y_train_device, y_test)
device_model = model.copy().send(device)
optimizer = optim.SGD(device_model.parameters(), lr=0.001)
loss_function = nn.CrossEntropyLoss()
train_epoch(train_dl, device_model, optimizer, device)
device_model.send(devices[0])
local_model = device_model.copy().get()
accuracy = evaluate_dataloader(test_dl, local_model, device)
round_accuracy.append(accuracy)
device_model.owner._objects = {}
acc = sum(round_accuracy) / len(round_accuracy)
print(f"[Round {round + 1}] Average Accuracy: {acc:.4}")
- Perform federated training and evaluation on the dataset.
num_rounds = 5
num_devices = 5
model = CNN()
federated_training_and_evaluation(model, X_train, X_test, y_train, y_test, num_rounds, num_devices)
Please note that using a CNN for tabular data is not a common practice. This example demonstrates a federated learning approach with a CNN model, but for a real-world tabular dataset, other algorithms like logistic regression, ensemble methods or feed-forward neural networks might work better.