-
Notifications
You must be signed in to change notification settings - Fork 2
/
inference.py
1837 lines (1630 loc) · 73.3 KB
/
inference.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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# 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 apache_beam as beam
from apache_beam.io.gcp import gcsio
from collections import defaultdict
import cv2
import math
import matplotlib.pyplot as plt
import openslide
import os
import numpy as np
import tensorflow as tf
class InferenceDoFn(beam.DoFn):
"""ParDo class that performs inference on image patch.
Attributes:
wsi_stitch_gcs_path: str, GCS path of WSI file.
patch_height: int, the height in pixels of an image patch.
patch_width: int, the width in pixels of an image patch.
patch_depth: int, the number of channels of an image patch.
gan_export_dir: str, directory where the exported trained SavedModel
resides.
gan_export_name: str, name of exported trained SavedModel folder.
generator_architecture: str, name of generator architecture, either
'berg' or 'GANomaly'.
berg_use_Z_inputs: bool, for berg architecture, whether to use Z
inputs. Query image inputs are always used.
berg_latent_size: int, for berg architecture, the latent size of the
noise vector.
berg_latent_mean: float, for berg architecture, the latent vector's
random normal mean.
berg_latent_stddev: float, for berg architecture, the latent vector's
random normal standard deviation.
image_stitch_types_set: set, strings of which image types to stitch.
bandwidth: float, the bandwidth of the kernel.
kernel: str, the kernel to use for density estimation.
metric: str, the distance metric to use. Note that not all metrics
are valid with all algorithms.
xbins: int, number of sample bins to create in the x dimension.
ybins: int, number of sample bins to create in the y dimension.
min_neighborhood_count: int, minimum number of adjacent points as
not to be removed from image.
connectivity: int, connectivity defining the neighborhood of a pixel.
min_anomaly_points_remaining: int, minimum number of anomaly points
following removing small objects to not clear all flags.
scaling_power: float, the exponent to use for scaling.
scaling_factor: float, positive factor to scale anomaly flag
counts by.
cmap_str: str, which color map to use.
kde_threshold: float, threshold to convert KDE grayscale image into
binary mask.
annotation_patch_gcs_filepath: str, GCS path where annotation patch
images are stored.
num_confusion_matrix_thresholds: int, number of thresholds to
calculate confusion matrix metrics over for comparing binary KDE
masks with annotations.
custom_mahalanobis_distance_threshold: float, threshold to override
learned Mahalanobis distance threshold from SavedModel for
creating Mahalanobis binary mask.
segmentation_coord_types_set: set, strings of which segmentation types
to output.
segmentation_export_dir: str, directory containing exported
segmentation models.
segmentation_model_name: str, name of segmentation model.
segmentation_patch_size: int, size of each patch of image for
segmentation model.
segmentation_stride: int, number of pixels to skip for each patch of
image for segmentation model.
segmentation_median_blur_image: bool, whether to median blur images
before segmentation.
segmentation_median_blur_kernel_size: int, kernel size of median blur
for segmentation.
segmentation_group_size: int, number of patches to include in a group
for segmentation.
"""
def __init__(
self,
wsi_stitch_gcs_path,
patch_height,
patch_width,
patch_depth,
gan_export_dir,
gan_export_name,
generator_architecture,
berg_use_Z_inputs,
berg_latent_size,
berg_latent_mean,
berg_latent_stddev,
image_stitch_types_set,
bandwidth,
kernel,
metric,
xbins,
ybins,
min_neighborhood_count,
connectivity,
min_anomaly_points_remaining,
scaling_power,
scaling_factor,
cmap_str,
kde_threshold,
annotation_patch_gcs_filepath,
num_confusion_matrix_thresholds,
custom_mahalanobis_distance_threshold,
segmentation_coord_types_set,
segmentation_export_dir,
segmentation_model_name,
segmentation_patch_size,
segmentation_stride,
segmentation_median_blur_image,
segmentation_median_blur_kernel_size,
segmentation_group_size
):
"""Constructor of ParDo class that performs inference on image patch.
Args:
wsi_stitch_gcs_path: str, GCS path of WSI file.
patch_height: int, the height in pixels of an image patch.
patch_width: int, the width in pixels of an image patch.
patch_depth: int, the number of channels of an image patch.
gan_export_dir: str, directory where the exported trained
SavedModel resides.
gan_export_name: str, name of exported trained SavedModel folder.
generator_architecture: str, name of generator architecture,
either 'berg' or 'GANomaly'.
berg_use_Z_inputs: bool, for berg architecture, whether to use Z
inputs. Query image inputs are always used.
berg_latent_size: int, for berg architecture, the latent size of
the noise vector.
berg_latent_mean: float, for berg architecture, the latent
vector's random normal mean.
berg_latent_stddev: float, for berg architecture, the latent
vector's random normal standard deviation.
image_stitch_types_set: set, strings of which image types to
stitch.
bandwidth: float, the bandwidth of the kernel.
kernel: str, the kernel to use for density estimation.
metric: str, the distance metric to use. Note that not all metrics
are valid with all algorithms.
xbins: int, number of sample bins to create in the x dimension.
ybins: int, number of sample bins to create in the y dimension.
min_neighborhood_count: int, minimum number of adjacent points as
not to be removed from image.
connectivity: int, connectivity defining the neighborhood of a
pixel.
min_anomaly_points_remaining: int, minimum number of anomaly
points following removing small objects to not clear all
flags.
scaling_power: float, the exponent to use for scaling.
scaling_factor: float, positive factor to scale anomaly flag
counts by.
cmap_str: str, which color map to use.
kde_threshold: float, threshold to convert KDE grayscale image
into binary mask.
annotation_patch_gcs_filepath: str, GCS path where annotation
patch images are stored.
num_confusion_matrix_thresholds: int, number of thresholds to
calculate confusion matrix metrics over for comparing binary
KDE masks with annotations.
custom_mahalanobis_distance_threshold: float, threshold to
override learned Mahalanobis distance threshold from
SavedModel for creating Mahalanobis binary mask.
segmentation_coord_types_set: set, strings of which segmentation
types to output.
segmentation_export_dir: str, directory containing exported
segmentation models.
segmentation_model_name: str, name of segmentation model.
segmentation_patch_size: int, size of each patch of image for
segmentation model.
segmentation_stride: int, number of pixels to skip for each patch
of image for segmentation model.
segmentation_median_blur_image: bool, whether to median blur
images before segmentation.
segmentation_median_blur_kernel_size: int, kernel size of median
blur for segmentation.
segmentation_group_size: int, number of patches to include in a
group for segmentation.
"""
self.wsi_stitch_gcs_path = wsi_stitch_gcs_path
self.patch_height = patch_height
self.patch_width = patch_width
self.patch_depth = patch_depth
self.gan_export_dir = gan_export_dir
self.gan_export_name = gan_export_name
self.generator_architecture = generator_architecture
self.berg_use_Z_inputs = berg_use_Z_inputs
self.berg_latent_size = berg_latent_size
self.berg_latent_mean = berg_latent_mean
self.berg_latent_stddev = berg_latent_stddev
self.image_stitch_types_set = image_stitch_types_set
self.bandwidth = bandwidth
self.kernel = kernel
self.metric = metric
self.xbins = xbins
self.ybins = ybins
self.min_neighborhood_count = min_neighborhood_count
self.connectivity = connectivity
self.min_anomaly_points_remaining = (
min_anomaly_points_remaining
)
self.scaling_power = scaling_power
self.scaling_factor = scaling_factor
self.cmap_str = cmap_str
self.kde_threshold = kde_threshold
self.annotation_patch_gcs_filepath = annotation_patch_gcs_filepath
self.num_confusion_matrix_thresholds = num_confusion_matrix_thresholds
self.custom_mahalanobis_distance_threshold = (
custom_mahalanobis_distance_threshold
)
self.segmentation_coord_types_set = segmentation_coord_types_set
self.segmentation_export_dir = segmentation_export_dir
self.segmentation_model_name = segmentation_model_name
self.segmentation_patch_size = segmentation_patch_size
self.segmentation_stride = segmentation_stride
self.segmentation_median_blur_image = segmentation_median_blur_image
self.segmentation_median_blur_kernel_size = (
segmentation_median_blur_kernel_size
)
self.segmentation_group_size = segmentation_group_size
def process_non_patch_grid_elements(self, grid_dict_list, gs_image_set):
"""Processes non-patch grid elements.
Args:
grid_dict_list: list, contains dicts of coordinates and 4-ary tree
grid indices.
gs_image_set: set, image output types that are grayscale, i.e.
have only one channel.
Returns:
List of dictionaries of image arrays.
"""
image_dict_list = []
for grid_dict in grid_dict_list:
image_dict = {}
for stitch_type in self.image_stitch_types_set:
if stitch_type in gs_image_set:
image_dict[stitch_type] = tf.ones(
shape=(self.patch_height, self.patch_width, 1),
dtype=tf.float32
)
else:
image_dict[stitch_type] = tf.ones(
shape=(
self.patch_height,
self.patch_width,
self.patch_depth
),
dtype=tf.float32
)
image_dict_list.append(image_dict)
return image_dict_list
def get_query_images(self, grid_dict_list):
"""Processes patch grid elements.
Args:
grid_dict_list: list, contains dicts of coordinates and 4-ary tree
grid indices.
Returns:
List containing query image tensors.
"""
images = []
if self.wsi_stitch_gcs_path:
gcs = gcsio.GcsIO()
local_file = "slide_file.svs"
num_retries = 0
while num_retries < 100:
try:
with open(local_file, "wb") as f:
f.write(gcs.open(self.wsi_stitch_gcs_path).read())
if tf.io.gfile.exists(path=local_file):
wsi = openslide.OpenSlide(filename=local_file)
images = []
for grid_dict in grid_dict_list:
image = np.array(
wsi.read_region(
location=grid_dict["coords"],
level=0,
size=(self.patch_width, self.patch_height)
)
)[:, :, :3]
images.append(image)
except:
num_retries += 1
else:
break
else:
for grid_dict in grid_dict_list:
raw_image = tf.io.read_file(filename=grid_dict["filename"])
image = tf.io.decode_png(
contents=raw_image, channels=self.patch_depth
)
image = tf.image.rot90(image=image, k=2)
images.append(image)
return images
##########################################################################
### GAN ##################################################################
##########################################################################
def scale_images(self, images):
"""Scales images from [0, 255] to [-1., 1.].
Args:
images: np.array, array of images with range [0, 255] of shape
(num_images, height, width, num_channels).
Returns:
Tensor of images with range [-1., 1.] of shape
(num_images, height, width, num_channels).
"""
return tf.cast(x=images, dtype=tf.float32) * (2. / 255) - 1.
def get_saved_model_serving_signatures(self, 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.
"""
print(
"get_saved_model_serving_signatures: output_dir = {}, export_name = {}".format(
params["output_dir"], export_name
)
)
loaded_model = tf.saved_model.load(
export_dir=os.path.join(
params["output_dir"], "export", export_name
)
)
infer = loaded_model.signatures["serving_default"]
# 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(self, 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_anomaly_scores"],
params["export_query_anomaly_flags"]
]
return export_Z_bool_list, export_query_image_bool_list
def parse_predictions_dict(self, 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(self, 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 = self.get_saved_model_serving_signatures(
export_name, params
)
(export_Z_bool_list,
export_query_image_bool_list) = self.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 = self.parse_predictions_dict(
predictions=predictions, num_growths=1
)
return predictions_by_growth
def plot_all_exports(
self,
Z,
query_images,
exports_on_gcs,
export_start_idx,
export_end_idx,
max_size,
only_output_growth_set,
num_rows,
params
):
"""Plots predictions based on bool conditions.
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).
exports_on_gcs: bool, whether exports are stored on GCS or locally.
export_start_idx: int, index to start at in export list.
export_end_idx: int, index to end at in export list.
max_size: int, the maximum image size within the exported SavedModel.
only_output_growth_set: set, which growth blocks to output.
num_rows: int, number of rows to plot for each desired output.
params: dict, user passed parameters.
"""
predictions_by_growth = self.get_current_growth_predictions(
export_name=self.gan_export_name,
Z=Z,
query_images=self.scale_images(query_images),
params=params
)
return predictions_by_growth
def plot_all_exports_by_architecture(
self,
Z,
query_images,
exports_on_gcs,
export_start_idx,
export_end_idx,
max_size,
only_output_growth_set,
num_rows,
generator_architecture,
overrides
):
"""Plots predictions based on bool conditions and architecture.
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)
exports_on_gcs: bool, whether exports are stored on GCS or locally.
export_start_idx: int, index to start at in export list.
export_end_idx: int, index to end at in export list.
max_size: int, the maximum image size within the exported SavedModel.
only_output_growth_set: set, which growth blocks to output.
num_rows: int, number of rows to plot for each desired output.
generator_architecture: str, architecture to be used for generator,
berg or GANomaly.
overrides: dict, user passed parameters to override default config.
"""
shared_config = {
"generator_architecture": generator_architecture,
"output_dir": "trained_models",
"export_all_growth_phases": False,
"export_query_images": True,
"export_query_anomaly_images_sigmoid": True,
"export_query_anomaly_images_linear": True,
"export_query_mahalanobis_distances": False,
"export_query_mahalanobis_distance_images_sigmoid": False,
"export_query_mahalanobis_distance_images_linear": False,
"export_query_pixel_anomaly_flag_images": False,
"export_query_anomaly_scores": True,
"export_query_anomaly_flags": True,
"output_Z": False,
"output_generated_images": False,
"output_encoded_generated_logits": False,
"output_encoded_generated_images": False,
"output_query_images": False,
"output_query_encoded_logits": False,
"output_query_encoded_images": False,
"output_query_gen_encoded_logits": False,
"output_query_gen_encoded_images": False,
"output_query_enc_encoded_logits": False,
"output_query_enc_encoded_images": False,
"output_query_anomaly_images_sigmoid": False,
"output_query_anomaly_images_linear": False,
"output_query_mahalanobis_distances": False,
"output_query_mahalanobis_distance_images_sigmoid": False,
"output_query_mahalanobis_distance_images_linear": False,
"output_query_pixel_anomaly_flag_images": False,
"output_query_anomaly_scores": False,
"output_query_anomaly_flags": False,
"output_transition_growths": False,
"output_stable_growths": True,
"image_depth": 3
}
if generator_architecture == "berg":
params={
"export_Z": True,
"export_generated_images": True,
"export_encoded_generated_logits": True,
"export_encoded_generated_images": True,
"export_query_encoded_logits": True,
"export_query_encoded_images": True,
"export_query_gen_encoded_logits": False,
"export_query_gen_encoded_images": False,
"export_query_enc_encoded_logits": False,
"export_query_enc_encoded_images": False
}
elif generator_architecture == "GANomaly":
Z = None
params={
"export_Z": False,
"export_generated_images": False,
"export_encoded_generated_logits": False,
"export_encoded_generated_images": False,
"export_query_encoded_logits": False,
"export_query_encoded_images": False,
"export_query_gen_encoded_logits": True,
"export_query_gen_encoded_images": True,
"export_query_enc_encoded_logits": True,
"export_query_enc_encoded_images": True
}
params.update(shared_config)
for key in overrides.keys():
if key in params:
params[key] = overrides[key]
return self.plot_all_exports(
Z=Z,
query_images=query_images,
exports_on_gcs=exports_on_gcs,
export_start_idx=export_start_idx,
export_end_idx=export_end_idx,
max_size=max_size,
only_output_growth_set=only_output_growth_set,
num_rows=num_rows,
params=params
)
def kde2D(self, x, y, bandwidth, kernel, metric, xbins, ybins, **kwargs):
"""Builds 2D kernel density estimate (KDE).
Args:
x: np.array, array of x-coordinates of points of shape
(num_anomaly_flags,).
y: np.array, array of y-coordinates of points of shape
(num_anomaly_flags,).
bandwidth: float, the bandwidth of the kernel.
kernel: str, the kernel to use for density estimation.
metric: str, the distance metric to use. Note that not all metrics
are valid with all algorithms.
xbins: int, number of sample bins to create in the x dimension.
ybins: int, number of sample bins to create in the y dimension.
kwargs: dict, any other keyword args to pass to
sklearn.neighbors.KernelDensity.
Returns:
np.array of the log-likelihood of samples of shape (xbins, ybins).
"""
import sklearn.neighbors
xbins = complex(0, xbins)
ybins = complex(0, ybins)
# Create grid of sample locations.
xx, yy = np.mgrid[x.min():x.max():xbins,
y.min():y.max():ybins]
xy_sample = np.vstack([yy.ravel(), xx.ravel()]).T
xy_train = np.vstack([y, x]).T
kde_skl = sklearn.neighbors.KernelDensity(
bandwidth=bandwidth,
kernel=kernel,
metric=metric,
**kwargs
)
kde_skl.fit(xy_train)
# Score_samples() returns the log-likelihood of the samples.
z = np.exp(kde_skl.score_samples(xy_sample))
return np.reshape(z, xx.shape)
def get_kernel_density_estimates(
self,
anomaly_flags,
depth,
bandwidth,
kernel,
metric,
xbins,
ybins,
min_neighborhood_count,
connectivity,
min_anomaly_points_remaining,
scaling_power,
scaling_factor,
cmap_str
):
"""Gets kernel density estimates for both RGB and grayscale.
Args:
anomaly_flags: tensor, binary anomaly flag images of shape
(batch_size, height, width).
depth: int, the number of color channels of the images.
bandwidth: float, the bandwidth of the kernel.
kernel: str, the kernel to use for density estimation.
metric: str, the distance metric to use. Note that not all metrics
are valid with all algorithms.
xbins: int, number of sample bins to create in the x dimension.
ybins: int, number of sample bins to create in the y dimension.
min_neighborhood_count: int, minimum number of adjacent points as
not to be removed from image.
connectivity: int, connectivity defining the neighborhood of a
pixel.
min_anomaly_points_remaining: int, minimum number of anomaly
points following removing small objects to not clear all
flags.
scaling_power: float, the exponent to use for scaling.
scaling_factor: float, positive factor to scale anomaly flag
counts by.
cmap_str: str, which color map to use.
Returns:
mesh_rgb: np.array, RGB KDE image of shape
(batch_size, height, width, 3).
mesh_gs: np.array, grayscale KDE image of shape
(batch_size, height, width, 1).
"""
import skimage.morphology
batch_size = anomaly_flags.shape[0]
# shape = (batch_size, 1).
anomaly_flag_counts = tf.expand_dims(
input=tf.reduce_sum(
input_tensor=tf.cast(x=anomaly_flags == 1., dtype=tf.float64),
axis=(1, 2)
),
axis=-1
)
anomaly_flags_removed = []
for image in anomaly_flags:
morphed_image = skimage.morphology.remove_small_objects(
ar=image.numpy() == 1.,
min_size=min_neighborhood_count,
connectivity=connectivity
)
morphed_image[0, 0] = 1.
morphed_image[0, -1] = 1.
morphed_image[-1, 0] = 1.
morphed_image[-1, -1] = 1.
anomaly_flags_removed.append(morphed_image)
anomaly_flags = tf.cast(
x=tf.stack(values=anomaly_flags_removed, axis=0), dtype=tf.float32
)
# shape = (batch_size, height, width, depth).
tiled_anomaly_flags = tf.tile(
input=tf.expand_dims(input=anomaly_flags, axis=-1),
multiples=(1, 1, 1, depth)
)
counts_remaining = []
zzs = []
for i in range(batch_size):
# shape = (num_true, 2).
anomaly_points = tf.where(
condition=tf.equal(x=tiled_anomaly_flags[i, :, :, 0], y=1.)
).numpy()
counts_remaining.append(anomaly_points.shape[0])
if anomaly_points.shape[0] > min_anomaly_points_remaining:
# each shape = (num_true,).
x, y = anomaly_points[:, 0], anomaly_points[:, 1]
# shape = (xbins, ybins).
zz = self.kde2D(
x=x,
y=y,
bandwidth=bandwidth,
kernel=kernel,
metric=metric,
xbins=xbins,
ybins=ybins
)
else:
zz = tf.zeros(shape=(xbins, ybins), dtype=tf.float64)
zzs.append(zz)
# shape = (batch_size, xbins, ybins).
zz = tf.stack(values=zzs, axis=0)
# shape = (batch_size, xbins * ybins).
zz_flatten = tf.reshape(tensor=zz, shape=(batch_size, xbins * ybins))
zz_flatten_scaled = zz_flatten
# shape = (batch_size, xbins * ybins).
zz_min_scaled = tf.math.reduce_min(
input_tensor=zz_flatten_scaled, axis=-1, keepdims=True
)
# shape = (batch_size, xbins * ybins).
zz_max_scaled = tf.math.reduce_max(
input_tensor=zz_flatten_scaled, axis=-1, keepdims=True
)
# shape = (batch_size, xbins * ybins).
zz_normalized_scaled = tf.math.divide_no_nan(
x=zz_flatten_scaled - zz_min_scaled,
y=zz_max_scaled - zz_min_scaled
)
# shape = (batch_size, xbins * ybins).
zz_normalized_scaled = tf.minimum(
x=zz_normalized_scaled * tf.pow(
x=anomaly_flag_counts / scaling_factor, y=scaling_power
),
y=1.
)
# shape = (batch_size, xbins * ybins).
zz_int_flat = tf.cast(
x=tf.math.round(x=zz_normalized_scaled * 255.),
dtype=tf.int32
)
cmap_colors = plt.get_cmap(cmap_str).colors
# shape = (256, 3).
rgb_cm = tf.constant(value=cmap_colors, dtype=tf.float32)
# shape = (batch_size, xbins * ybins, depth).
zz_gathered = tf.gather(indices=zz_int_flat, params=rgb_cm)
# shape = (batch_size, xbins, ybins, depth).
zz_rgb = tf.reshape(
tensor=zz_gathered, shape=(batch_size, xbins, ybins, depth)
)
# shape = (batch_size, xbins, ybins, depth).
zz_rgb_scaled = zz_rgb * 2. - 1.
# shape = (batch_size, height, width, depth).
mesh_rgb = tf.image.resize(
images=zz_rgb_scaled,
size=(tiled_anomaly_flags.shape[1], tiled_anomaly_flags.shape[2])
)
# shape = (batch_size, xbins, ybins, 1).
zz_gs = tf.reshape(
tensor=zz_normalized_scaled, shape=(batch_size, xbins, ybins, 1)
)
# shape = (batch_size, xbins, ybins, depth).
zz_gs_scaled = zz_gs * 2. - 1.
# shape = (batch_size, height, width, 1).
mesh_gs = tf.image.resize(
images=zz_gs_scaled,
size=(tiled_anomaly_flags.shape[1], tiled_anomaly_flags.shape[2])
)
return mesh_rgb, mesh_gs
def confusion_matrix(self, filename, image, label_image):
"""Creates confusion matrix metrics at thresholds between images.
Args:
filename: str, filaname of image.
image: np.array, image array of shape
(patch_height, patch_width, 1).
label_image: np.array, label image array of shape
(patch_height, patch_width, 1).
Returns:
List of dictionaries containing confusion matrix metrics at
thresholds.
"""
thresholds = tf.linspace(
start=0., stop=1., num=self.num_confusion_matrix_thresholds
)
images_thresholded = image > thresholds
return [
{
"filename": filename,
"threshold": th,
"tp": tp,
"fp": fp,
"fn": fn,
"tn": tn
}
for th, tp, fp, fn, tn in zip(
thresholds.numpy().tolist(),
tf.reduce_sum(
input_tensor=tf.cast(
x=tf.logical_and(
x=images_thresholded, y=label_image == 1
),
dtype=tf.int32
),
axis=(0, 1)
).numpy().tolist(),
tf.reduce_sum(
input_tensor=tf.cast(
x=tf.logical_and(
x=images_thresholded, y=label_image == 0
),
dtype=tf.int32
),
axis=(0, 1)
).numpy().tolist(),
tf.reduce_sum(
input_tensor=tf.cast(
x=tf.logical_and(
x=~images_thresholded, y=label_image == 1
),
dtype=tf.int32
),
axis=(0, 1)
).numpy().tolist(),
tf.reduce_sum(
input_tensor=tf.cast(
x=tf.logical_and(
x=~images_thresholded, y=label_image == 0
),
dtype=tf.int32
),
axis=(0, 1)
).numpy().tolist()
)
]
def inference_from_gan_saved_model(
self, grid_dict_list, gs_image_set, query_images
):
"""Inferences GAN SavedModel and gets outputs.
Args:
grid_dict_list: list, contains dicts of coordinates and 4-ary tree
grid indices.
gs_image_set: set, image output types that are grayscale, i.e.
have only one channel.
query_images: tensor, query image tensor of shape
(batch, patch_height, patch_width, 3).
Returns:
image_dict_list: list, dictionaries containing image tensors.
confusion_matrix_list: list, lists of dictionaries containing
confusion matrix metrics at thresholds.
"""
batch_size = len(grid_dict_list)
image_dict_list = [{} for _ in range(batch_size)]
confusion_matrix_list = [[] for _ in range(batch_size)]
image_dict = {}
if (
"query_images" in self.image_stitch_types_set and
len(self.image_stitch_types_set) == 1
):
query_images = self.scale_images(images=query_images)
image_dict = {"query_images": query_images}
else:
Z = None
if (self.generator_architecture == "berg" and
self.berg_use_Z_inputs):
Z = tf.random.normal(
shape=(
query_images.shape[0], self.berg_latent_size
),
mean=self.berg_latent_mean,
stddev=self.berg_latent_stddev,
dtype=tf.float32
)
predictions_by_growth = self.plot_all_exports_by_architecture(
Z=Z,
query_images=query_images,
exports_on_gcs=True,
export_start_idx=0,
export_end_idx=1,