-
Notifications
You must be signed in to change notification settings - Fork 13
/
utils_v2.py
1775 lines (1413 loc) · 66.8 KB
/
utils_v2.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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from torchvision import datasets, transforms
import math
import random
import torch
import copy
import csv
from datetime import datetime
import os
import numpy as np
import torchvision
from torchvision import datasets, transforms
from torch.utils.data import Dataset, DataLoader
from torch import nn
import functools
import operator
import transform as T
import json
from torch.utils.data import DataLoader, RandomSampler, SequentialSampler
from scipy import io
import torch
from random import Random
from comm_helpers import SyncAllreduce, SyncAllreduce_1, SyncAllreduce_2, SyncAllGather
class Utils():
def target_transform(target):
return int(target) - 1
def get_dataset_dist(self, args):
if args.dataset == "cifar10":
data_dir = "./data"
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
])
train_dataset = datasets.CIFAR10(
root=data_dir,
train=True,
download=True,
transform=transform
)
test_dataset = datasets.CIFAR10(
root=data_dir,
train=False,
download=True,
transform=transform
)
if args.dataset == "svhn":
data_dir = "./data"
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
])
train_dataset = datasets.SVHN(
root=data_dir,
split='train',
download=True,
transform=transform
)
test_dataset = datasets.SVHN(
root=data_dir,
split='test',
download=True,
transform=transform
)
if args.dataset == "emnist":
data_dir = "./data"
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
])
train_dataset = datasets.EMNIST(root='./data/',
train=True,
transform=transform,split='balanced',
download=True)
test_dataset = datasets.EMNIST(root='./data/',
train=False,split='balanced',
transform=transform)
if args.dataset == "cifar10":
if args.iid:
user_idxs,server_idxs = self.iid_dist(train_dataset, args)
if args.user_semi:
user_idxs,server_idxs = user_semi_iid_dist2(dataset, args)
else:
if args.user_semi:
user_idxs,server_idxs = self.user_semi_noniid_dist2(train_dataset, args)
else:
user_idxs,server_idxs = self.getNonIIDdata(train_dataset, args)
if args.dataset == "svhn":
if args.iid:
user_idxs,server_idxs = self.iid_dist_svhn(train_dataset, args)
else:
user_idxs,server_idxs = self.getNonIIDdata_svhn(train_dataset, args)
if args.dataset == "emnist":
if args.iid:
user_idxs,server_idxs = self.iid_dist_emnist(train_dataset, args)
else:
user_idxs,server_idxs = self.getNonIIDdata_emnist_largeK(train_dataset, args)
return train_dataset, test_dataset, user_idxs,server_idxs
def iid_dist(self, dataset, args):
rng = Random()
rng.seed(1)
print('iid----')
data_per_device = (len(dataset) - args.num_data_server)//args.num_devices
num_sample_of_server = args.num_data_server
num_sample_of_each_class_server = int(num_sample_of_server/len(dataset.classes))
server_idxs=[]
rest_idxs = []
idx_target_class_list = []
for target_class in range(len(dataset.classes)):
idxs_target_class = np.where(np.array(dataset.targets)==target_class)[0].tolist()
np.random.shuffle(idxs_target_class)
idx_target_class_list.append(idxs_target_class)
### distribute sample of each class to the server
server_idxs += idx_target_class_list[target_class][0:num_sample_of_each_class_server]
### record rest sample according to class
rest_idxs += idx_target_class_list[target_class][num_sample_of_each_class_server:]
users_idxs = [[] for i in range(args.num_devices)] # Index dictionary for devices
random.shuffle(rest_idxs)
for i in range(args.num_devices):
users_idxs[i] = rest_idxs[i*data_per_device:(i+1)*data_per_device]
print(len(users_idxs))
return users_idxs,server_idxs
def user_semi_iid_dist2(self, dataset, args):
rng = Random()
rng.seed(1)
data_per_device = (len(dataset) - args.num_data_server)//args.num_devices
num_sample_of_server = args.num_data_server
num_sample_of_each_class_server = int(num_sample_of_server/len(dataset.classes))
server_idxs=[]
rest_idxs = []
idx_target_class_list = []
for target_class in range(len(dataset.classes)):
idxs_target_class = np.where(np.array(dataset.targets)==target_class)[0].tolist()
np.random.shuffle(idxs_target_class)
idx_target_class_list.append(idxs_target_class)
### distribute sample of each class to the server
server_idxs += idx_target_class_list[target_class][0:num_sample_of_each_class_server]
### record rest sample according to class
rest_idxs += idx_target_class_list[target_class][num_sample_of_each_class_server:]
users_idxs_u = [[] for i in range(args.num_devices)] # Index dictionary for devices
users_idxs_x = [[] for i in range(args.num_devices)] # Index dictionary for devices
random.shuffle(rest_idxs)
random.shuffle(server_idxs)
num_x = len(server_idxs)//args.num_devices
for i in range(args.num_devices):
users_idxs_u[i] = rest_idxs[i*data_per_device:(i+1)*data_per_device]
users_idxs_x[i] = server_idxs[i*num_x:(i+1)*num_x]
return users_idxs_u, users_idxs_x
def user_semi_noniid_dist2(self, dataset, args):
rng = Random()
rng.seed(1)
data_per_device = (len(dataset) - args.num_data_server)//args.num_devices
num_sample_of_server = args.num_data_server
num_sample_of_each_class_server = int(num_sample_of_server/len(dataset.classes))
server_idxs=[]
rest_idxs = []
idx_target_class_list = []
labeled_class_idx = []
server_labels = []
for target_class in range(len(dataset.classes)):
idxs_target_class = np.where(np.array(dataset.targets)==target_class)[0].tolist()
np.random.shuffle(idxs_target_class)
idx_target_class_list.append(idxs_target_class)
### distribute sample of each class to the server
server_idxs += idx_target_class_list[target_class][0:num_sample_of_each_class_server]
server_labels += [target_class for ii_lab in range(num_sample_of_each_class_server)]
labeled_class_idx.append(idx_target_class_list[target_class][0:num_sample_of_each_class_server])
### record rest sample according to class
rest_idxs += idx_target_class_list[target_class][num_sample_of_each_class_server:]
users_idxs_u = [[] for i in range(args.num_devices)] # Index dictionary for devices
users_idxs_x = [[] for i in range(args.num_devices)] # Index dictionary for devices
random.shuffle(rest_idxs)
for i_ue in range(args.num_devices):
users_idxs_u[i_ue] = rest_idxs[i_ue*data_per_device:(i_ue+1)*data_per_device]
target_classes = np.random.choice(np.arange(len(dataset.classes)),2)
random.shuffle(labeled_class_idx[target_classes[0]])
random.shuffle(labeled_class_idx[target_classes[1]])
users_idxs_x[i_ue] += labeled_class_idx[target_classes[0]][0:args.num_data_server//args.num_devices//2]
users_idxs_x[i_ue] += labeled_class_idx[target_classes[1]][0:args.num_data_server//args.num_devices//2]
current_classs = 0
users_classes = [[] for i in range(args.num_devices)] # Classes dictionary for devices
classes_devives = [[] for i in range(len(dataset.classes))] # Devices in each class
# Distribute class numbers to devices
for i in range(args.num_devices):
next_current_class = (current_classs+2)%len(dataset.classes)
if next_current_class > current_classs:
users_classes[i] = np.arange(current_classs, next_current_class)
else:
users_classes[i] = np.append(
np.arange(current_classs, len(dataset.classes)),
np.arange(0, next_current_class)
)
for j in users_classes[i]:
classes_devives[j].append(i)
current_classs = next_current_class
# Combine indexes and labels for sorting
idxs_labels = np.vstack((np.array(server_idxs) ,np.array(server_labels)))
idxs_labels = idxs_labels[:, idxs_labels[1, :].argsort()]
users_idxs = [[] for i in range(args.num_devices)] # Index dictionary for devices
current_idx = 0
for i in range(len(dataset.classes)):
if not len(classes_devives[i]):
continue
send_to_device = 0
for j in range(current_idx, len(idxs_labels[0])):
if idxs_labels[1, j] != i:
current_idx = j
break
users_idxs[classes_devives[i][send_to_device]].append(idxs_labels[0, j])
send_to_device = (send_to_device+1)%len(classes_devives[i])
return users_idxs_u, users_idxs
def iid_dist_svhn(self, dataset, args):
data_per_device = (len(dataset) - args.num_data_server)//args.num_devices
num_sample_of_server = len(dataset) - args.num_devices*data_per_device
num_sample_of_each_class_server = int(num_sample_of_server/10)
server_idxs=[]
rest_idxs = []
idx_target_class_list = []
for target_class in range(10):
idxs_target_class = np.where(np.array(dataset.labels)==target_class)[0].tolist()
np.random.shuffle(idxs_target_class)
idx_target_class_list.append(idxs_target_class)
### distribute sample of each class to the server
server_idxs += idx_target_class_list[target_class][0:num_sample_of_each_class_server]
### record rest sample according to class
rest_idxs += idx_target_class_list[target_class][num_sample_of_each_class_server:]
users_idxs = [[] for i in range(args.num_devices)] # Index dictionary for devices
random.shuffle(rest_idxs)
for i in range(args.num_devices):
users_idxs[i] = rest_idxs[i*data_per_device:(i+1)*data_per_device]
return users_idxs,server_idxs
def iid_dist_emnist(self, dataset, args):
data_per_device = (len(dataset) - args.num_data_server)//args.num_devices
print('data_per_device',data_per_device)
num_class = 47
num_sample_of_server = len(dataset) - args.num_devices*data_per_device
num_sample_of_each_class_server = int(num_sample_of_server/num_class)
server_idxs=[]
rest_idxs = []
idx_target_class_list = []
for target_class in range(num_class):
idxs_target_class = np.where(np.array(dataset.targets)==target_class)[0].tolist()
np.random.shuffle(idxs_target_class)
idx_target_class_list.append(idxs_target_class)
### distribute sample of each class to the server
server_idxs += idx_target_class_list[target_class][0:num_sample_of_each_class_server]
### record rest sample according to class
rest_idxs += idx_target_class_list[target_class][num_sample_of_each_class_server:]
users_idxs = [[] for i in range(args.num_devices)] # Index dictionary for devices
random.shuffle(rest_idxs)
for i in range(args.num_devices):
users_idxs[i] = rest_idxs[i*data_per_device:(i+1)*data_per_device]
return users_idxs,server_idxs
def getNonIIDdata_emnist(self, data, args):
from random import Random
from math import ceil
labelList = data.targets
labelList = labelList.cpu().numpy()
num_class = 47
Total_labelList = data.targets
Total_labelList = Total_labelList.cpu().numpy()
print(labelList.shape)
num_sample_of_server = args.num_data_server
######
num_sample_of_each_class_server = int(num_sample_of_server/num_class)
server_idxs=[]
idx_target_class_list = []
for target_class in range(num_class):
idxs_target_class = np.where(np.array(labelList)==target_class)[0].tolist()
np.random.shuffle(idxs_target_class)
idx_target_class_list.append(idxs_target_class)
### distribute sample of each class to the server
server_idxs += idx_target_class_list[target_class][0:num_sample_of_each_class_server]
np.random.shuffle(server_idxs)
######
# labelList = rest_idxs
rng = Random()
rng.seed(2020)
a = []
b = []
devices_labelid = []
for id in range(len(Total_labelList)):
if id not in server_idxs:
a.append((labelList[id], id))
b.append(labelList[id])
devices_labelid.append(id)
### sampels probility
sample_probility_ = []
for id in range(num_class):
index = np.where(np.array(b)==id)[0]
index = list(index)
sample_probility_.append(len(index))
sample_probility = np.array(sample_probility_)/np.sum(sample_probility_)
print(sample_probility)
# Same Part
labelIdxDict = dict()
for label, idx in a:
labelIdxDict.setdefault(label,[])
labelIdxDict[label].append(idx)
labelNum = len(labelIdxDict)
labelNameList = [key for key in labelIdxDict]
labelIdxPointer = [0] * labelNum
base_size = args.num_devices
partitions = [list() for i in range(base_size)]
eachPartitionLen= int(len(a)/base_size)
majorLabelNumPerPartition = ceil(labelNum/len(partitions))
print('majorLabelNumPerPartition',majorLabelNumPerPartition)
basicLabelRatio = args.basicLabelRatio
interval = 1
labelPointer = 0
#basic part
for partPointer in range(len(partitions)):
requiredLabelList = list()
for _ in range(majorLabelNumPerPartition):
requiredLabelList.append(labelPointer)
labelPointer += interval
if labelPointer > labelNum - 1:
labelPointer = interval
for labelIdx in requiredLabelList:
idxIncrement = int(sample_probility_[labelIdx]*basicLabelRatio)
partitions[partPointer].extend(labelIdxDict[labelIdx][0:idxIncrement])
labelIdxDict[labelIdx][0:idxIncrement] = []
#random part
remainLabels = list()
for labelIdx in range(labelNum):
remainLabels.extend(labelIdxDict[labelIdx])
remainLabels_class = []
for target_class in range(num_class):
tmp = np.where(np.array(Total_labelList[remainLabels])==target_class)[0].tolist()
remainLabels_class.append(len(tmp))
print(np.sum(remainLabels_class))
print(remainLabels_class)
for partPointer in range(len(partitions)):
for target_class in range(num_class):
idxs_target_class = np.where(np.array(Total_labelList[remainLabels])==target_class)[0].tolist()
num_sample_of_each_class = int(remainLabels_class[partPointer]*sample_probility[target_class])
remainLabels_array = np.array(remainLabels)
partitions[partPointer].extend(remainLabels_array[idxs_target_class[0:num_sample_of_each_class]].tolist())
remainLabels = np.delete(np.array(remainLabels), idxs_target_class[0:num_sample_of_each_class]).tolist()
rng.shuffle(partitions[partPointer])
return partitions,server_idxs
def non_iid_dist_random(self, dataset, args):
### Number of samples the server has
num_sample_of_server = len(dataset) - args.num_devices*args.max_data_per_device
import itertools
all_class = np.arange(len(dataset.classes)).tolist()
### Produce all possible combinations of users' class
all_combination = list(itertools.combinations(all_class,args.class_per_device))
np.random.shuffle(all_combination) ### Shuffle the order of these combinations
idx_target_class_list = []
### Divide the samples of each class equally for the server
num_sample_of_each_class_server = int(num_sample_of_server/len(dataset.classes))
server_idxs = []
rest_idxs = []
for target_class in range(len(dataset.classes)):
idxs_target_class = np.where(np.array(dataset.targets)==target_class)[0].tolist()
np.random.shuffle(idxs_target_class)
idx_target_class_list.append(idxs_target_class)
### distribute sample of each class to the server
server_idxs += idx_target_class_list[target_class][0:num_sample_of_each_class_server]
### record rest sample according to class
rest_idxs.append(idx_target_class_list[target_class][num_sample_of_each_class_server:])
users_idxs = [[] for i in range(args.num_devices)]
### distribute sample of each class to users
for user_id in range(args.num_devices):
if user_id>=len(all_combination):
combination_id = user_id%len(all_combination)
else:
combination_id = user_id
user_class = all_combination[combination_id]
user_idxs_tmp = []
for user_class_i in list(user_class):
np.random.shuffle(rest_idxs[user_class_i])
user_idxs_tmp += rest_idxs[user_class_i][0:int(args.max_data_per_device/args.class_per_device)]
users_idxs[user_id] = user_idxs_tmp
return users_idxs,server_idxs
def getNonIIDdata(self, data, args):
from random import Random
from math import ceil
labelList = data.targets
num_sample_of_server = args.num_data_server
######
num_sample_of_each_class_server = int(num_sample_of_server/len(data.classes))
server_idxs=[]
idx_target_class_list = []
for target_class in range(len(data.classes)):
idxs_target_class = np.where(np.array(data.targets)==target_class)[0].tolist()
np.random.shuffle(idxs_target_class)
idx_target_class_list.append(idxs_target_class)
### distribute sample of each class to the server
server_idxs += idx_target_class_list[target_class][0:num_sample_of_each_class_server]
######
rng = Random()
rng.seed(2020)
a = []
for id in range(len(data)):
if id not in server_idxs:
a.append((labelList[id], id))
# Same Part
labelIdxDict = dict()
for label, idx in a:
labelIdxDict.setdefault(label,[])
labelIdxDict[label].append(idx)
labelNum = len(labelIdxDict)
labelNameList = [key for key in labelIdxDict]
labelIdxPointer = [0] * labelNum
base_size = 10
partitions = [list() for i in range(base_size)]
eachPartitionLen= int(len(a)/base_size)
majorLabelNumPerPartition = ceil(labelNum/len(partitions))
print('majorLabelNumPerPartition',majorLabelNumPerPartition)
basicLabelRatio = args.basicLabelRatio
interval = 1
labelPointer = 0
#basic part
for partPointer in range(len(partitions)):
requiredLabelList = list()
for _ in range(majorLabelNumPerPartition):
requiredLabelList.append(labelPointer)
labelPointer += interval
if labelPointer > labelNum - 1:
labelPointer = interval
for labelIdx in requiredLabelList:
start = labelIdxPointer[labelIdx]
idxIncrement = int(eachPartitionLen*basicLabelRatio)
partitions[partPointer].extend(labelIdxDict[labelNameList[labelIdx]][start:start+ idxIncrement])
length_tmp = len(labelIdxDict[labelNameList[labelIdx]][start:start+ idxIncrement])
tmp = np.arange(start).tolist()
random.shuffle(tmp)
index_tmp = np.array(labelIdxDict[labelNameList[labelIdx]])
if length_tmp < idxIncrement:
partitions[partPointer].extend(index_tmp[tmp[0:idxIncrement-length_tmp]].tolist())
labelIdxPointer[labelIdx] += idxIncrement
#random part
remainLabels = list()
for labelIdx in range(labelNum):
remainLabels.extend(labelIdxDict[labelNameList[labelIdx]][labelIdxPointer[labelIdx]:])
rng.shuffle(remainLabels)
for partPointer in range(len(partitions)):
idxIncrement = eachPartitionLen - len(partitions[partPointer])
partitions[partPointer].extend(remainLabels[:idxIncrement])
rng.shuffle(partitions[partPointer])
remainLabels = remainLabels[idxIncrement:]
if args.num_devices == 20:
partitions_list = [list() for i in range(20)]
for partPointer in range(10):
index_partitions = partitions[partPointer]
len_partitions = len(index_partitions)
rng.shuffle(index_partitions)
partitions_list[partPointer] = index_partitions[0:len_partitions//2]
partitions_list[partPointer+10] = index_partitions[len_partitions//2:]
partitions = partitions_list
if args.num_devices == 30:
partitions_list = [list() for i in range(30)]
for partPointer in range(10):
index_partitions = partitions[partPointer]
len_partitions = len(index_partitions)
rng.shuffle(index_partitions)
partitions_list[partPointer] = index_partitions[0:len_partitions//3]
partitions_list[partPointer+10] = index_partitions[len_partitions//3:len_partitions*2//3]
partitions_list[partPointer+20] = index_partitions[len_partitions*2//3:]
partitions = partitions_list
if args.num_devices == 100:
partitions_list = [list() for i in range(100)]
for partPointer in range(10):
index_partitions = partitions[partPointer]
len_partitions = len(index_partitions)
rng.shuffle(index_partitions)
for ii in range(10-1):
partitions_list[partPointer+ii*10] = index_partitions[(len_partitions*ii)//10:(len_partitions*(ii+1))//10]
partitions_list[partPointer+90] = index_partitions[len_partitions*9//10:]
partitions = partitions_list
return partitions, server_idxs
def getNonIIDdata_svhn(self, data, args):
from random import Random
from math import ceil
labelList = copy.deepcopy(data.labels) - 1
num_sample_of_server = args.num_data_server
server_idxs = np.arange(0,num_sample_of_server).tolist()
######
num_sample_of_each_class_server = int(num_sample_of_server/10)
server_idxs=[]
idx_target_class_list = []
for target_class in range(10):
idxs_target_class = np.where(np.array(data.labels)==target_class)[0].tolist()
np.random.shuffle(idxs_target_class)
idx_target_class_list.append(idxs_target_class)
### distribute sample of each class to the server
server_idxs += idx_target_class_list[target_class][0:num_sample_of_each_class_server]
######
rng = Random()
rng.seed(2020)
a = []
for id in range(len(data)):
if id not in server_idxs:
a.append((labelList[id], id))
# Same Part
labelIdxDict = dict()
for label, idx in a:
labelIdxDict.setdefault(label,[])
labelIdxDict[label].append(idx)
labelNum = len(labelIdxDict)
labelNameList = [key for key in labelIdxDict]
labelIdxPointer = [0] * labelNum
# sizes = number of nodes
sizes = args.num_devices
partitions = [list() for i in range(sizes)]
eachPartitionLen= int(len(a)/sizes)
majorLabelNumPerPartition = ceil(labelNum/len(partitions))
print('majorLabelNumPerPartition',majorLabelNumPerPartition)
basicLabelRatio = args.basicLabelRatio
interval = 1
labelPointer = 0
#basic part
for partPointer in range(len(partitions)):
requiredLabelList = list()
for _ in range(majorLabelNumPerPartition):
requiredLabelList.append(labelPointer)
labelPointer += interval
if labelPointer > labelNum - 1:
labelPointer = interval
for labelIdx in requiredLabelList:
start = labelIdxPointer[labelIdx]
idxIncrement = int(eachPartitionLen*basicLabelRatio)
partitions[partPointer].extend(labelIdxDict[labelNameList[labelIdx]][start:start+ idxIncrement])
length_tmp = len(labelIdxDict[labelNameList[labelIdx]][start:start+ idxIncrement])
tmp = np.arange(start).tolist()
index_tmp = np.array(labelIdxDict[labelNameList[labelIdx]])
if length_tmp < idxIncrement:
partitions[partPointer].extend(index_tmp[tmp[0:idxIncrement-length_tmp]].tolist())
labelIdxPointer[labelIdx] += idxIncrement
#random part
remainLabels = list()
for labelIdx in range(labelNum):
remainLabels.extend(labelIdxDict[labelNameList[labelIdx]][labelIdxPointer[labelIdx]:])
rng.shuffle(remainLabels)
for partPointer in range(len(partitions)):
idxIncrement = eachPartitionLen - len(partitions[partPointer])
partitions[partPointer].extend(remainLabels[:idxIncrement])
rng.shuffle(partitions[partPointer])
remainLabels = remainLabels[idxIncrement:]
return partitions, server_idxs
def getNonIIDdata_emnist_largeK(self, data, args):
from random import Random
from math import ceil
labelList = data.targets
labelList = labelList.cpu().numpy()
num_class = 47
Total_labelList = data.targets
Total_labelList = Total_labelList.cpu().numpy()
print(labelList.shape)
num_sample_of_server = args.num_data_server
######
num_sample_of_each_class_server = int(num_sample_of_server/num_class)
server_idxs=[]
idx_target_class_list = []
for target_class in range(num_class):
idxs_target_class = np.where(np.array(labelList)==target_class)[0].tolist()
np.random.shuffle(idxs_target_class)
idx_target_class_list.append(idxs_target_class)
### distribute sample of each class to the server
server_idxs += idx_target_class_list[target_class][0:num_sample_of_each_class_server]
np.random.shuffle(server_idxs)
rng = Random()
rng.seed(2020)
a = []
b = []
devices_labelid = []
for id in range(len(Total_labelList)):
if id not in server_idxs:
a.append((labelList[id], id))
b.append(labelList[id])
devices_labelid.append(id)
### sampels probility
sample_probility_ = []
for id in range(num_class):
index = np.where(np.array(b)==id)[0]
index = list(index)
sample_probility_.append(len(index))
sample_probility = np.array(sample_probility_)/np.sum(sample_probility_)
print(sample_probility)
# Same Part
labelIdxDict = dict()
for label, idx in a:
labelIdxDict.setdefault(label,[])
labelIdxDict[label].append(idx)
labelNum = len(labelIdxDict)
labelNameList = [key for key in labelIdxDict]
labelIdxPointer = [0] * labelNum
base_size = 47
partitions = [list() for i in range(base_size)]
eachPartitionLen= int(len(a)/base_size)
majorLabelNumPerPartition = ceil(labelNum/len(partitions))
print('majorLabelNumPerPartition',majorLabelNumPerPartition)
basicLabelRatio = args.basicLabelRatio
interval = 1
labelPointer = 0
#basic part
for partPointer in range(len(partitions)):
requiredLabelList = list()
for _ in range(majorLabelNumPerPartition):
requiredLabelList.append(labelPointer)
labelPointer += interval
if labelPointer > labelNum - 1:
labelPointer = interval
for labelIdx in requiredLabelList:
idxIncrement = int(sample_probility_[labelIdx]*basicLabelRatio)
partitions[partPointer].extend(labelIdxDict[labelIdx][0:idxIncrement])
labelIdxDict[labelIdx][0:idxIncrement] = []
#random part
remainLabels = list()
for labelIdx in range(labelNum):
remainLabels.extend(labelIdxDict[labelIdx])
remainLabels_class = []
for target_class in range(num_class):
tmp = np.where(np.array(Total_labelList[remainLabels])==target_class)[0].tolist()
remainLabels_class.append(len(tmp))
print(np.sum(remainLabels_class))
print(remainLabels_class)
for partPointer in range(len(partitions)):
for target_class in range(num_class):
idxs_target_class = np.where(np.array(Total_labelList[remainLabels])==target_class)[0].tolist()
num_sample_of_each_class = int(remainLabels_class[partPointer]*sample_probility[target_class])
remainLabels_array = np.array(remainLabels)
partitions[partPointer].extend(remainLabels_array[idxs_target_class[0:num_sample_of_each_class]].tolist())
remainLabels = np.delete(np.array(remainLabels), idxs_target_class[0:num_sample_of_each_class]).tolist()
rng.shuffle(partitions[partPointer])
if args.num_devices == 470:
partitions_list = [list() for i in range(470)]
for partPointer in range(num_class):
index_partitions = partitions[partPointer]
len_partitions = len(index_partitions)
rng.shuffle(index_partitions)
for increase_tmp in range(10):
partitions_list[partPointer + increase_tmp*47] = index_partitions[len_partitions*(increase_tmp)//10:len_partitions*(increase_tmp+1)//10]
partitions = partitions_list
return partitions, server_idxs
def Generate_device_server_index(args, path_device_idxs):
utils = Utils()
train_dataset, test_dataset, device_idxs, server_idxs = utils.get_dataset_dist(args) ##### generate the data indexes of the users and the server
dictionary1 = {'device_idxs':device_idxs}
np.save(path_device_idxs+"device_idxs.npy", dictionary1)
dictionary2 = {'server_idxs':server_idxs}
np.save(path_device_idxs+"server_idxs.npy", dictionary2)
def Load_device_server_index(args, path_device_idxs):
#### load data index of the users and the server
device_ids = np.load(path_device_idxs + 'device_idxs' + '.npy', allow_pickle=True).item()
server_idxs = np.load(path_device_idxs + 'server_idxs' + '.npy', allow_pickle=True).item()
device_ids = device_ids['device_idxs']
server_idxs = server_idxs['server_idxs']
return server_idxs, device_ids
def Generate_communicate_user_list(args, path_device_idxs):
iterations_epoch = args.k_img//args.bs
if args.num_comm_ue == 10:
ue_list_epoch = np.zeros((args.epoch,iterations_epoch,args.num_comm_ue+1+args.H),dtype='int32')
if args.num_comm_ue == 30:
ue_list_epoch = np.zeros((args.epoch,iterations_epoch,args.num_comm_ue+1+args.H*2),dtype='int32')
if args.num_comm_ue == 47:
ue_list_epoch = np.zeros((args.epoch,iterations_epoch,args.num_comm_ue+1+args.H*4),dtype='int32')
if args.user_semi:
ue_list_epoch = np.zeros((args.epoch,iterations_epoch,args.num_comm_ue),dtype='int32')
if args.num_comm_ue == 20:
ue_list_epoch = np.zeros((args.epoch,iterations_epoch,args.num_comm_ue+1+args.H),dtype='int32')
if args.num_comm_ue <= args.size - 1:
for e in range(args.epoch):
for it in range(iterations_epoch):
if args.user_semi:
ue_list = np.arange(0, args.size).tolist()
connected_user_list = random.sample(ue_list, args.num_comm_ue)
ue_list = connected_user_list
else:
ue_list = np.arange(1, args.num_devices+1).tolist()
connected_user_list = random.sample(ue_list, args.num_comm_ue)
ue_list = connected_user_list
random.shuffle(ue_list)
ue_list = [0] + ue_list
if args.H and args.dataset == 'emnist':
if args.num_comm_ue == 10:
ue_list = ue_list + [48]
if args.num_comm_ue == 30:
ue_list = ue_list + [48,49]
if args.num_comm_ue == 47:
ue_list = ue_list + [48,49,50,51]
if args.H and args.dataset == 'cifar10':
if args.num_comm_ue == 10 and args.num_devices == 10:
ue_list = ue_list + [11]
if args.num_comm_ue == 10 and args.num_devices == 30:
ue_list = ue_list + [31]
if args.num_comm_ue == 20 and args.num_devices == 20:
ue_list = ue_list + [21]
if args.num_comm_ue == 20 and args.num_devices == 30:
ue_list = ue_list + [31]
if args.num_comm_ue == 30:
ue_list = ue_list + [31,32]
if args.H and args.dataset == 'svhn':
if args.num_comm_ue == 10 and args.num_devices == 10:
ue_list = ue_list + [11]
if args.num_comm_ue == 10 and args.num_devices == 30:
ue_list = ue_list + [31]
if args.num_comm_ue == 20 and args.num_devices == 20:
ue_list = ue_list + [21]
if args.num_comm_ue == 20 and args.num_devices == 30:
ue_list = ue_list + [31]
if args.num_comm_ue == 30:
ue_list = ue_list + [31,32]
ue_list = np.array(ue_list, dtype='int32')
ue_list_epoch[e,it,0:len(ue_list)] = ue_list
ue_list_epoch = np.array(ue_list_epoch, dtype='int32')
io.savemat(path_device_idxs+'ue_list_epoch.mat', {'ue_list_epoch': ue_list_epoch})
dictionary1 = {'ue_list_epoch':ue_list_epoch.tolist()}
np.save(path_device_idxs + "ue_list_epoch.npy", dictionary1)
def Load_communicate_user_list(args, path_device_idxs):
if args.num_comm_ue <= args.size - 1:
ue_list_epoches = np.load(path_device_idxs + 'ue_list_epoch' + '.npy', allow_pickle=True).item()
ue_list_epoches = ue_list_epoches['ue_list_epoch']
else:
ue_list_epoches = []
return ue_list_epoches
def Generate_Train_data_loader(args, labeled_dataset, unlabeled_dataset, train_sampler):
Train_data_loader = []
if args.dataset == 'emnist':
if args.num_comm_ue == 10:
server_rank_list = [0,48]
if args.num_comm_ue == 30:
server_rank_list = [0,48,49]
if args.num_comm_ue == 20:
server_rank_list = [0,21]
if args.num_comm_ue == 47:
server_rank_list = [0,48,49,50,51]
if args.dataset == 'svhn' or args.dataset == 'cifar10':
if args.num_comm_ue == 10 and args.num_devices == 10:
server_rank_list = [0,11]
if args.num_comm_ue == 10 and args.num_devices == 20:
server_rank_list = [0,21]
if args.num_comm_ue == 20 and args.num_devices == 20:
server_rank_list = [0,21]
if args.num_comm_ue == 10 and args.num_devices == 30:
server_rank_list = [0,31]
if args.num_comm_ue == 20 and args.num_devices == 30:
server_rank_list = [0,31]
if args.num_comm_ue == 30 and args.num_devices == 30:
server_rank_list = [0,31,32]
k = 0
for rank in range(args.size):
if rank in set(server_rank_list):
Data_Loader = Assign_Train_data_loader(args, rank, labeled_dataset, unlabeled_dataset, train_sampler, k=0)
else:
k = k+1
Data_Loader = Assign_Train_data_loader(args, rank, labeled_dataset, unlabeled_dataset, train_sampler, k)
Train_data_loader.append(Data_Loader)
return Train_data_loader
def Generate_Train_data_loader_user_side_semi(args, labeled_dataset, unlabeled_dataset, test_dataset):
Train_data_loader = []
k = 0
for rank in range(args.size):
labeled_trainloader = DataLoader(
labeled_dataset[rank],
# sampler=train_sampler(labeled_dataset),
shuffle = True,
batch_size=args.bs,
num_workers=4,
drop_last=True)
unlabeled_trainloader = DataLoader(
unlabeled_dataset[rank],
# sampler=train_sampler(unlabeled_dataset[rank-1]),
batch_size=args.bs,
num_workers=4,
shuffle = True,
drop_last = True)
Train_data_loader.append([labeled_trainloader,unlabeled_trainloader])
test_loader = DataLoader(test_dataset,
batch_size=args.bs,
shuffle=False,num_workers=4)
return Train_data_loader, [test_loader]
def Generate_Test_data_loader(args, test_dataset, base_dataset, device_ids):
Test_data_loader = []
for rank in range(args.size):
Data_Loader = Assign_Test_data_loader(args, rank, test_dataset, base_dataset, device_ids)
Test_data_loader.append(Data_Loader)
return Test_data_loader
def Assign_Train_data_loader(args, rank, labeled_dataset, unlabeled_dataset, train_sampler, k):
if k > 0:
unlabeled_trainloader = DataLoader(
unlabeled_dataset[k-1],
# sampler=train_sampler(unlabeled_dataset[rank-1]),
batch_size=args.bs,
num_workers=4,
shuffle = True,
drop_last = True)
return unlabeled_trainloader
else:
labeled_trainloader = DataLoader(