AnsonZhang commited on
Commit
17da1e2
1 Parent(s): a7b70c3

Create femnist.py

Browse files
Files changed (1) hide show
  1. femnist.py +133 -0
femnist.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+ import matplotlib.pyplot as plt
4
+ import math
5
+ import numpy as np
6
+ import os
7
+
8
+ from scipy import io
9
+ from scipy import stats
10
+ from tqdm import tqdm
11
+ import math
12
+ import PIL.Image as Img
13
+ import uuid
14
+
15
+ def show_img(image):
16
+ image = np.multiply(image, 255)
17
+ image = image.reshape(int(math.sqrt(len(image))), int(math.sqrt(len(image))))
18
+ image = Img.fromarray(image)
19
+ image = image.convert('L')
20
+ image.save('outfile.png')
21
+
22
+ def gen_data_dict(data_dict, raw_data, group_name):
23
+ data_dict[group_name] = []
24
+ for _, value in raw_data.items():
25
+ for img_data, img_label in zip(value['x'], value['y']):
26
+ data_dict[group_name].append({
27
+ 'image': np.multiply(img_data, 255),
28
+ 'label': img_label
29
+ })
30
+
31
+ def construct_data_dirs_clientwise(raw_data, group_name, data_dir, data_type='train'):
32
+ data_group_dir = os.path.join(data_dir, 'huggingface', 'clientwise', group_name, data_type)
33
+ if not os.path.exists(data_group_dir):
34
+ os.makedirs(data_group_dir)
35
+
36
+ for _, value in raw_data.items():
37
+ for img_data, img_label in zip(value['x'], value['y']):
38
+ sample_dir = os.path.join(data_group_dir, str(img_label))
39
+ if not os.path.exists(sample_dir):
40
+ os.makedirs(sample_dir)
41
+ sampel_path = os.path.join(sample_dir, str(uuid.uuid1())[:8]+'.png')
42
+
43
+ image = np.multiply(img_data, 255)
44
+ image = image.reshape(int(math.sqrt(len(image))), int(math.sqrt(len(image))))
45
+ image = Img.fromarray(image)
46
+ image = image.convert('L')
47
+ image.save(sampel_path)
48
+
49
+ def construct_data_dirs(raw_data, data_dir, data_type='train'):
50
+ data_group_dir = os.path.join(data_dir, 'huggingface', 'centralized', data_type)
51
+ if not os.path.exists(data_group_dir):
52
+ os.makedirs(data_group_dir)
53
+
54
+ for _, value in raw_data.items():
55
+ for img_data, img_label in zip(value['x'], value['y']):
56
+ sample_dir = os.path.join(data_group_dir, str(img_label))
57
+ if not os.path.exists(sample_dir):
58
+ os.makedirs(sample_dir)
59
+ sampel_path = os.path.join(sample_dir, str(uuid.uuid1())[:8]+'.png')
60
+
61
+ image = np.multiply(img_data, 255)
62
+ image = image.reshape(int(math.sqrt(len(image))), int(math.sqrt(len(image))))
63
+ image = Img.fromarray(image)
64
+ image = image.convert('L')
65
+ image.save(sampel_path)
66
+
67
+ def load_data(name):
68
+ train_users = []
69
+ train_num_samples = []
70
+ train_data = {}
71
+
72
+ test_users = []
73
+ test_num_samples = []
74
+ test_data = {}
75
+
76
+ parent_path = os.path.dirname(os.path.realpath(__file__))
77
+ data_dir = os.path.join(parent_path, 'dataset', name)
78
+ train_subdir = os.path.join(data_dir, 'train')
79
+ test_subdir = os.path.join(data_dir, 'test')
80
+
81
+ # load train
82
+ train_files = os.listdir(train_subdir)
83
+ train_files = [f for f in train_files if f.endswith('.json')]
84
+
85
+ for index, f in tqdm(enumerate(train_files), desc='Training Data Generating', total=len(train_files)):
86
+ group_name = 'client_' + str(index)
87
+ file_dir = os.path.join(train_subdir, f)
88
+
89
+ with open(file_dir) as inf:
90
+ data = json.load(inf)
91
+
92
+ # show image and print label
93
+ # show_img(data['user_data']['f3242_19']['x'][0])
94
+ # print("Label: " + str(data['user_data']['f3242_19']['y'][0]))
95
+
96
+ # train_users.extend(data['users'])
97
+ train_num_samples.extend([sum(data['num_samples'])])
98
+ gen_data_dict(train_data, data['user_data'], group_name)
99
+ construct_data_dirs_clientwise(data['user_data'], group_name, data_dir, data_type='train')
100
+ construct_data_dirs(data['user_data'], data_dir, data_type='train')
101
+
102
+ # load test
103
+ test_files = os.listdir(test_subdir)
104
+ test_files = [f for f in test_files if f.endswith('.json')]
105
+
106
+ for index, f in tqdm(enumerate(test_files), desc='Testing Data Generating', total=len(test_files)):
107
+ group_name = 'client_' + str(index)
108
+ file_dir = os.path.join(test_subdir, f)
109
+
110
+ with open(file_dir) as inf:
111
+ data = json.load(inf)
112
+
113
+ test_users.extend(data['users'])
114
+ test_num_samples.extend([sum(data['num_samples'])])
115
+ gen_data_dict(test_data, data['user_data'], group_name)
116
+ construct_data_dirs_clientwise(data['user_data'], group_name, data_dir, data_type='test')
117
+ construct_data_dirs(data['user_data'], data_dir, data_type='test')
118
+
119
+ return train_num_samples, train_data, test_num_samples, test_data
120
+
121
+ if __name__ == '__main__':
122
+ name = 'femnist-small'
123
+ train_num_samples, train_data, \
124
+ test_num_samples, test_data = load_data(name)
125
+
126
+ print('####################################')
127
+ print('DATASET: %s' % name)
128
+ print('%d train samples (total)' % np.sum(train_num_samples))
129
+ print('%d test samples (total)' % np.sum(test_num_samples))
130
+ print('%.2f train samples per user (mean)' % np.mean(train_num_samples))
131
+ print('%.2f test samples per user (mean)' % np.mean(test_num_samples))
132
+
133
+