-
Notifications
You must be signed in to change notification settings - Fork 2
/
features.py
379 lines (302 loc) · 11.1 KB
/
features.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
# Copyright 2020 Johns Hopkins University. All Rights Reserved.
#
# 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
#
# https://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.
# =============================================================================
import json
from pprint import pformat
from glob import glob
from enum import Enum
from absl import logging
import tensorflow as tf
import numpy as np
class F(Enum):
SYMBOLS = "syms"
NUM_SYMBOLS_PER_POST = "lens"
NUM_POSTS = "num_posts"
ACTION_TYPE = "action_type"
AUTHOR_ID = "author_id"
HOUR = "hour"
FEATURE_SHAPE = {
F.SYMBOLS: [None],
F.NUM_SYMBOLS_PER_POST: [None],
F.NUM_POSTS: [None],
F.AUTHOR_ID: [None],
F.ACTION_TYPE: [None],
F.HOUR: [None]
}
FEATURE_FORMAT = {
F.SYMBOLS: tf.io.FixedLenSequenceFeature(
[], dtype=tf.int64),
F.NUM_SYMBOLS_PER_POST: tf.io.FixedLenSequenceFeature(
[], dtype=tf.int64),
F.NUM_POSTS: tf.io.FixedLenFeature([], dtype=tf.int64),
F.AUTHOR_ID: tf.io.FixedLenFeature([], dtype=tf.int64),
F.ACTION_TYPE: tf.io.FixedLenSequenceFeature([], dtype=tf.int64),
F.HOUR: tf.io.FixedLenSequenceFeature([], dtype=tf.int64)
}
FEATURE_TYPE = {
F.SYMBOLS: tf.int64,
F.NUM_SYMBOLS_PER_POST: tf.int64,
F.NUM_POSTS: tf.int64,
F.AUTHOR_ID: tf.int64,
F.ACTION_TYPE: tf.int64,
F.HOUR: tf.int64
}
SEQUENCE_FEATURES = set([
F.SYMBOLS,
F.NUM_SYMBOLS_PER_POST,
F.ACTION_TYPE,
F.HOUR
])
def get_feature_shape(feature):
if feature in FEATURE_SHAPE:
return FEATURE_SHAPE[feature]
raise ValueError(
(f"{feature} shape information not defined. "
f"Add feature shape to `FEATURE_SHAPE` dictionary."))
def get_feature_format(feature):
if feature in FEATURE_FORMAT:
return FEATURE_FORMAT[feature]
raise ValueError(
(f"{feature} format information not defined. "
f"Add feature format to `FEATURE_FORMAT` dictionary."))
def get_feature_type(feature):
if feature in FEATURE_TYPE:
return FEATURE_TYPE[feature]
raise ValueError(
(f"{feature} type information not defined. "
f"Add feature type to `FEATURE_TYPE` dictionary."))
def is_sequence_feature(feature):
if isinstance(feature, str):
feature = F(feature)
return feature in SEQUENCE_FEATURES
def _parse(features, sep=','):
if isinstance(features, str):
feature_set = {F[f] for f in features.split(sep)}
elif isinstance(features, F):
feature_set = set([features])
elif isinstance(features, set) or isinstance(features, list):
feature_set = set()
for feature in features:
if isinstance(feature, F):
feature_set.add(feature)
if isinstance(feature, str):
try:
feature_set.add(F(feature))
except KeyError:
print(f"{feature} not in F")
raise
else:
raise ValueError(features)
if not feature_set:
raise ValueError(features)
return feature_set
def _feature_type(features):
""" Return feature types as a dict with string keys """
return {f.value: get_feature_type(f) for f in features}
def _feature_format(features):
""" Return feature formats as a dict with string keys """
return {f.value: get_feature_format(f) for f in features}
def _feature_shape(features):
""" Return feature shapes as a dict with string keys """
return {f.value: get_feature_shape(f) for f in features}
class FeatureConfig:
""" A `FeatureConfig` describes the `Features` of a problem
and should capture sufficient information to serialize
and deserialize data from protobufs.
"""
def __init__(self, *, context_features, sequence_features,
label_feature, padded_length,
num_symbols, num_action_types):
"""
Arguments:
context_features: `str`, `set`, or `list` of features.
sequence_features: `str`, `set`, or `list` of features.
label_feature: Feature associated with the label.
padded_length: Length to which symbols are padded.
num_symbols: Number of subwords in the vocabulary.
num_action_types: Number of action types (e.g. subreddits).
"""
self._context_features = _parse(context_features)
self._sequence_features = _parse(sequence_features)
if isinstance(label_feature, str):
label_feature = F(label_feature)
self._label_feature = F(label_feature)
self._padded_length = padded_length
self._num_symbols = num_symbols
self._num_action_types = num_action_types
def to_dict(self):
return {
"context_features": [x.value for x in self.context_features],
"sequence_features": [x.value for x in self.sequence_features],
"label_feature": self.label_feature.value,
"padded_length": self.padded_length,
"num_symbols": self.num_symbols,
"num_action_types": self.num_action_types
}
def save_as_json(self, path):
with open(path, "w") as write_file:
setting_as_dict = self.to_dict()
json.dump(setting_as_dict, write_file, indent=4)
@classmethod
def from_json(cls, path):
with open(path) as fp:
json_contents = json.load(fp)
return cls(**json_contents)
def __str__(self):
return pformat(self.to_dict())
@property
def context_features(self):
return self._context_features
@property
def sequence_features(self):
return self._sequence_features
@property
def label_feature(self):
return self._label_feature
@property
def padded_length(self):
return self._padded_length
@property
def num_symbols(self):
return self._num_symbols
@property
def num_action_types(self):
return self._num_action_types
@property
def features(self):
return self.context_features | self.sequence_features
@property
def length_feature(self):
return F.NUM_POSTS.value
@property
def shape(self):
label_shape = get_feature_shape(self.label_feature)
feature_shape_list = []
for f in self.features:
if f is F.SYMBOLS:
feature_shape_list.append((f.value, (None, self.padded_length)))
else:
feature_shape_list.append((f.value, get_feature_shape(f)))
feature_shape_dict = dict(feature_shape_list)
del feature_shape_dict[self.label_feature.value]
return feature_shape_dict, label_shape
@property
def parse_single_example_fn(self):
context_format = _feature_format(self.context_features)
sequence_format = _feature_format(self.sequence_features)
def data_map_fn(serialized_example):
features = tf.io.parse_single_sequence_example(
serialized_example, context_features=context_format,
sequence_features=sequence_format)
# Flatten the context and sequence features
feature_dict = {}
for f, v in features[0].items():
feature_dict[f] = v
for f, v in features[1].items():
assert f not in feature_dict
feature_dict[f] = v
# Unpack serialized symbols, padding documents to fixed length.
# When `RaggedTensor` become first-class citizens, this may
# be simplified to just passing along the ragged tensor object
# directly.
assert F.SYMBOLS.value in feature_dict
assert F.NUM_SYMBOLS_PER_POST.value in feature_dict
values = feature_dict[F.SYMBOLS.value]
lengths = feature_dict[F.NUM_SYMBOLS_PER_POST.value]
rt = tf.RaggedTensor.from_row_lengths(values, lengths)
dt = rt.to_tensor()
paddings = [[0, 0], [0, self.padded_length-tf.shape(dt)[1]]]
padded_t = tf.pad(dt, paddings, 'CONSTANT', constant_values=0)
feature_dict[F.SYMBOLS.value] = padded_t
labels = feature_dict[self.label_feature.value]
return feature_dict, labels
return data_map_fn
def make_sequence_example(context_features, sequence_features):
def _floats_to_feature_list(values):
return [
tf.train.Feature(float_list=tf.train.FloatList(value=value))
for value in values]
def _ints_to_feature_list(values):
ret = []
for value in values:
if isinstance(value, int) or isinstance(value, np.int64):
value = [value]
ret.append(tf.train.Feature(int64_list=tf.train.Int64List(value=value)))
return ret
def _values_to_feature_list(feature, values):
if get_feature_type(feature) == tf.int64:
return _ints_to_feature_list(values)
if get_feature_type(feature) == tf.float32:
return _floats_to_feature_list(values)
raise ValueError(feature)
def _int_to_feature(value):
return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
feature = {
f.value: _int_to_feature(v) for f, v in context_features.items()}
feature_list = {
f.value: tf.train.FeatureList(feature=_values_to_feature_list(f, v))
for f, v in sequence_features.items()}
for feat in sequence_features.keys():
assert feat.value in feature_list
for feat in context_features.keys():
assert feat.value in feature
example = tf.train.SequenceExample(
feature_lists=tf.train.FeatureLists(feature_list=feature_list),
context=tf.train.Features(feature=feature))
return example
def tfrecord_dataset(input_file_pattern, config, compression_type=None):
"""
Arguments
input_file_pattern: Regex matching input tfrecord files.
config: `FeatureConfig` instance
compression_type: (Optional.) A tf.string scalar evaluating to one
of "" (no compression), "ZLIB", or "GZIP".
Returns: tf.data.Dataset
"""
filenames = tf.data.Dataset.list_files(input_file_pattern)
dataset = tf.data.TFRecordDataset(filenames,
compression_type=compression_type)
return dataset.map(
config.parse_single_example_fn,
num_parallel_calls=tf.data.experimental.AUTOTUNE)
def write_tfrecords_from_generator(tfrecord_path, setting, generator,
shard_size=5000):
""" Arguments
tfrecord_path: Prefix for output TFRecord files.
setting: `FeatureConfig` instance
generator: Python generator yielding episodes of user actions.
shard_size (5000): How many examples to store per TFRecord file.
"""
shard = 0
# Continue writing examples until we run out of authors, sharding the
# TFRecords into multiple files with `shard_size` authors per shard.
while True:
shard_path = tfrecord_path + '.{:03d}'.format(shard) + '.tf'
with tf.io.TFRecordWriter(shard_path) as writer:
logging.info(f"Writing {shard_path}")
for _ in range(shard_size):
try:
episode = next(generator)
features, label = episode
context_features = {
k: features[k.value] for k in setting.context_features}
sequence_features = {
k: features[k.value] for k in setting.sequence_features}
example = make_sequence_example(
context_features,
sequence_features)
writer.write(example.SerializeToString())
except StopIteration:
return
shard += 1