-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathinference_zero_shot.py
3673 lines (3376 loc) · 170 KB
/
inference_zero_shot.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
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
import argparse
from collections import OrderedDict, Iterable
from copy import deepcopy
from datetime import datetime
import matplotlib.pylab as plt
import gc
import logging
logging.getLogger('matplotlib.font_manager').disabled = True
import matplotlib.pylab as plt
import os
import pdb
import pickle
import pprint as pp
import random
import pandas as pd
from scipy import stats
from IPython.display import display, HTML
pd.options.display.max_rows = 1500
pd.options.display.max_columns = 200
pd.options.display.width = 1000
pd.set_option('max_colwidth', 400)
from IPython.display import display
import numpy as np
from sklearn import linear_model
import torch
import torch.nn as nn
from torch.nn import functional as F
from torch.utils.data import Dataset, DataLoader
from torchvision import datasets, transforms, utils
import matplotlib.pyplot as plt
import sys, os
sys.path.append(os.path.join(os.path.dirname("__file__"), '..'))
sys.path.append(os.path.join(os.path.dirname("__file__"), '..', '..'))
from zeroc.datasets.arc_image import ARCDataset
from zeroc.datasets.BabyARC.code.dataset.dataset import *
from zeroc.concept_library.concepts import Concept, Concept_Pattern, Placeholder, Tensor
from zeroc.argparser import update_default_hyperparam, get_args_EBM, get_SGLD_kwargs
from zeroc.concept_library.models import load_best_model, GraphEBM, neg_mask_sgd, neg_mask_sgd_ensemble, ResBlock, CResBlock, spectral_norm
from zeroc.train import get_c_core, init_concepts_with_repr, ConceptDataset, ConceptFewshotDataset, ConceptCompositionDataset, get_dataset, requires_grad, test_acc, load_model_energy, SampleBuffer, sample_buffer, id_to_tensor
from zeroc.concept_library.settings import REPR_DIM
from zeroc.utils import REA_PATH, EXP_PATH
try:
from zeroc.concept_library.util import try_call, plot_simple, plot_2_axis, Attr_Dict, MineDataset, Batch, extend_dims, groupby_add_keys, get_unique_keys_df, filter_df, groupby_add_keys, to_cpu_recur, Printer, get_num_params, transform_dict, get_graph_edit_distance, draw_nx_graph, get_nx_graph, get_triu_ids, get_soft_IoU, get_pdict, Batch, pdump, pload, filter_kwargs, gather_broadcast, ddeepcopy as deepcopy, to_Variable, set_seed, Zip, COLOR_LIST, init_args, make_dir, str2bool, get_filename_short, get_machine_name, get_device, record_data, plot_matrices, filter_filename, get_next_available_key, to_np_array, print_banner, get_filename_short, write_to_config, to_cpu
from zeroc.concept_library.util import find_connected_components_colordiff, onehot_to_RGB, classify_concept, Shared_Param_Dict, get_inputs_targets_EBM, repeat_n, color_dict, to_one_hot, onehot_to_RGB, get_root_dir, get_module_parameters, assign_embedding_value, get_hashing, to_device_recur, visualize_matrices
except Exception as e:
raise Exception(f"{e}. Please update the concept_library by running 'git submodule init; git submodule update' in the local zeroc repo!")
p = Printer()
# # 1. Helper functions:
# In[ ]:
def plot_loss(data_record, interval=1):
fontsize = 12
plt.figure(figsize=(8,6))
plt.plot(data_record['epoch'][::interval], data_record['pos_out'][::interval], label="pos")
plt.plot(data_record['epoch'][::interval], data_record['neg_out'][::interval], label="neg")
plt.plot(data_record['epoch'][::interval], data_record['loss'][::interval], label="loss")
plt.plot(data_record['epoch'][::interval], np.array(data_record['loss'][::interval]) - np.array(data_record['pos_out'][::interval]), label="loss-pos")
plt.legend(fontsize=fontsize)
plt.tick_params(labelsize=fontsize)
plt.xlabel("epoch", fontsize=fontsize)
plt.ylabel("loss", fontsize=fontsize)
plt.show()
def update_CONCEPTS_OPERATORS(CONCEPTS, OPERATORS, concept_embeddings_load, update_keys=None):
if update_keys is not None and not isinstance(update_keys, list):
update_keys = [update_keys]
for key in CONCEPTS:
if key in concept_embeddings_load:
if update_keys is not None and key in update_keys and key in concept_embeddings_load:
c_repr_curr = CONCEPTS[key].get_node_repr()
c_repr_curr.data = torch.FloatTensor(concept_embeddings_load[key])
for key in OPERATORS:
if update_keys is not None and key in update_keys and key in concept_embeddings_load:
c_repr_curr = OPERATORS[key].get_node_repr()
c_repr_curr.data = torch.FloatTensor(concept_embeddings_load[key])
def test_concept_embedding(CONCEPTS, OPERATORS, concept_embeddings_load, raise_warnings_only=False, checked_keys=None):
concept_embeddings = {key: to_np_array(CONCEPTS[key].get_node_repr()) for key in CONCEPTS}
operator_embeddings = {key: to_np_array(OPERATORS[key].get_node_repr()) for key in OPERATORS}
concept_embeddings.update(operator_embeddings)
different_list = []
same_list = []
for key, value in concept_embeddings_load.items():
if key not in concept_embeddings:
p.warning("key '{}' not in the current concept/relation embedding.".format(key))
continue
if (checked_keys is None or key in checked_keys) and np.abs(value - concept_embeddings[key]).max() > 0:
different_list.append(key)
else:
same_list.append(key)
if len(different_list) > 0:
if raise_warnings_only:
print("The c_repr for {} are the same.\nThe c_repr for {} are different.\n".format(same_list, different_list))
else:
raise Exception("The c_repr for {} are the same.\nThe c_repr for {} are different.\n".format(same_list, different_list))
def get_model_samples(
model,
args,
dataset=None,
init="gaussian",
sample_step=None,
batch_size=None,
ensemble_size=1,
plot_ensemble_mode="min",
analysis_modes=["mask|c_repr", "c_repr|mask", "mask|c", "c_repr|c"],
w_type="image+mask",
plot_grey_scale=False,
concept_collection=None,
CONCEPTS=None,
OPERATORS=None,
isplot=True,
device="cpu",
plot_topk=3,
):
"""This one is with concept_collection argument."""
def init_neg_mask(pos_img, buffer, args):
"""Initialize negative mask"""
neg_data = sample_buffer(
buffer,
in_channels=args.in_channels,
n_classes=args.n_classes,
image_size=args.image_size,
batch_size=batch_size*ensemble_size,
is_mask=args.is_mask,
is_two_branch=args.is_two_branch,
w_type=args.w_type,
p=args.p_buffer,
device=device,
)
_, neg_mask, _, _ = neg_data
pos_img_l = repeat_n(pos_img, n_repeats=ensemble_size)
if args.is_two_branch:
if init == "mask-gaussian":
neg_mask = (neg_mask[0] * (pos_img_l[0].argmax(1)[:, None] != 0), neg_mask[1] * (pos_img_l[1].argmax(1)[:, None] != 0))
else:
if init == "mask-gaussian":
pos_img_l = repeat_n(pos_img, n_repeats=ensemble_size)
neg_mask = (neg_mask[0] * (pos_img_l.argmax(1)[:, None] != 0),)
for k in range(len(neg_mask)):
neg_mask[k].requires_grad = True
return neg_mask
model.eval()
buffer = SampleBuffer()
args = deepcopy(args)
batch_size = args.batch_size if batch_size is None else batch_size
sample_step = args.sample_step if sample_step is None else sample_step
if concept_collection is not None:
args.concept_collection = concept_collection
args.sample_step = sample_step
args.ebm_target = "mask"
if args.is_mask:
assert dataset is not None
dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=False, collate_fn=Batch(is_collate_tuple=True).collate())
for pos_data in dataloader:
break
pos_img, pos_mask, pos_id, _ = pos_data
pos_repr = id_to_tensor(pos_id, CONCEPTS=CONCEPTS, OPERATORS=OPERATORS).to(device)
if args.is_two_branch:
pos_img = (pos_img[0].to(device), pos_img[1].to(device))
else:
pos_img = pos_img.to(device)
pos_mask = to_device_recur(pos_mask, device)
data = {
"pos_img": pos_img,
"pos_mask": pos_mask,
"pos_id": pos_id,
"pos_repr": pos_repr,
"concept_collection": args.concept_collection,
}
# Calculate E(ground truth mask for given concept)
if "mask|c_repr" in analysis_modes:
neg_mask = init_neg_mask(pos_img, buffer, args)
(_, neg_mask_ensemble, _, _, _), neg_out_list_ensemble, _ = neg_mask_sgd_ensemble(
model, pos_img, neg_mask, pos_repr, z=None, zgnn=None, wtarget=None, args=args,
ensemble_size=ensemble_size,
)
data["mask|c_repr"] = {
"neg_mask_ensemble": neg_mask_ensemble,
"neg_out_list_ensemble": neg_out_list_ensemble,
}
# Calculate E(concept given a ground truth mask)
if "c_repr|mask" in analysis_modes:
data["c_repr|mask"] = {"c_repr_pred": model.classify(pos_img, pos_mask, args.concept_collection, CONCEPTS=CONCEPTS, OPERATORS=OPERATORS)}
if "mask|c" in analysis_modes:
neg_mask_ensemble_collection = []
neg_out_list_ensemble_collection = []
for j in range(len(args.concept_collection)):
neg_mask = init_neg_mask(pos_img, buffer, args)
c_repr = id_to_tensor([args.concept_collection[j]] * len(pos_repr), CONCEPTS=CONCEPTS, OPERATORS=OPERATORS).to(device)
(_, neg_mask_ensemble, _, _, _), neg_out_list_ensemble, _ = neg_mask_sgd_ensemble(
model, pos_img, neg_mask, c_repr, z=None, zgnn=None, wtarget=None, args=args,
ensemble_size=ensemble_size,
out_mode="min",
)
neg_mask_ensemble_collection.append(neg_mask_ensemble)
neg_out_list_ensemble_collection.append(neg_out_list_ensemble)
neg_mask_ensemble_collection = tuple(torch.stack([neg_mask_ensemble_ele[k] for neg_mask_ensemble_ele in neg_mask_ensemble_collection], -1) for k in range(len(neg_mask_ensemble_collection[0])))
neg_out_list_ensemble_collection = np.stack(neg_out_list_ensemble_collection, -1) # [n_steps, ensemble_size, batch_size, n_repr]
c_repr_energy = neg_out_list_ensemble_collection[-1].min(0)
c_repr_argsort = c_repr_energy.argsort(1)
c_repr_pred_list = []
for i, argsort in enumerate(c_repr_argsort):
c_repr_pred = {}
for k in range(len(args.concept_collection)):
id_k = c_repr_argsort[i][k]
c_repr_pred[args.concept_collection[id_k]] = c_repr_energy[i][id_k].item()
c_repr_pred_list.append(c_repr_pred)
data["both|c"] = {
"neg_mask_ensemble_collection": neg_mask_ensemble_collection,
"neg_out_list_ensemble_collection": neg_out_list_ensemble_collection,
"c_repr_pred": c_repr_pred_list,
}
if isplot:
plot_data(model, data, args, plot_ensemble_mode=plot_ensemble_mode, w_type=w_type, plot_grey_scale=plot_grey_scale, topk=plot_topk)
else:
neg_out_list = []
neg_img, neg_id = neg_data
neg_img.requires_grad = True
noise = torch.randn(batch_size, args.in_channels, args.image_size, args.image_size, device=device)
for k in range(sample_step):
if "noise" not in locals():
noise = torch.randn(neg_img.shape[0], args.in_channels, args.image_size, args.image_size, device=device)
noise.normal_(0, args.lambd)
neg_img.data.add_(noise.data)
neg_out = model(neg_img, neg_id)
neg_out.sum().backward()
neg_out_list.append(to_np_array(neg_out))
neg_img.grad.data.clamp_(-0.01, 0.01)
neg_img.data.add_(neg_img.grad.data, alpha=-args.step_size)
neg_img.grad.detach_()
neg_img.grad.zero_()
neg_img.data.clamp_(0, 1)
data = {
"neg_img": neg_img,
"neg_id": neg_id,
}
neg_out_list = np.concatenate(neg_out_list, -1).T
if isplot:
if neg_img.shape[1] != 3:
for img, neg_ele in zip(neg_img.argmax(1), neg_out):
print("loss={:.6f}".format(to_np_array(neg_ele)))
visualize_matrices([img])
return data
def plot_data(model, data, args, plot_ensemble_mode="min", w_type="image+mask", topk=3, plot_grey_scale=False):
plt.figure(figsize=(12,6))
neg_out_list_ensemble = data["mask|c_repr"]["neg_out_list_ensemble"] # [n_steps, ensemble_size, batch_size]
for i in range(min(neg_out_list_ensemble.shape[-1], 6)):
for k in range(neg_out_list_ensemble.shape[1]):
plt.plot(neg_out_list_ensemble[:,k,i], c=COLOR_LIST[i], label="example_{}".format(i) if k==0 else None, alpha=0.4)
plt.legend()
plt.show()
pos_img, pos_mask, pos_id, pos_repr = data["pos_img"], data["pos_mask"], data["pos_id"], data["pos_repr"]
concept_collection = data["concept_collection"]
if topk == -1:
topk = len(concept_collection)
topk = min(topk, len(concept_collection))
length = len(pos_repr)
pos_out_last = to_np_array(model(pos_img, mask=pos_mask, c_repr=pos_repr)).squeeze()
if args.is_two_branch:
if pos_img[0].shape[1] == 3:
pos_img_core = torch.cat([pos_img[0].detach().to('cpu'), pos_img[1].detach().to('cpu')])
else:
pos_img_core = torch.cat([onehot_to_RGB(pos_img[0]), onehot_to_RGB(pos_img[1])])
pos_mask_core = torch.cat([pos_mask[0].detach().to('cpu').round(), pos_mask[1].detach().to('cpu').round()])
for i in range(0, length, 6):
print("\n{} to {}:".format(i, i+5))
print("positive images: input (up) and target (down)")
visualize_matrices(pos_img[0][i:i+6].argmax(1), images_per_row=6)
visualize_matrices(pos_img[1][i:i+6].argmax(1), images_per_row=6)
print("positive mask: input obj mask (up) and target obj mask (down)")
visualize_matrices(pos_mask[0][i:i+6,0].round() if "mask" in w_type else pos_mask[0][i:i+6].argmax(1), images_per_row=6, subtitles=["\n".join(["{}: {:.4f}".format("[{}]".format(key) if pos_id[i+j]==key else key, item) for k, (key, item) in enumerate(Dict.items()) if k < topk]) for j, Dict in enumerate(data["c_repr|mask"]["c_repr_pred"][i:i+6])])
visualize_matrices(pos_mask[1][i:i+6,0].round() if "mask" in w_type else pos_mask[1][i:i+6].argmax(1), images_per_row=6, subtitles=["c:"+"\n".join(["{}: {:.4f}".format("[{}]".format(key) if pos_id[i+j]==key else key, item) for k, (key, item) in enumerate(Dict.items()) if k < topk]) for j, Dict in enumerate(data["both|c"]["c_repr_pred"][i:i+6])])
if "mask|c_repr" in data:
if "neg_out_argmin" not in locals():
neg_mask_ensemble = data["mask|c_repr"]["neg_mask_ensemble"]
neg_out_argmin = neg_out_list_ensemble[-1].argmin(0) # neg_out_list_ensemble: [time_step, ensemble_size, batch_size]
if plot_ensemble_mode == "min":
print("negative mask | c_repr: input obj mask (up) and target obj mask (down), with lowest-loss element in the ensemble:")
visualize_matrices([neg_mask_ensemble[0][neg_out_argmin[k],k,0].round() if "mask" in w_type else neg_mask_ensemble[0][neg_out_argmin[k],k].argmax(0) for k in range(i, i+6)], images_per_row=6, subtitles=["{}: {:.4f}".format(pos_id[k], neg_out_list_ensemble[-1,neg_out_argmin[k],k]) for k in range(i,i+6)])
visualize_matrices([neg_mask_ensemble[1][neg_out_argmin[k],k,0].round() if "mask" in w_type else neg_mask_ensemble[1][neg_out_argmin[k],k].argmax(0) for k in range(i, i+6)], images_per_row=6)
if plot_grey_scale:
plot_matrices([neg_mask_ensemble[0][neg_out_argmin[k],k,0] for k in range(i, i+6)] if "mask" in w_type else neg_mask_ensemble[0][neg_out_argmin[k],k].argmax(0), scale_limit=(0,1), images_per_row=6)
plot_matrices([neg_mask_ensemble[1][neg_out_argmin[k],k,0] for k in range(i, i+6)] if "mask" in w_type else neg_mask_ensemble[1][neg_out_argmin[k],k].argmax(0), scale_limit=(0,1), images_per_row=6)
elif plot_ensemble_mode == "all":
for j in range(ensemble_size):
is_best = j == neg_out_argmin
if j == 0:
print("negative mask | c_repr: {}th element in the ensemble for input obj mask (up) and target obj mask (down)".format(j))
else:
print(" {}th element in the ensemble for input obj mask (up) and target obj mask (down)".format(j))
visualize_matrices([neg_mask_ensemble[0][j,k,0].round() if "mask" in w_type else neg_mask_ensemble[0][j,k].argmax(0) for k in range(i, i+6)], images_per_row=6, subtitles=["{}: {:.4f}{}".format(pos_id[k], neg_out_list_ensemble[-1,j,k], ", best" if is_best[k] else "") for k in range(i,i+6)])
visualize_matrices([neg_mask_ensemble[1][j,k,0].round() if "mask" in w_type else neg_mask_ensemble[1][j,k].argmax(0) for k in range(i, i+6)], images_per_row=6)
if plot_grey_scale:
plot_matrices([neg_mask_ensemble[0][j,k,0] for k in range(i, i+6)], scale_limit=(0,1), images_per_row=6)
plot_matrices([neg_mask_ensemble[1][j,k,0] for k in range(i, i+6)], scale_limit=(0,1), images_per_row=6)
else:
raise
if "both|c" in data:
if "c_repr_pred_c" not in locals():
neg_mask_ensemble_collection = data["both|c"]['neg_mask_ensemble_collection']
neg_out_list_ensemble_collection = data["both|c"]["neg_out_list_ensemble_collection"]
c_repr_pred_c = data["both|c"]['c_repr_pred']
neg_out_argsort_c = neg_out_list_ensemble_collection[-1].min(0).argsort(-1) # length batch_size, each indicating the argsort of concept id
for j in range(topk):
if j == 0:
print("negative mask | c: top {}th prediction for input obj mask (up) and target obj mask (down)".format(j+1))
else:
print(" top {}th prediction in the ensemble for input obj mask (up) and target obj mask (down)".format(j+1))
visualize_matrices([neg_mask_ensemble_collection[0][k,...,neg_out_argsort_c[k][j]].squeeze(0).round()
if "mask" in w_type else neg_mask_ensemble_collection[0][k,...,neg_out_argsort_c[k][j]].argmax(0)
for k in range(i, i+6)], images_per_row=6,
subtitles=["{}: {:.4f}".format("[{}]".format(concept_collection[neg_out_argsort_c[k][j]]) if concept_collection[neg_out_argsort_c[k][j]]==pos_id[k] else concept_collection[neg_out_argsort_c[k][j]], c_repr_pred_c[k][concept_collection[neg_out_argsort_c[k][j]]]) for k in range(i, i+6)]
)
visualize_matrices([neg_mask_ensemble_collection[1][k,...,neg_out_argsort_c[k][j]].squeeze(0).round()
if "mask" in w_type else neg_mask_ensemble_collection[1][k,...,neg_out_argsort_c[k][j]].argmax(0)
for k in range(i, i+6)], images_per_row=6,
)
print()
else:
if pos_img.shape[1] == 3:
pos_img_core = pos_img.detach().to('cpu')
else:
pos_img_core = onehot_to_RGB(pos_img)
for i in range(0, length, 6):
print("\n{} to {}:".format(i, i+5))
print("positive images:")
visualize_matrices(pos_img[i:i+6].argmax(1), images_per_row=6)
print("positive masks:")
visualize_matrices(pos_mask[0][i:i+6,0].round() if "mask" in w_type else pos_mask[0][i:i+6].argmax(1), images_per_row=6, subtitles=["\n".join(["{}: {:.4f}".format("[{}]".format(key) if pos_id[i+j]==key else key, item) for k, (key, item) in enumerate(Dict.items()) if k < topk]) + "\nc:" + "\n".join(["{}: {:.4f}".format("[{}]".format(key) if pos_id[i+j]==key else key, item) for k, (key, item) in enumerate(data["both|c"]["c_repr_pred"][i+j].items()) if k < topk]) for j, Dict in enumerate(data["c_repr|mask"]["c_repr_pred"][i:i+6])])
if "mask|c_repr" in data:
if "neg_out_argmin" not in locals():
neg_mask_ensemble = data["mask|c_repr"]["neg_mask_ensemble"]
neg_out_argmin = neg_out_list_ensemble[-1].argmin(0)
if plot_ensemble_mode == "min":
print("negative mask | c_repr: for lowest-loss element in the ensemble:")
visualize_matrices([neg_mask_ensemble[0][neg_out_argmin[k],k,0].round()
if "mask" in w_type else neg_mask_ensemble[0][neg_out_argmin[k],k].argmax(0)
for k in range(i, i+6)], images_per_row=6, subtitles=["{}: {:.4f}".format(pos_id[k], neg_out_list_ensemble[-1,neg_out_argmin[k],k]) for k in range(i,i+6)])
if plot_grey_scale:
plot_matrices([neg_mask_ensemble[0][neg_out_argmin[k],k,0] for k in range(i, i+6)], scale_limit=(0,1), images_per_row=6)
elif plot_ensemble_mode == "all":
for j in range(ensemble_size):
if j == 0:
print("negative mask | c_repr: {}th element in the ensemble".format(j))
else:
print(" {}th element in the ensemble".format(j))
is_best = j == neg_out_argmin
visualize_matrices([neg_mask_ensemble[0][j,k,0].round() for k in range(i, i+6)], images_per_row=6, subtitles=["{}: {:.4f}{}".format(pos_id[k], neg_out_list_ensemble[-1,j,k], ", best" if is_best[k] else "") for k in range(i,i+6)])
if plot_grey_scale:
plot_matrices([neg_mask_ensemble[0][j,k,0] for k in range(i, i+6)], scale_limit=(0,1), images_per_row=6)
else:
raise
if "both|c" in data:
if "c_repr_pred_c" not in locals():
neg_mask_ensemble_collection = data["both|c"]['neg_mask_ensemble_collection']
neg_out_list_ensemble_collection = data["both|c"]["neg_out_list_ensemble_collection"]
c_repr_pred_c = data["both|c"]['c_repr_pred']
neg_out_argsort_c = neg_out_list_ensemble_collection[-1].min(0).argsort(-1) # length batch_size, each indicating the argsort of concept id
for j in range(topk):
if j == 0:
print("negative mask | c: top {}th prediction for the mask".format(j+1))
else:
print(" top {}th prediction for the mask".format(j+1))
visualize_matrices([neg_mask_ensemble_collection[0][k,...,neg_out_argsort_c[k][j]].squeeze(0).round()
if "mask" in w_type else neg_mask_ensemble_collection[0][k,...,neg_out_argsort_c[k][j]].argmax(0)
for k in range(i, i+6)], images_per_row=6,
subtitles=["{}: {:.4f}".format("[{}]".format(concept_collection[neg_out_argsort_c[k][j]]) if concept_collection[neg_out_argsort_c[k][j]]==pos_id[k] else concept_collection[neg_out_argsort_c[k][j]], c_repr_pred_c[k][concept_collection[neg_out_argsort_c[k][j]]]) for k in range(i, i+6)]
)
print()
def plot_acc(dirname, filenames, acc_modes=None, filter_mode=None, prefix=None, suffix=None, is_plot_loss=True):
# Plot the accuracy for the a set of model given paths. You can specify which accuracy modes, prefix, and suffix to be used.
# If acc_modes is None, we use all accuracy modes
for filename in filenames:
path = dirname + filename
data_record = pickle.load(open(path, "rb"))
args = init_args(update_default_hyperparam(data_record["args"]))
accuracy = data_record["acc"]
table_acc_modes = {'Filenames': filenames}
if acc_modes == None:
acc_modes = accuracy.keys()
if filter_mode is None:
acc_modes = [acc_mode for acc_mode in acc_modes if (prefix is None or acc_mode.startswith(prefix)) and (suffix is None or acc_mode.endswith(suffix))]
elif filter_mode == "standard":
acc_modes = ['acc:mask|c_repr:val', 'acc:mask|c:val', 'acc:c_repr|mask:val', 'acc:c_repr|c:val']
else:
raise
print(filename)
plt.figure(figsize=(8,6))
best_dict = {}
for key in acc_modes:
x = accuracy["epoch:val"]
y = accuracy[key]
best_dict[key] = np.max(accuracy[key])
plt.plot(x, y, label=key)
acc_mean = np.array([accuracy[key] for key in acc_modes]).mean(0)
acc_mean_argmax = acc_mean.argmax()
plt.plot(x, acc_mean, label="mean_plot")
plt.axvline(x=accuracy["epoch:val"][acc_mean_argmax], color='k', linestyle='--')
if is_plot_loss:
if args.train_mode == "cd":
plt.plot(data_record["epoch"], data_record["E:pos:train"], label="E:pos:train")
plt.plot(data_record["epoch"], data_record["E:neg|c_repr:train"], label="E:neg:train")
plt.plot(data_record["epoch"], data_record["E:neg_gen:train"], label="E:neg_gen:train")
if "loss_kl" in data_record:
plt.plot(data_record["epoch"], data_record["loss_kl"], label="loss_kl")
plt.plot(data_record["epoch"], data_record["loss_entropy_mask_mean"], label="loss_entropy_mask_mean")
plt.plot(data_record["epoch"], data_record["loss_entropy_repr_mean"], label="loss_entropy_repr_mean")
elif args.train_mode == "sl":
plt.plot(data_record["epoch"], data_record["loss_mask:train"], label="loss_mask:train")
plt.plot(data_record["epoch"], data_record["loss_repr:train"], label="loss_repr:train")
plt.plot(data_record["epoch"], data_record["loss:train"], label="loss:train")
else:
raise
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
title = "Best:"
for key in best_dict:
title += " {}={:.4f}".format(key[4:-4], best_dict[key], end="")
plt.title(title)
plt.show()
def analyze(
dirname,
filename,
init="gaussian", # "mask-gaussian"
batch_size=12,
load_epoch=-1,
ensemble_size=8,
plot_ensemble_mode="min",
plot_grey_scale=False,
analysis_result=None,
# New settings:
n_examples=1000,
sample_step=120,
lambd=-1,
seed=2,
CONCEPTS=None,
OPERATORS=None,
isplot=True,
):
"""Get test_acc, generate samples, and visualize."""
print_banner(filename)
try:
data_record = pickle.load(open(dirname + filename, "rb"))
except Exception as e:
print(e)
return None, None, None
if isplot:
plot_loss(data_record)
args = init_args(update_default_hyperparam(data_record["args"]))
pp.pprint(args.__dict__)
if 'concept_embeddings' in data_record:
test_concept_embedding(CONCEPTS, OPERATORS, data_record['concept_embeddings'])
if n_examples is not None:
args.n_examples = n_examples
args.gpuid = "False"
if lambd != -1:
args.lambd = lambd
device = "cpu"
if load_epoch < 0:
load_epoch += data_record["epoch"][-1]
id = int(np.round(load_epoch / args.save_interval))
if id > len(data_record["model_dict"]):
print("{} has only {} epochs. Continue".format(filename, data_record["epoch"][-1]))
return None, None, None
if analysis_result is None:
set_seed(seed=seed)
dataset, args = get_dataset(args)
dataloader = DataLoader(dataset, batch_size=len(dataset), shuffle=True, collate_fn=Batch(is_collate_tuple=True).collate())
model = load_model_energy(data_record["model_dict"][id], device=device)
val_acc_dict = test_acc(model, args, dataloader, device, CONCEPTS=CONCEPTS, OPERATORS=OPERATORS, suffix=":val")
print("\nacc and energy:")
pp.pprint(val_acc_dict)
print("\nmodel at epoch {}:".format(id * args.save_interval))
# Perform gradient descent to find a low energy mask:
data, neg_out_list_ensemble = get_model_samples(model, args, dataset=dataset, init=init, sample_step=sample_step, batch_size=batch_size, ensemble_size=ensemble_size, plot_ensemble_mode=plot_ensemble_mode, plot_grey_scale=plot_grey_scale, CONCEPTS=CONCEPTS, OPERATORS=OPERATORS, isplot=isplot)
else:
print("Loading saved analysis:")
model = load_model_energy(data_record["model_dict"][id], device=device)
data = analysis_result["data"]
neg_out_list_ensemble = analysis_result["neg_out_list_ensemble"]
val_acc_dict = analysis_result["val_acc_dict"]
print("\nacc and energy:")
pp.pprint(val_acc_dict)
print("\nmodel at epoch {}:".format(id * args.save_interval))
if isplot:
plot_data(model, data, neg_out_list_ensemble, args, plot_ensemble_mode=plot_ensemble_mode, plot_grey_scale=plot_grey_scale)
dataset = None
print()
data_record.pop("model_dict")
info = {
"args": args,
"data_record": data_record,
"data": data,
"neg_out_list_ensemble": neg_out_list_ensemble,
"val_acc_dict": val_acc_dict,
}
return model, dataset, info
def get_useful_keys(df, args_keys):
useful_keys = []
for key in sorted(args_keys):
try:
df_mean = df.groupby(by=key).mean()
except:
continue
if len(df_mean) == 1:
continue
useful_keys.append(key)
if "gpuid" in useful_keys:
useful_keys.remove("gpuid")
if "is_two_branch" in useful_keys:
useful_keys.remove("is_two_branch")
return useful_keys
def print_info(args, keys=None):
if keys is None:
keys = ["dataset", "canvas_size", "neg_mode_coef", "ebm_target_mode", "step_size_repr", "c_repr_mode", "c_repr_first", "channel_base", "n_examples", "aggr_mode", "kl_coef", "entropy_coef_mask", "entropy_coef_repr", "is_spec_norm", "color_avail","id"]
for key in keys:
print("{}: {}".format(key, getattr(args, key)))
def get_update_acc(dirname, suffix=""):
"""Get Pandas dataframe analysing acc."""
filenames = filter_filename(dirname, include=".p")
df_dict_list = []
for filename in filenames:
data_record = pickle.load(open(dirname + filename, "rb"))
args = init_args(update_default_hyperparam(data_record["args"]))
df_dict = {}
acc_dict = data_record["acc"]
for key in acc_dict:
best_id_acc = np.argmax(acc_dict['acc:mean:val'])
acc_repr = np.array([acc_dict[key] for key in acc_dict if key.startswith("acc:c_repr")]).mean(0)
acc_mask = np.array([acc_dict[key] for key in acc_dict if key.startswith("acc:mask") and "_0" not in key and "_1" not in key]).mean(0)
best_id_acc_repr = np.argmax(acc_repr)
best_id_acc_mask = np.argmax(acc_mask)
df_dict["epoch"] = acc_dict["epoch:val"][-1]
df_dict["best_epoch:acc"] = acc_dict["epoch:val"][best_id_acc]
df_dict["best_epoch:acc_repr"] = acc_dict["epoch:val"][best_id_acc_repr]
df_dict["best_epoch:acc_mask"] = acc_dict["epoch:val"][best_id_acc_mask]
df_dict["acc:c_repr:mean:val"] = np.max(acc_repr)
df_dict["acc:mask:mean:val"] = np.max(acc_mask)
#print(df_dict["best_epoch:acc_mask"])
best_id_model = int(df_dict["best_epoch:acc_mask"] / 20)
decice= "cuda:0"
model = load_model_energy(data_record["model_dict"][best_id_model], device=device)
set_seed(seed=2)
args.n_examples = 500
dataset, _ = get_dataset(args)
dataloader = DataLoader(dataset, batch_size=len(dataset), shuffle=False, collate_fn=Batch(is_collate_tuple=True).collate())
decice= "cuda:0"
update_val_acc_dict = test_acc(model, args, dataloader, device, CONCEPTS=CONCEPTS, OPERATORS=OPERATORS, suffix=suffix)
print(filename)
print("epoch: ", best_id_model)
print(update_val_acc_dict)
print("\n")
def get_df(dirname):
"""Get Pandas dataframe analysising acc."""
filenames = filter_filename(dirname, include=".p")
df_dict_list = []
for filename in filenames:
try:
data_record = pickle.load(open(dirname + filename, "rb"))
except Exception as e:
print("Error {} from file {}".format(e, filename))
args = init_args(update_default_hyperparam(data_record["args"]))
df_dict = {}
acc_dict = data_record["acc"]
for key in acc_dict:
best_id_acc = np.argmax(acc_dict['acc:mean:val'])
acc_repr = np.array([acc_dict[key] for key in acc_dict if key.startswith("acc:c_repr")]).mean(0)
acc_mask = np.array([acc_dict[key] for key in acc_dict if key.startswith("acc:mask") and "_0" not in key and "_1" not in key]).mean(0)
best_id_acc_repr = np.argmax(acc_repr)
best_id_acc_mask = np.argmax(acc_mask)
df_dict["epoch"] = acc_dict["epoch:val"][-1]
df_dict["best_epoch:acc"] = acc_dict["epoch:val"][best_id_acc]
df_dict["best_epoch:acc_repr"] = acc_dict["epoch:val"][best_id_acc_repr]
df_dict["best_epoch:acc_mask"] = acc_dict["epoch:val"][best_id_acc_mask]
df_dict["acc:c_repr:mean:val"] = np.max(acc_repr)
df_dict["acc:mask:mean:val"] = np.max(acc_mask)
if key == "epoch:val":
pass
elif key.startswith("acc:"):
df_dict[key] = np.max(acc_dict[key])
elif key.startswith("E:"):
df_dict[key] = acc_dict[key][best_id_acc]
else:
raise
df_dict.update(args.__dict__)
df_dict["filename"] = filename
df_dict_list.append(df_dict)
df = pd.DataFrame(df_dict_list)
info = {"args_keys": list(args.__dict__.keys()),
"acc_keys": [key for key in acc_dict.keys() if "_0" not in key and "_1" not in key],
}
return df, info
def get_bidirectional_graph(graph):
Dict = {"IsInside": "IsEnclosed",
"IsEnclosed": "IsInside",
}
graph_new = []
# Standardize:
def standardize_graph(graph):
new_graph = []
for ele in graph:
if isinstance(ele[0], list):
ele = (tuple(ele[0]), ele[1])
new_graph.append(ele)
return new_graph
new_graph = standardize_graph(graph)
graph_add = []
for ele in new_graph:
if isinstance(ele[0], tuple):
reverse_ele = ((ele[0][1], ele[0][0]), ele[1])
if reverse_ele not in new_graph:
graph_add.append(reverse_ele)
return new_graph + graph_add
# ### 1.1 Helper functions:
# In[ ]:
def load_model_hash(
hash_str,
is_dataset=False,
is_update_repr=False,
isplot=1,
mutual_exclusive_coef=None,
return_args=False,
update_keys=None,
load_epoch="best",
):
try:
load_epoch = eval(load_epoch)
except:
pass
subfolders = filter_filename(EXP_PATH, exclude=".")
is_found = False
for subfolder in subfolders:
if "evaluation" in subfolder:
continue
filenames = filter_filename(f"{EXP_PATH}/{subfolder}/", include=[hash_str, ".p"])
if len(filenames) == 1:
is_found = True
break
assert is_found, f"Did not find the experiment with hash_str '{hash_str}' under the subfolders of './{EXP_PATH}/'. Please check if the hash_str is correct."
filename = filenames[0]
data_record = pickle.load(open(f"{EXP_PATH}/{subfolder}/{filename}", "rb"))
if is_update_repr:
update_CONCEPTS_OPERATORS(CONCEPTS, OPERATORS, data_record["concept_embeddings"][-1], update_keys=update_keys)
test_concept_embedding(CONCEPTS, OPERATORS, data_record["concept_embeddings"][-1], raise_warnings_only=True, checked_keys=update_keys)
else:
test_concept_embedding(CONCEPTS, OPERATORS, data_record["concept_embeddings"][-1], checked_keys=update_keys)
args = init_args(update_default_hyperparam(data_record["args"]))
if isplot >= 1:
plot_acc(dirname, [filename], filter_mode="standard")
model, best_model_id = load_best_model(data_record,
keys=["mask|c_repr", "mask|c", "c_repr|mask", "c_repr|c"],
load_epoch=load_epoch,
return_id=True,
)
model.to(device)
info = {"load_id": best_model_id}
if return_args:
info["args"] = args
if is_dataset:
args.n_examples = 500
args.seed = 2
print("canvas_size: {}, color_avail: {}".format(args.canvas_size, args.color_avail))
dataset, args = get_dataset(args, is_load=True)
info["dataset"] = dataset
if isplot >= 2:
init = "mask-input"
sample_step = 150
batch_size = 36
ensemble_size = 16
plot_grey_scale = False
plot_ensemble_mode = "min"
args.lambd_start = 0.1
if mutual_exclusive_coef is None:
mutual_exclusive_coef = args.mutual_exclusive_coef
args.mutual_exclusive_coef = mutual_exclusive_coef
data = get_model_samples(model, args, dataset=dataset, init=init, sample_step=sample_step, batch_size=batch_size, ensemble_size=ensemble_size, plot_ensemble_mode=plot_ensemble_mode, plot_grey_scale=plot_grey_scale, CONCEPTS=CONCEPTS, OPERATORS=OPERATORS, device=device, isplot=True)
return model, info
# Build an empty selector:
def get_empty_selector(ebm_dict, CONCEPTS, OPERATORS):
selector = Concept_Pattern(
name=None,
value=Placeholder(Tensor(dtype="cat", range=range(10))),
attr={},
is_all_obj=True,
is_ebm=True,
is_selector_gnn=False,
is_default_ebm=False,
ebm_dict=ebm_dict,
CONCEPTS=CONCEPTS,
OPERATORS=OPERATORS,
device=device,
cache_forward=False,
in_channels=10,
z_mode="None",
w_type="image+mask",
mask_mode="concat",
aggr_mode="max",
pos_embed_mode="None",
is_ebm_share_param=True,
is_relation_z=False,
img_dims=2,
is_spec_norm=True,
act_name="leakyrelu0.2",
normalization_type="None",
)
return selector
def get_c_repr(c_str, num, device, mode):
if mode == "concept":
c_repr = CONCEPTS[c_str].get_node_repr().detach()[None].repeat_interleave(num, 0).to(device)
elif mode == "relation":
c_repr = OPERATORS[c_str].get_node_repr().detach()[None].repeat_interleave(num, 0).to(device)
else:
raise
return c_repr
def get_graph_info(info):
# Get all objects and their concepts:
graph_info = {"obj_type": {}, "relations": {}}
obj_masks = info["obj_masks"]
graph_info["obj_masks"] = obj_masks
for key, mask in obj_masks.items():
obj_type = classify_concept(mask)
graph_info["obj_type"][key] = obj_type
# Get relations:
for key, relation in info["obj_full_relations"].items():
relations_valid = {"SameShape", "SameColor", "IsInside"}
relation_ele_valid = set(relation).intersection(relations_valid)
if len(relation_ele_valid) == 0:
continue
if len(relation_ele_valid) == 2:
pass
graph_info["relations"][key] = list(relation_ele_valid)
graph_info["structure"] = info["structure"]
return graph_info
def get_concept_from_graph_info(graph_info):
attr_dict = {}
for key, obj_type in graph_info["obj_type"].items():
attr_dict["{}".format(key, obj_type)] = Placeholder(obj_type, value=graph_info["obj_masks"][key])
concept = Concept(
name="concept",
value=Placeholder(Tensor(dtype="cat", range=range(10))),
attr=attr_dict,
)
for key, relations in graph_info["relations"].items():
for relation in relations:
concept.add_relation_manual(relation, key[0], key[1])
return concept
def get_query_concept_pattern(query_type, graph_info):
def filter_relations(relations):
relations = deepcopy(relations)
keys_to_pop = []
for key, relation in relations.items():
if (key[1], key[0]) in relations and relations[(key[1], key[0])] == relation and key not in keys_to_pop:
keys_to_pop.append((key[1], key[0]))
for key in keys_to_pop:
relations.pop(key)
return relations
query_type = query_type.split("-")[-1]
obj_names = list(graph_info["obj_type"])
# graph_info = deepcopy(graph_info)
# graph_info["relations"] = filter_relations(graph_info["relations"])
concept = get_concept_from_graph_info(graph_info)
if query_type == "1c":
obj_type_avail = list(graph_info["obj_type"].values())
obj_type_query = np.random.choice(obj_type_avail)
query_key_candidates = [key for key, obj_type in graph_info["obj_type"].items() if obj_type == obj_type_query]
refer_masks = torch.stack([graph_info["obj_masks"][key] for key in query_key_candidates])
query = {
"graph": [(0, obj_type_query)],
"refer": 0,
}
elif query_type == "2a":
# [concept, (0, 1)/(1, 0), (refer)]
assert len(graph_info["relations"]) > 0
relation_id_selected = np.random.choice(len(graph_info["relations"]))
relation_key_selected = list(graph_info["relations"])[relation_id_selected]
key0, key1 = relation_key_selected
pivot_node_id = np.random.choice(2)
refer_node_id = 1 - pivot_node_id
pivot_node_key = relation_key_selected[pivot_node_id]
c_pattern = Concept_Pattern(
name=None,
value=Placeholder(Tensor(dtype="cat", range=range(10))),
attr={key0: Placeholder(graph_info["obj_type"][key0]),
key1: Placeholder(graph_info["obj_type"][key1]),
},
re={relation_key_selected: graph_info["relations"][relation_key_selected][0]},
refer_node_names=[relation_key_selected[refer_node_id]],
)
refer_masks = concept.get_refer_nodes(c_pattern, is_match_node=True)
refer_masks = {key: value.get_node_value() for key, value in refer_masks.items()}
query = {"graph": [((0,1),graph_info["relations"][relation_key_selected][0]), (pivot_node_id, graph_info["obj_type"][pivot_node_key])],
"refer": refer_node_id}
refer_masks = torch.stack(list(refer_masks.values()))
elif query_type == "3a":
# [concept, (0, 1)/(1, 0), (1,2)/(2,1), (refer)]
if graph_info["structure"] == ['pivot:Rect', (1, 0, 'IsInside'), '(concept)', (1, 2), '(refer)']:
query = {
"graph": [(0, "Rect"), ((1,0), "IsInside"), ((1,2), graph_info["relations"][(obj_names[1], obj_names[2])][0])],
"refer": 2,
}
refer_masks = graph_info["obj_masks"][obj_names[2]][None]
elif graph_info["structure"] == ["pivot", (0,1), "(concept)", (1,2), "(refer)"]:
query = {
"graph": [(0, graph_info["obj_type"][obj_names[0]]), ((0,1), graph_info["relations"][(obj_names[0], obj_names[1])][0]), ((1,2), graph_info["relations"][(obj_names[1], obj_names[2])][0])],
"refer": 2,
}
refer_masks = graph_info["obj_masks"][obj_names[2]][None]
else:
return None, None
elif query_type == "3b":
if graph_info["structure"] == ["pivot", "pivot", (0,2), (1,2), "(refer)"]:
query = {
"graph": [(0, graph_info["obj_type"][obj_names[0]]),
(1, graph_info["obj_type"][obj_names[1]]),
((0,2), graph_info["relations"][(obj_names[0], obj_names[2])][0]),
((1,2), graph_info["relations"][(obj_names[1], obj_names[2])][0]),
],
"refer": 2,
}
refer_masks = graph_info["obj_masks"][obj_names[2]][None]
else:
return None, None
return query, refer_masks
def get_all_queries(dataset, query_type, seed=2, isplot=False):
set_seed(seed)
query_all_dict = {}
query_type = query_type.split("-")[-1]
for i in range(len(dataset)):
input, target, infos = get_inputs_targets_EBM(dataset[i])
input = torch.stack(list(input[0].values())).to(device)
for j in range(len(input)):
graph_info = get_graph_info(infos[j])
query, refer_masks = get_query_concept_pattern(query_type, graph_info)
if query is not None:
record_data(query_all_dict, [input[j:j+1], query, refer_masks], ["input", "query", "refer_masks"])
if isplot:
visualize_matrices(input[j:j+1].argmax(1))
print(query)
plot_matrices(refer_masks)
print("\n\n")
return query_all_dict
def get_selector_from_graph(graph, ebm_dict, CONCEPTS, OPERATORS):
def get_is_exist(selector, node_name):
return node_name in [ele.split(":")[0] for ele in list(selector.nodes)]
selector = get_empty_selector(ebm_dict, CONCEPTS, OPERATORS)
for i, item in enumerate(graph):
if isinstance(item[0], tuple):
obj0 = "obj_{}".format(item[0][0]) if get_is_exist(selector, "obj_{}".format(item[0][0])) else None
obj1 = "obj_{}".format(item[0][1]) if get_is_exist(selector, "obj_{}".format(item[0][1])) else None
if obj0 is not None and obj1 is None:
selector.add_relation_manual(item[1], obj0)
elif obj0 is None and obj1 is not None:
selector.add_relation_manual(item[1], None, obj1)
elif obj0 is None and obj1 is None:
selector.add_relation_manual(item[1])
else:
assert obj0 is not None and obj1 is not None
selector.add_relation_manual(item[1], obj0, obj1)
else:
selector.add_obj(CONCEPTS[item[1]], add_obj_name="obj_{}".format(item[0]))
if "refer" in graph:
selector.set_refer_nodes("obj_{}".format(graph["refer"]))
return selector
def get_selector_for_parsing(keys_dict, ebm_dict, CONCEPTS, OPERATORS):
"""E.g. keys_dict = {"Line": 3, "SameShape": 4}"""
selector = get_empty_selector(ebm_dict, CONCEPTS, OPERATORS)
for key, count in keys_dict.items():
if key in CONCEPTS:
for i in range(count):
selector.add_obj(CONCEPTS[key])
elif key in OPERATORS:
for i in range(count):
selector.add_relation_manual(key)
else:
raise
return selector
def get_concept_graph(c_type, is_new_vertical=True, is_bidirectional_re=False, is_concept=True, is_relation=True):
if is_new_vertical:
if not is_bidirectional_re:
graph_gt_dict = {
"Line": [
(0, "Line"),
],
"2-Line": [
(0, "Line"),
(1, "Line"),
],
"3-Line": [
(0, "Line"),
(1, "Line"),
(2, "Line"),
],
"Parallel": [
((0, 1), "Parallel"),
],
"VerticalMid": [
((0, 1), "VerticalMid"),
],
"VerticalEdge": [
((0, 1), "VerticalEdge"),
],
"Eshape": [
(0, "Line"),
(1, "Line"),
(2, "Line"),
(3, "Line"),
((0, 1), 'VerticalEdge'),
((0, 2), 'VerticalMid'),
((0, 3), 'VerticalEdge'),
((1, 2), 'Parallel'),
((1, 3), 'Parallel'),
((2, 3), 'Parallel'),
],
"Fshape": [
(0, "Line"),