-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathget_predictions.py
More file actions
361 lines (306 loc) · 12.5 KB
/
Copy pathget_predictions.py
File metadata and controls
361 lines (306 loc) · 12.5 KB
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
# Copyright 2020 Google Inc. 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
#
# 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.
# ==============================================================================
import math
import os
import tensorflow as tf
def get_saved_model_serving_signatures(export_name, params):
"""Gets SavedModel's serving signatures for inference.
Args:
export_name: str, name of exported SavedModel.
params: dict, user passed parameters.
Returns:
Loaded SavedModel and its serving signatures for inference.
"""
loaded_model = tf.saved_model.load(
export_dir=os.path.join(
params["output_dir"], "export", export_name
)
)
print("signature_keys = {}".format(list(loaded_model.signatures.keys())))
infer = loaded_model.signatures["serving_default"]
print("structured_outputs = {}".format(infer.structured_outputs))
# Loaded model also needs to be returned so that infer can find the
# variables within the graph in the outer scope.
return loaded_model, infer
def create_export_bool_lists(params):
"""Creates lists of user parameters bools for exporting.
Args:
params: dict, user passed parameters.
Returns:
List of bools relating to the Z serving input and list of bools
relating to the query images serving input.
"""
export_Z_bool_list = [
params["export_Z"],
params["export_generated_images"],
params["export_encoded_generated_logits"],
params["export_encoded_generated_images"]
]
export_query_image_bool_list = [
params["export_query_images"],
params["export_query_encoded_logits"],
params["export_query_encoded_images"],
params["export_query_gen_encoded_logits"],
params["export_query_gen_encoded_images"],
params["export_query_enc_encoded_logits"],
params["export_query_enc_encoded_images"],
params["export_query_anomaly_images_sigmoid"],
params["export_query_anomaly_images_linear"],
params["export_query_mahalanobis_distances"],
params["export_query_mahalanobis_distance_images_sigmoid"],
params["export_query_mahalanobis_distance_images_linear"],
params["export_query_pixel_anomaly_flag_images"],
params["export_query_pixel_anomaly_flag_counts"],
params["export_query_pixel_anomaly_flag_percentages"],
params["export_query_anomaly_scores"],
params["export_query_anomaly_flags"]
]
return export_Z_bool_list, export_query_image_bool_list
def parse_predictions_dict(predictions, num_growths):
"""Parses predictions dictionary to remove graph generated suffixes.
Args:
predictions: dict, predictions dictionary directly from SavedModel
inference call.
num_growths: int, number of model growths contained in export.
Returns:
List of num_growths length of dictionaries with fixed keys and
predictions.
"""
predictions_by_growth = [{} for _ in range(num_growths)]
for k in sorted(predictions.keys()):
key_split = k.split("_")
if key_split[-1].isnumeric() and key_split[-2].isnumeric():
idx = 0 if num_growths == 1 else int(key_split[-2])
predictions_by_growth[idx].update(
{"_".join(key_split[3:-2]): predictions[k]}
)
else:
idx = 0 if num_growths == 1 else int(key_split[-1])
predictions_by_growth[idx].update(
{"_".join(key_split[3:-1]): predictions[k]}
)
del predictions
return predictions_by_growth
def get_current_growth_predictions(export_name, Z, query_images, params):
"""Gets predictions from exported SavedModel for current growth.
Args:
export_name: str, name of exported SavedModel.
Z: tensor, random latent vector of shape
(batch_size, generator_latent_size).
query_images: tensor, real images to query the model with of shape
(batch_size, height, width, num_channels).
params: dict, user passed parameters.
Returns:
List of num_growths length of dictionaries with fixed keys and
predictions.
"""
loaded_model, infer = get_saved_model_serving_signatures(
export_name, params
)
(export_Z_bool_list,
export_query_image_bool_list) = create_export_bool_lists(params)
if query_images is not None:
image_size = query_images.shape[1]
assert(image_size % 2 == 0)
if params["generator_architecture"] == "berg":
if Z is not None and any(export_Z_bool_list):
if query_images is not None and any(export_query_image_bool_list):
kwargs = {
"generator_decoder_inputs": Z,
"encoder_{0}x{0}_inputs".format(image_size): (
query_images
)
}
predictions = infer(**kwargs)
else:
predictions = infer(generator_decoder_inputs=Z)
else:
if query_images is not None and any(export_query_image_bool_list):
kwargs = {
"encoder_{0}x{0}_inputs".format(image_size): (
query_images
)
}
predictions = infer(**kwargs)
else:
print("Nothing was exported, so nothing to infer.")
elif params["generator_architecture"] == "GANomaly":
if query_images is not None and any(export_query_image_bool_list):
kwargs = {
"generator_encoder_{0}x{0}_inputs".format(image_size): (
query_images
)
}
predictions = infer(**kwargs)
predictions_by_growth = parse_predictions_dict(
predictions=predictions, num_growths=1
)
return predictions_by_growth
def get_all_growth_predictions_using_Z_and_query_images_berg(
Z, query_images, max_size, only_output_growth_set, infer
):
"""Gets predictions for all growths using Z and query images.
Args:
Z: tensor, random latent vector of shape
(batch_size, generator_latent_size).
query_images: tensor, real images to query the model with of shape
(batch_size, height, width, num_channels).
max_size: int, the maximum image size within the exported SavedModel.
only_output_growth_set: set, whether to output growth block.
infer: SignatureDef, loaded SavedModel's serving signature def to be
used for inference.
Returns:
Dictionary with exported names for keys and predictions tensors for
values.
"""
assert(max_size % 2 == 0)
num_blocks = int(math.log(max_size, 2)) - 1
kwargs = {"generator_decoder_inputs": Z}
kwargs.update(
{
"encoder_{0}x{0}_inputs".format(4 * 2 ** i): (
tf.image.resize(
images=(
query_images
if i in only_output_growth_set
else query_images[0:0]
),
size=[4 * 2 ** i, 4 * 2 ** i]
)
)
for i in range(num_blocks)
}
)
predictions = infer(**kwargs)
return predictions
def get_all_growth_predictions_using_query_images_berg(
query_images, max_size, only_output_growth_set, infer
):
"""Gets predictions for all growths using query images.
Args:
query_images: tensor, real images to query the model with of shape
(batch_size, height, width, num_channels).
max_size: int, the maximum image size within the exported SavedModel.
only_output_growth_set: set, whether to output growth block.
infer: SignatureDef, loaded SavedModel's serving signature def to be
used for inference.
Returns:
Dictionary with exported names for keys and predictions tensors for
values.
"""
assert(max_size % 2 == 0)
num_blocks = int(math.log(max_size, 2)) - 1
kwargs = {
"encoder_{0}x{0}_inputs".format(4 * 2 ** i): (
tf.image.resize(
images=(
query_images
if i in only_output_growth_set
else query_images[0:0]
),
size=[4 * 2 ** i, 4 * 2 ** i]
)
)
for i in range(num_blocks)
}
predictions = infer(**kwargs)
return predictions
def get_all_growth_predictions_using_query_images_ganomaly(
query_images, max_size, only_output_growth_set, infer
):
"""Gets predictions for all growths using query images.
Args:
query_images: tensor, real images to query the model with of shape
(batch_size, height, width, num_channels).
max_size: int, the maximum image size within the exported SavedModel.
only_output_growth_set: set, whether to output growth block.
infer: SignatureDef, loaded SavedModel's serving signature def to be
used for inference.
Returns:
Dictionary with exported names for keys and predictions tensors for
values.
"""
assert(max_size % 2 == 0)
num_blocks = int(math.log(max_size, 2)) - 1
kwargs = {
"generator_encoder_{0}x{0}_inputs".format(4 * 2 ** i): (
tf.image.resize(
images=(
query_images
if i in only_output_growth_set
else query_images[0:0]
),
size=[4 * 2 ** i, 4 * 2 ** i]
)
)
for i in range(num_blocks)
}
predictions = infer(**kwargs)
return predictions
def get_all_growth_predictions(
export_name, Z, query_images, max_size, only_output_growth_set, params
):
"""Gets predictions for all growths from exported SavedModel.
Args:
export_name: str, name of exported SavedModel.
Z: tensor, random latent vector of shape
(batch_size, generator_latent_size).
query_images: tensor, real images to query the model with of shape
(batch_size, height, width, num_channels).
max_size: int, the maximum image size within the exported SavedModel.
only_output_growth_set: set, whether to output growth block.
params: dict, user passed parameters.
Returns:
List of num_growths length of dictionaries with fixed keys and
predictions.
"""
loaded_model, infer = get_saved_model_serving_signatures(
export_name, params
)
(export_Z_bool_list,
export_query_image_bool_list) = create_export_bool_lists(params)
if params["generator_architecture"] == "berg":
if Z is not None and any(export_Z_bool_list):
if query_images is not None and any(export_query_image_bool_list):
predictions = (
get_all_growth_predictions_using_Z_and_query_images_berg(
Z, query_images, max_size, only_output_growth_set, infer
)
)
else:
predictions = infer(generator_inputs=Z)
else:
if query_images is not None and any(export_query_image_bool_list):
predictions = (
get_all_growth_predictions_using_query_images_berg(
query_images, max_size, only_output_growth_set, infer
)
)
else:
print("Nothing was exported, so nothing to infer.")
elif params["generator_architecture"] == "GANomaly":
if query_images is not None and any(export_query_image_bool_list):
predictions = (
get_all_growth_predictions_using_query_images_ganomaly(
query_images, max_size, only_output_growth_set, infer
)
)
else:
print("Nothing was exported, so nothing to infer.")
predictions_by_growth = parse_predictions_dict(
predictions=predictions,
num_growths=(int(math.log(max_size, 2)) - 2) * 2 + 1
)
return predictions_by_growth