-
Notifications
You must be signed in to change notification settings - Fork 196
/
emnist_dataset.py
214 lines (180 loc) · 8.73 KB
/
emnist_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
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
# Copyright 2019, Google LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Library for loading and preprocessing EMNIST training and testing data."""
from typing import Tuple
import tensorflow as tf
import tensorflow_federated as tff
MAX_CLIENT_DATASET_SIZE = 418
def _reshape_for_digit_recognition(element):
return (tf.expand_dims(element['pixels'], axis=-1), element['label'])
def _reshape_for_autoencoder(element):
x = 1 - tf.reshape(element['pixels'], (-1, 28 * 28))
return (x, x)
def create_preprocess_fn(
num_epochs: int,
batch_size: int,
shuffle_buffer_size: int = MAX_CLIENT_DATASET_SIZE,
emnist_task: str = 'digit_recognition',
num_parallel_calls: tf.Tensor = tf.data.experimental.AUTOTUNE
) -> tff.Computation:
"""Creates a preprocessing function for EMNIST client datasets.
The preprocessing shuffles, repeats, batches, and then reshapes, using
the `shuffle`, `repeat`, `batch`, and `map` attributes of a
`tf.data.Dataset`, in that order.
Args:
num_epochs: An integer representing the number of epochs to repeat the
client datasets.
batch_size: An integer representing the batch size on clients.
shuffle_buffer_size: An integer representing the shuffle buffer size on
clients. If set to a number <= 1, no shuffling occurs.
emnist_task: A string indicating the EMNIST task being performed. Must be
one of 'digit_recognition' or 'autoencoder'. If the former, then elements
are mapped to tuples of the form (pixels, label), if the latter then
elements are mapped to tuples of the form (pixels, pixels).
num_parallel_calls: An integer representing the number of parallel calls
used when performing `tf.data.Dataset.map`.
Returns:
A callable performing the preprocessing discussed above.
"""
if num_epochs < 1:
raise ValueError('num_epochs must be a positive integer.')
if shuffle_buffer_size <= 1:
shuffle_buffer_size = 1
if emnist_task == 'digit_recognition':
mapping_fn = _reshape_for_digit_recognition
elif emnist_task == 'autoencoder':
mapping_fn = _reshape_for_autoencoder
else:
raise ValueError('emnist_task must be one of "digit_recognition" or '
'"autoencoder".')
def preprocess_fn(dataset):
return dataset.shuffle(shuffle_buffer_size).repeat(num_epochs).batch(
batch_size, drop_remainder=False).map(
mapping_fn, num_parallel_calls=num_parallel_calls)
return preprocess_fn # pytype: disable=bad-return-type
def get_federated_datasets(
train_client_batch_size: int = 20,
test_client_batch_size: int = 100,
train_client_epochs_per_round: int = 1,
test_client_epochs_per_round: int = 1,
train_shuffle_buffer_size: int = MAX_CLIENT_DATASET_SIZE,
test_shuffle_buffer_size: int = 1,
only_digits: bool = False,
emnist_task: str = 'digit_recognition'
) -> Tuple[tff.simulation.datasets.ClientData,
tff.simulation.datasets.ClientData]:
"""Loads and preprocesses federated EMNIST training and testing sets.
Args:
train_client_batch_size: The batch size for all train clients.
test_client_batch_size: The batch size for all test clients.
train_client_epochs_per_round: The number of epochs each train client should
iterate over their local dataset, via `tf.data.Dataset.repeat`. Must be
set to a positive integer.
test_client_epochs_per_round: The number of epochs each test client should
iterate over their local dataset, via `tf.data.Dataset.repeat`. Must be
set to a positive integer.
train_shuffle_buffer_size: An integer representing the shuffle buffer size
(as in `tf.data.Dataset.shuffle`) for each train client's dataset. By
default, this is set to the largest dataset size among all clients. If set
to some integer less than or equal to 1, no shuffling occurs.
test_shuffle_buffer_size: An integer representing the shuffle buffer size
(as in `tf.data.Dataset.shuffle`) for each test client's dataset. If set
to some integer less than or equal to 1, no shuffling occurs.
only_digits: A boolean representing whether to take the digits-only
EMNIST-10 (with only 10 labels) or the full EMNIST-62 dataset with digits
and characters (62 labels). If set to True, we use EMNIST-10, otherwise we
use EMNIST-62.
emnist_task: A string indicating the EMNIST task being performed. Must be
one of 'digit_recognition' or 'autoencoder'. If the former, then elements
are mapped to tuples of the form (pixels, label), if the latter then
elements are mapped to tuples of the form (pixels, pixels).
Returns:
A tuple (emnist_train, emnist_test) of `tff.simulation.datasets.ClientData`
instances representing the federated training and test datasets.
"""
if train_client_epochs_per_round < 1:
raise ValueError(
'train_client_epochs_per_round must be a positive integer.')
if test_client_epochs_per_round < 0:
raise ValueError('test_client_epochs_per_round must be a positive integer.')
if train_shuffle_buffer_size <= 1:
train_shuffle_buffer_size = 1
if test_shuffle_buffer_size <= 1:
test_shuffle_buffer_size = 1
emnist_train, emnist_test = tff.simulation.datasets.emnist.load_data(
only_digits=only_digits)
train_preprocess_fn = create_preprocess_fn(
num_epochs=train_client_epochs_per_round,
batch_size=train_client_batch_size,
shuffle_buffer_size=train_shuffle_buffer_size,
emnist_task=emnist_task)
test_preprocess_fn = create_preprocess_fn(
num_epochs=test_client_epochs_per_round,
batch_size=test_client_batch_size,
shuffle_buffer_size=test_shuffle_buffer_size,
emnist_task=emnist_task)
emnist_train = emnist_train.preprocess(train_preprocess_fn)
emnist_test = emnist_test.preprocess(test_preprocess_fn)
return emnist_train, emnist_test
def get_centralized_datasets(
train_batch_size: int = 20,
test_batch_size: int = 500,
train_shuffle_buffer_size: int = 10000,
test_shuffle_buffer_size: int = 1,
only_digits: bool = False,
emnist_task: str = 'digit_recognition'
) -> Tuple[tf.data.Dataset, tf.data.Dataset]:
"""Loads and preprocesses centralized EMNIST training and testing sets.
Args:
train_batch_size: The batch size for the training dataset.
test_batch_size: The batch size for the test dataset.
train_shuffle_buffer_size: An integer specifying the buffer size used to
shuffle the train dataset via `tf.data.Dataset.shuffle`. If set to an
integer less than or equal to 1, no shuffling occurs.
test_shuffle_buffer_size: An integer specifying the buffer size used to
shuffle the test dataset via `tf.data.Dataset.shuffle`. If set to an
integer less than or equal to 1, no shuffling occurs.
only_digits: A boolean representing whether to take the digits-only
EMNIST-10 (with only 10 labels) or the full EMNIST-62 dataset with digits
and characters (62 labels). If set to True, we use EMNIST-10, otherwise we
use EMNIST-62.
emnist_task: A string indicating the EMNIST task being performed. Must be
one of 'digit_recognition' or 'autoencoder'. If the former, then elements
are mapped to tuples of the form (pixels, label), if the latter then
elements are mapped to tuples of the form (pixels, pixels).
Returns:
A tuple (train_dataset, test_dataset) of `tf.data.Dataset` instances
representing the centralized training and test datasets.
"""
if train_shuffle_buffer_size <= 1:
train_shuffle_buffer_size = 1
if test_shuffle_buffer_size <= 1:
test_shuffle_buffer_size = 1
emnist_train, emnist_test = tff.simulation.datasets.emnist.load_data(
only_digits=only_digits)
emnist_train = emnist_train.create_tf_dataset_from_all_clients()
emnist_test = emnist_test.create_tf_dataset_from_all_clients()
train_preprocess_fn = create_preprocess_fn(
num_epochs=1,
batch_size=train_batch_size,
shuffle_buffer_size=train_shuffle_buffer_size,
emnist_task=emnist_task)
test_preprocess_fn = create_preprocess_fn(
num_epochs=1,
batch_size=test_batch_size,
shuffle_buffer_size=test_shuffle_buffer_size,
emnist_task=emnist_task)
emnist_train = train_preprocess_fn(emnist_train)
emnist_test = test_preprocess_fn(emnist_test)
return emnist_train, emnist_test