/
features_dict.py
322 lines (269 loc) · 9.86 KB
/
features_dict.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
# coding=utf-8
# Copyright 2023 The TensorFlow Datasets Authors.
#
# 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.
"""FeatureDict: Main feature connector container."""
from __future__ import annotations
import concurrent.futures
from typing import Dict, List, Union
from tensorflow_datasets.core import utils
from tensorflow_datasets.core.features import feature as feature_lib
from tensorflow_datasets.core.features import tensor_feature
from tensorflow_datasets.core.features import top_level_feature
from tensorflow_datasets.core.proto import feature_pb2
from tensorflow_datasets.core.utils import dtype_utils
from tensorflow_datasets.core.utils import py_utils
from tensorflow_datasets.core.utils import type_utils
Json = type_utils.Json
WORKER_COUNT = 16
class _DictGetCounter(object):
"""Wraps dict.get and counts successful key accesses."""
def __init__(self, d):
self.count = 0
self.wrapped_mapping = d
def get(self, key: str):
if self.wrapped_mapping and key in self.wrapped_mapping:
self.count += 1
return self.wrapped_mapping[key]
return None
class FeaturesDict(top_level_feature.TopLevelFeature):
"""Composite `FeatureConnector`; each feature in `dict` has its own connector.
The encode/decode method of the spec feature will recursively encode/decode
every sub-connector given on the constructor.
Other features can inherit from this class and call super() in order to get
nested container.
Example:
For DatasetInfo:
```
features = tfds.features.FeaturesDict({
'input': tfds.features.Image(),
'output': np.int32,
})
```
At generation time:
```
for image, label in generate_examples:
yield {
'input': image,
'output': label
}
```
At tf.data.Dataset() time:
```
for example in tfds.load(...):
tf_input = example['input']
tf_output = example['output']
```
For nested features, the FeaturesDict will internally flatten the keys for the
features and the conversion to tf.train.Example. Indeed, the tf.train.Example
proto do not support nested features while tf.data.Dataset does.
But internal transformation should be invisible to the user.
Example:
```
tfds.features.FeaturesDict({
'input': np.int32,
'target': {
'height': np.int32,
'width': np.int32,
},
})
```
Will internally store the data as:
```
{
'input': tf.io.FixedLenFeature(shape=(), dtype=tf.int32),
'target/height': tf.io.FixedLenFeature(shape=(), dtype=tf.int32),
'target/width': tf.io.FixedLenFeature(shape=(), dtype=tf.int32),
}
```
"""
def __init__(
self,
feature_dict: Dict[str, feature_lib.FeatureConnectorArg],
*,
doc: feature_lib.DocArg = None,
):
"""Initialize the features.
Args:
feature_dict (dict): Dictionary containing the feature connectors of a
example. The keys should correspond to the data dict as returned by
tf.data.Dataset(). Types (np.int32,...) and dicts will automatically be
converted into FeatureConnector.
doc: Documentation of this feature (e.g. description).
Raises:
ValueError: If one of the given features is not recognized
"""
super(FeaturesDict, self).__init__(doc=doc)
self._feature_dict = {k: to_feature(v) for k, v in feature_dict.items()}
# Dict functions.
# In Python 3, should inherit from collections.abc.Mapping().
def keys(self):
return self._feature_dict.keys()
def items(self):
return self._feature_dict.items()
def values(self):
return self._feature_dict.values()
def __contains__(self, k):
return k in self._feature_dict
def __getitem__(self, key):
"""Return the feature associated with the key."""
return self._feature_dict[key]
def __len__(self):
return len(self._feature_dict)
def __iter__(self):
return iter(self._feature_dict)
# Feature functions
def __repr__(self):
"""Display the feature dictionary."""
lines = ['{}({{'.format(type(self).__name__)]
# Add indentation
for key, feature in sorted(list(self._feature_dict.items())):
feature_repr = tensor_feature.get_inner_feature_repr(feature)
all_sub_lines = "'{}': {},".format(key, feature_repr)
lines.extend(' ' + l for l in all_sub_lines.split('\n'))
lines.append('})')
return '\n'.join(lines)
def catalog_documentation(
self,
) -> List[feature_lib.CatalogFeatureDocumentation]:
feature_docs = [
feature_lib.CatalogFeatureDocumentation(
name='',
cls_name=type(self).__name__,
tensor_info=None,
description=self._doc.desc,
value_range=self._doc.value_range,
)
]
for feature_name, feature in sorted(list(self._feature_dict.items())):
for documentation in feature.catalog_documentation():
if documentation.name:
nested_name = f'{feature_name}/{documentation.name}'
else:
nested_name = feature_name
feature_docs.append(documentation.replace(name=nested_name))
return feature_docs
@py_utils.memoize()
def get_tensor_info(self):
"""See base class for details."""
return {
feature_key: feature.get_tensor_info()
for feature_key, feature in self._feature_dict.items()
}
@py_utils.memoize()
def get_serialized_info(self):
"""See base class for details."""
return {
feature_key: feature.get_serialized_info()
for feature_key, feature in self._feature_dict.items()
}
@classmethod
def from_json_content(
cls, value: Union[Json, feature_pb2.FeaturesDict]
) -> 'FeaturesDict':
if isinstance(value, dict):
features = {
k: feature_lib.FeatureConnector.from_json(v) for k, v in value.items()
}
else:
features = {
name: feature_lib.FeatureConnector.from_proto(proto)
for name, proto in value.features.items()
}
return cls(features)
def to_json_content(self) -> feature_pb2.FeaturesDict:
return feature_pb2.FeaturesDict(
features={
feature_key: feature.to_proto()
for feature_key, feature in self._feature_dict.items()
},
)
def encode_example(self, example_dict):
"""See base class for details."""
example = {}
for k, (feature, example_value) in utils.zip_dict(
self._feature_dict, example_dict
):
try:
example[k] = feature.encode_example(example_value)
except Exception as e: # pylint: disable=broad-except
utils.reraise(
e, prefix=f'In <{feature.__class__.__name__}> with name "{k}":\n'
)
return example
def _flatten(self, x):
"""See base class for details."""
if x and not isinstance(x, (dict, FeaturesDict)):
raise ValueError(
'Error while flattening dict: FeaturesDict received a non dict item: '
'{}'.format(x)
)
dict_counter = _DictGetCounter(x)
out = []
for k, f in sorted(self.items()):
out.extend(f._flatten(dict_counter.get(k))) # pylint: disable=protected-access
if x and dict_counter.count != len(x):
raise ValueError(
'Error while flattening dict: Not all dict items have been consumed, '
'this means that the provided dict structure does not match the '
'`FeatureDict`. Please check for typos in the key names. '
'Available keys: {}. Unrecognized keys: {}'.format(
list(self.keys()), list(set(x.keys()) - set(self.keys()))
)
)
return out
def _nest(self, list_x):
"""See base class for details."""
curr_pos = 0
out = {}
for k, f in sorted(self.items()):
offset = len(f._flatten(None)) # pylint: disable=protected-access
out[k] = f._nest(list_x[curr_pos : curr_pos + offset]) # pylint: disable=protected-access
curr_pos += offset
if curr_pos != len(list_x):
raise ValueError(
'Error while nesting: Expected length {} does not match input '
'length {} of {}'.format(curr_pos, len(list_x), list_x)
)
return out
def save_metadata(self, data_dir, feature_name=None):
"""See base class for details."""
# Recursively save all child features
for child_name, feature in self._feature_dict.items():
name_for_file = feature_lib.convert_feature_name_to_filename(
feature_name=child_name, parent_name=feature_name
)
feature.save_metadata(data_dir, feature_name=name_for_file)
def load_metadata(self, data_dir, feature_name=None):
"""See base class for details."""
# Load all child features asynchronously
def load_metadata(feature_item):
child_name, feature = feature_item
name_for_file = feature_lib.convert_feature_name_to_filename(
feature_name=child_name, parent_name=feature_name
)
feature.load_metadata(data_dir, feature_name=name_for_file)
with concurrent.futures.ThreadPoolExecutor(
max_workers=WORKER_COUNT
) as executor:
executor.map(load_metadata, self._feature_dict.items())
def to_feature(value: feature_lib.FeatureConnectorArg):
"""Convert the given value to Feature if necessary."""
if isinstance(value, feature_lib.FeatureConnector):
return value
elif dtype_utils.is_np_or_tf_dtype(value): # tf.int32, np.int32,...
return tensor_feature.Tensor(shape=(), dtype=value)
elif isinstance(value, dict):
return FeaturesDict(value)
else:
raise ValueError('Feature not supported: {}'.format(value))