Fashion MNIST IID and Balanced Dataset

Fashion MNIST IID and Balanced DatasetΒΆ

import torch
import torchvision

import numpy as np
import math
mnist_trainset = torchvision.datasets.FashionMNIST(root='./data', train=True, download=True, transform=torchvision.transforms.Compose([
                               torchvision.transforms.ToTensor(),
                               torchvision.transforms.Normalize(
                                 (0.5,), (0.5,))
                             ]))
mnist_testset = torchvision.datasets.FashionMNIST(root='./data', train=False, download=True, transform=torchvision.transforms.Compose([
                               torchvision.transforms.ToTensor(),
                               torchvision.transforms.Normalize(
                                 (0.5,), (0.5,))
                             ]))
## Parameters:
n_epochs = 3
batch_size_train = 10000
batch_size_test = 500
log_interval = 500
train_loader = torch.utils.data.DataLoader(mnist_trainset,batch_size=batch_size_train, shuffle=True)
test_loader = torch.utils.data.DataLoader(mnist_testset,batch_size=batch_size_test, shuffle=False)
import papayaclient
class TheModel(torch.nn.Module):

    def __init__(self):
        super(TheModel, self).__init__()

        self.linear1 = torch.nn.Linear(784, 400)
        self.linear2 = torch.nn.Linear(400, 10)
        self.relu = torch.nn.ReLU()

    def forward(self, x):
        x1 = x.flatten(start_dim = 1)
        return self.linear2(self.relu(self.linear1(x1)))
clients = []
for batchno, (ex_data, ex_labels) in enumerate(train_loader):
    clients.append(papayaclient.PapayaClient(dat = ex_data,
                                            labs = ex_labels,
                                            batch_sz = 500,
                                            num_partners = 5,
                                            model_class = TheModel,
                                            loss_fn = torch.nn.CrossEntropyLoss))
## Train the Nodes
num_epochs_total = 100
num_epochs_per_swap = 5
num_times = (num_epochs_total // num_epochs_per_swap)
for i in range(0, num_times):
    for n in clients:
        for j in range(0, num_epochs_per_swap):
            n.model_train_epoch()
    if i > 1 and i < num_times - 1 :
        for n in clients:
            n.select_partners(3)
        for n in clients:
            for i in range(0, 4) :
                n.update_partner_weights()
            n.average_partners()
for c in clients :
    print(c.logs['stringy'][99])
node4707epoch 99 loss 0.4933081567287445
node2356epoch 99 loss 0.47502967715263367
node2701epoch 99 loss 0.505750298500061
node1288epoch 99 loss 0.4734148383140564
node3711epoch 99 loss 0.48109182715415955
node2082epoch 99 loss 0.5586797595024109
accuracies = {}
with torch.no_grad():
    for i in clients :
        accuracies_node = []
        for batchno, (ex_data, ex_labels) in enumerate(test_loader) :
            accuracies_node.append(((i.model.forward(ex_data).argmax(dim = 1) == ex_labels).float().mean()).item())
        accuracies[i.node_id] = np.array(accuracies_node).mean()
accuracies
{4707: 0.8096000105142593,
 2356: 0.8093999952077866,
 2701: 0.8076000064611435,
 1288: 0.8087000012397766,
 3711: 0.8119000017642974,
 2082: 0.8101999938488007}