-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdataset.py
179 lines (144 loc) · 6.95 KB
/
dataset.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
import torch
import torchvision
from torch import nn
from torchvision.models import resnet18
from torch.utils.data import DataLoader, random_split, Dataset
from fedlab.utils.dataset.partition import CIFAR10Partitioner
import json
import numpy as np
from tqdm import tqdm
from io import BytesIO
from flwr.common import Parameters
import random
from torchvision.transforms import ToTensor, Normalize, Compose
from torchvision.datasets import MNIST
class FEMNISTDataset(Dataset):
def __init__(self, X_data, y_data):
self.X_data = X_data
self.y_data = y_data
def __len__(self):
return len(self.X_data)
def __getitem__(self, index):
return self.X_data[index], self.y_data[index]
def femnist_data(path_to_data_folder="data/femnist_data", combine_clients=20, subset=50):
"""
Input: the path to the folder of json files.
Data is downloadable from: https://mega.nz/file/XYhhSRIb#PAVgu1zGUoGUU5EzF2xCOnUmGlp5nNQAF8gPdvo_m2U
It can also be downloaded by cloning the LEAF repository, and running the following command in the femnist folder:
./preprocess.sh -s niid --iu 1.0 --sf 1.0 -k 0 -t sample --smplseed 42 --spltseed 42
Returns: a tuple containing the training dataloaders, and test dataloaders,
with a dataloader for each client
"""
all_clients = []
for i in tqdm(range(0, 36)): # for each json file
with open(f"{path_to_data_folder}/all_data_{i}.json") as file:
data = json.load(file)
for client in data["users"]:
X_data = data["user_data"][client]["x"]
num_samples = len(X_data)
X_data = np.array(X_data, dtype=np.float32).reshape(num_samples, 1, 28, 28)
y_data = np.array(data["user_data"][client]["y"], dtype=np.int64)
all_clients.append((X_data, y_data))
# Combine clients
all_X_train, all_y_train, all_X_test, all_y_test = [], [], [], []
for group in zip(*[iter(all_clients)] * combine_clients):
X_data = np.concatenate([client[0] for client in group])
y_data = np.concatenate([client[1] for client in group])
X_train, X_test = random_split(X_data, (0.9, 0.1), torch.Generator().manual_seed(42))
y_train, y_test = random_split(y_data, (0.9, 0.1), torch.Generator().manual_seed(42))
all_X_train.append(X_train)
all_y_train.append(y_train)
all_X_test.append(X_test)
all_y_test.append(y_test)
indices = np.random.choice(len(all_X_train), size=subset, replace=False)
selected_X_train = [all_X_train[i] for i in indices]
selected_y_train = [all_y_train[i] for i in indices]
selected_X_test = [all_X_test[i] for i in indices]
selected_y_test = [all_y_test[i] for i in indices]
X_train = np.concatenate(selected_X_train)
y_train = np.concatenate(selected_y_train)
X_test = np.concatenate(selected_X_test)
y_test = np.concatenate(selected_y_test)
# Create PyTorch datasets
train_dataset = FEMNISTDataset(X_train, y_train)
test_dataset = FEMNISTDataset(X_test, y_test)
return train_dataset, test_dataset
def cifar_data(num_clients=50, balanced_data=False):
"""
Returns: a tuple containing the training data loaders, and test data loaders,
with a dataloader for each client
"""
# Download and reshape the dataset
train_data = torchvision.datasets.CIFAR10(root="cifar_data", train=True, download=True)
test_data = torchvision.datasets.CIFAR10(root="cifar_data", train=False, download=True)
X_train = (train_data.data / 255).astype(np.float32).transpose(0, 3, 1, 2)
y_train = np.array(train_data.targets, dtype=np.int64)
X_test = (test_data.data / 255).astype(np.float32).transpose(0, 3, 1, 2)
y_test = np.array(test_data.targets, dtype=np.int64)
if balanced_data:
balance=True
partition="iid"
dir_alpha=None
else: # data not balanced
balance=None
partition="dirichlet"
dir_alpha=0.3
# Partition the data
partitioned_train_data = CIFAR10Partitioner(train_data.targets,
num_clients,
balance=balance,
partition=partition,
dir_alpha=dir_alpha,
seed=42)
partitioned_test_data = CIFAR10Partitioner(test_data.targets,
num_clients,
balance=True,
partition="iid",
seed=42)
all_client_trainloaders = []
all_client_testloaders = []
# Put the data onto a dataloader for each client, following the partitions
for client in range(num_clients):
client_X_train = X_train[partitioned_train_data[client], :, :, :]
client_y_train = y_train[partitioned_train_data[client]]
torch.manual_seed(47)
train_loader = DataLoader(dataset=list(zip(client_X_train, client_y_train)),
batch_size=32,
shuffle=True,
pin_memory=True)
client_X_test = X_test[partitioned_test_data[client], :, :, :]
client_y_test = y_test[partitioned_test_data[client]]
torch.manual_seed(47)
test_loader = DataLoader(dataset=list(zip(client_X_test, client_y_test)),
batch_size=32,
shuffle=True,
pin_memory=True)
all_client_trainloaders.append(train_loader)
all_client_testloaders.append(test_loader)
return all_client_trainloaders, all_client_testloaders
def prepare_dataset(num_partitions: int, batch_size: int, val_ratio: float = 0.1):
"""Download MNIST and generate IID partitions."""
trainset, testset = femnist_data()
remaining_samples = len(trainset) % num_partitions
num_images = len(trainset) // num_partitions
partition_len = [num_images] * num_partitions
for i in range(remaining_samples):
partition_len[i] += 1
trainsets = random_split( trainset, partition_len, torch.Generator().manual_seed(47))
trainloaders = []
valloaders = []
for trainset_ in trainsets:
num_total = len(trainset_)
num_val = int(val_ratio * num_total)
num_train = num_total - num_val
for_train, for_val = random_split(
trainset_, [num_train, num_val], torch.Generator().manual_seed(2023)
)
trainloaders.append(
DataLoader(for_train, batch_size=batch_size, shuffle=True, num_workers=2)
)
valloaders.append(
DataLoader(for_val, batch_size=batch_size, shuffle=False, num_workers=2)
)
testloader = DataLoader(testset, batch_size=128)
return trainloaders, valloaders, testloader