-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodel_utils.py
executable file
·181 lines (159 loc) · 6.78 KB
/
model_utils.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
180
181
import json
import numpy as np
import os
import torch
import torch.nn as nn
IMAGE_SIZE = 28
IMAGE_PIXELS = IMAGE_SIZE * IMAGE_SIZE
NUM_CHANNELS = 1
def suffer_data(data):
data_x = data['x']
data_y = data['y']
# randomly shuffle data
np.random.seed(100)
rng_state = np.random.get_state()
np.random.shuffle(data_x)
np.random.set_state(rng_state)
np.random.shuffle(data_y)
return (data_x, data_y)
def batch_data(data, batch_size):
'''
data is a dict := {'x': [numpy array], 'y': [numpy array]} (on one client)
returns x, y, which are both numpy array of length: batch_size
'''
data_x = data['x']
data_y = data['y']
# randomly shuffle data
np.random.seed(100)
rng_state = np.random.get_state()
np.random.shuffle(data_x)
np.random.set_state(rng_state)
np.random.shuffle(data_y)
# loop through mini-batches
for i in range(0, len(data_x), batch_size):
batched_x = data_x[i:i+batch_size]
batched_y = data_y[i:i+batch_size]
yield (batched_x, batched_y)
def get_random_batch_sample(data_x, data_y, batch_size):
num_parts = len(data_x)//batch_size + 1
if(len(data_x) > batch_size):
batch_idx = np.random.choice(list(range(num_parts +1)))
sample_index = batch_idx*batch_size
if(sample_index + batch_size > len(data_x)):
return (data_x[sample_index:], data_y[sample_index:])
else:
return (data_x[sample_index: sample_index+batch_size], data_y[sample_index: sample_index+batch_size])
else:
return (data_x,data_y)
def get_batch_sample(data, batch_size):
data_x = data['x']
data_y = data['y']
np.random.seed(100)
rng_state = np.random.get_state()
np.random.shuffle(data_x)
np.random.set_state(rng_state)
np.random.shuffle(data_y)
batched_x = data_x[0:batch_size]
batched_y = data_y[0:batch_size]
return (batched_x, batched_y)
def read_data(dataset):
'''parses data in given train and test data directories
assumes:
- the data in the input directories are .json files with
keys 'users' and 'user_data'
- the set of train set users is the same as the set of test set users
Return:
clients: list of client ids
groups: list of group ids; empty list if none found
train_data: dictionary of train data
test_data: dictionary of test data
'''
train_data_dir = os.path.join('data',dataset,'data', 'train')
test_data_dir = os.path.join('data',dataset,'data', 'test')
clients = []
groups = []
train_data = {}
test_data = {}
train_files = os.listdir(train_data_dir)
train_files = [f for f in train_files if f.endswith('.json')]
for f in train_files:
file_path = os.path.join(train_data_dir, f)
with open(file_path, 'r') as inf:
cdata = json.load(inf)
clients.extend(cdata['users'])
if 'hierarchies' in cdata:
groups.extend(cdata['hierarchies'])
train_data.update(cdata['user_data'])
test_files = os.listdir(test_data_dir)
test_files = [f for f in test_files if f.endswith('.json')]
for f in test_files:
file_path = os.path.join(test_data_dir, f)
with open(file_path, 'r') as inf:
cdata = json.load(inf)
test_data.update(cdata['user_data'])
clients = list(sorted(train_data.keys()))
return clients, groups, train_data, test_data
def read_user_data(index,data,dataset):
id = data[0][index]
train_data = data[2][id]
test_data = data[3][id]
X_train, y_train, X_test, y_test = train_data['x'], train_data['y'], test_data['x'], test_data['y']
if(dataset == "Mnist"):
X_train, y_train, X_test, y_test = train_data['x'], train_data['y'], test_data['x'], test_data['y']
X_train = torch.Tensor(X_train).view(-1, NUM_CHANNELS, IMAGE_SIZE, IMAGE_SIZE).type(torch.float32)
y_train = torch.Tensor(y_train).type(torch.int64)
X_test = torch.Tensor(X_test).view(-1, NUM_CHANNELS, IMAGE_SIZE, IMAGE_SIZE).type(torch.float32)
y_test = torch.Tensor(y_test).type(torch.int64)
elif(dataset == "Linear_synthetic"):
X_train = torch.Tensor(X_train).type(torch.float32)
y_train = torch.Tensor(y_train).type(torch.float32).unsqueeze(1)
X_test = torch.Tensor(X_test).type(torch.float32)
y_test = torch.Tensor(y_test).type(torch.float32).unsqueeze(1)
#y_train = torch.flatten(y_train, 1)
#y_test = torch.flatten(y_test, 1)
#print(y_test.size(),y_train.size())
else:
X_train = torch.Tensor(X_train).type(torch.float32)
y_train = torch.Tensor(y_train).type(torch.int64)
X_test = torch.Tensor(X_test).type(torch.float32)
y_test = torch.Tensor(y_test).type(torch.int64)
train_data = [(x, y) for x, y in zip(X_train, y_train)]
test_data = [(x, y) for x, y in zip(X_test, y_test)]
return id, train_data, test_data
class Metrics(object):
def __init__(self, clients, params):
self.params = params
num_rounds = params['num_rounds']
self.bytes_written = {c.id: [0] * num_rounds for c in clients}
self.client_computations = {c.id: [0] * num_rounds for c in clients}
self.bytes_read = {c.id: [0] * num_rounds for c in clients}
self.accuracies = []
self.train_accuracies = []
def update(self, rnd, cid, stats):
bytes_w, comp, bytes_r = stats
self.bytes_written[cid][rnd] += bytes_w
self.client_computations[cid][rnd] += comp
self.bytes_read[cid][rnd] += bytes_r
def write(self):
metrics = {}
metrics['dataset'] = self.params['dataset']
metrics['num_rounds'] = self.params['num_rounds']
metrics['eval_every'] = self.params['eval_every']
metrics['learning_rate'] = self.params['learning_rate']
metrics['mu'] = self.params['mu']
metrics['num_epochs'] = self.params['num_epochs']
metrics['batch_size'] = self.params['batch_size']
metrics['accuracies'] = self.accuracies
metrics['train_accuracies'] = self.train_accuracies
metrics['client_computations'] = self.client_computations
metrics['bytes_written'] = self.bytes_written
metrics['bytes_read'] = self.bytes_read
metrics_dir = os.path.join('out', self.params['dataset'], 'metrics_{}_{}_{}_{}_{}.json'.format(
self.params['seed'], self.params['optimizer'], self.params['learning_rate'], self.params['num_epochs'], self.params['mu']))
#os.mkdir(os.path.join('out', self.params['dataset']))
if not os.path.exists('out'):
os.mkdir('out')
if not os.path.exists(os.path.join('out', self.params['dataset'])):
os.mkdir(os.path.join('out', self.params['dataset']))
with open(metrics_dir, 'w') as ouf:
json.dump(metrics, ouf)