-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathretrieveGraph.py
1628 lines (1476 loc) · 66 KB
/
retrieveGraph.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
"""
Filter out candidates using vectors created from COPT and spectral methods. Then classify with GW or other methods on the reduced number of candidates.
"""
import _init_paths
import utils
import graph
import lib.graph as gwGraph
import networkx as nx
import torch
from lib.ot_distances import Fused_Gromov_Wasserstein_distance
import numpy as np
import pickle
from tqdm import tqdm
from torch.utils.data.dataloader import DataLoader
from torch.utils.data import Dataset
from sklearn.model_selection import GridSearchCV
import got_stochastic as st
import torch.nn as nn
import sys
import runGraph
import os
import math
import netlsd
from sklearn.pipeline import Pipeline
import grakel
from sklearn.svm import SVC
import pickle
import time
import pdb
#optional
torch.set_default_tensor_type('torch.DoubleTensor')
def classify_svm_var_len(dataset, data_idx, query_idx, args, node_labels, q_labels, dataset_cls=None, tgt_cls=None, data_sketch=None, C_opt=None):
# pdb.set_trace()
assert data_sketch is not None
all_graphs = []
#pdb.set_trace()
min_label = min([l.min().item() for l in node_labels])
max_label = max([l.max().item() for l in node_labels])
#pdb.set_trace()
for i, sketch in enumerate(data_sketch):
adj = -reconstruct_mx(sketch)
n_nodes = len(adj)
eye = torch.eye(n_nodes)
adj /= adj.diag().sum().abs()
adj[eye>0] = 0
adj = adj.numpy()
###
#adj = np.eye(n_nodes)
###
#adj_l.append(adj)
#node2attr = {node:lap[node] for node in range(len(adj))}
#node2attr = [lap[node] for node in range(len(adj))]
cur_node_labels = node_labels[i].numpy()
node2attr = {node:cur_node_labels[node] for node in range(n_nodes)}
all_graphs.append([adj, node2attr])
train_graphs = [all_graphs[i] for i in data_idx] #[torch.from_numpy(data_idx)]
test_graphs = [all_graphs[i] for i in query_idx] #[torch.from_numpy(query_idx)]
train_cls = np.array([dataset_cls[i] for i in data_idx])
L = 2
if L != 3:
sys.stdout.write('L! {}'.format( L))
#pdb.set_trace()
do_grid_search = args.grid_search #False #True #False
if C_opt is None and do_grid_search:
print('Doing grid search!')
time0 = time.time()
gk = grakel.GraphKernel(kernel=[{"name": "multiscale_laplacian", 'which':'fast', 'L':L, 'n_samples':100}], normalize=True)
C_opt = grid_search(gk, train_graphs, train_cls)
grid_dur = np.round((time.time()-time0)/60, 2)
sys.stdout.write('C_opt found {} dur {} '.format(C_opt, grid_dur))
#for train_idx, train_size in enumerate([0.7]):
#average_acc, std_acc, average_time = ComputeAccuracy.ComputeAccuracy(all_graphs, dataset_cls, test_size=round(1-train_size,1), n_runs=2, cv_folds = 5) #n_runs=5
gk = grakel.GraphKernel(kernel=[{"name": "multiscale_laplacian", 'L':L}], normalize=True) ##normalize!?
else:
C_opt = 1 if C_opt is None else C_opt
use_lap = True #False
if use_lap:
if args.fast:
#try to find best C using subset of data
#gk = grakel.GraphKernel(kernel=[{"name": "multiscale_laplacian_fast", 'L':L, 'n_samples':150}], normalize=True)
gk = grakel.GraphKernel(kernel=[{"name": "multiscale_laplacian", 'which':'fast', 'L':L, 'n_samples':100}], normalize=True)
#using MultiscaleLaplacianFast is actually very slow
#gk = grakel.MultiscaleLaplacianFast(L=L, normalize=True, n_samples=150)
else:
gk = grakel.GraphKernel(kernel=[{"name": "multiscale_laplacian", 'L':L}], normalize=True) ##normalize!?
#
#gk = grakel.MultiscaleLaplacian(L=3, normalize=True)
else:
gk = grakel.GraphKernel(kernel=[{"name": "pyramid_match"}], normalize=True) ##normalize!?
G2 = []
for g in all_graphs:
node2idx = {}
for k, v in g[1].items():
#pdb.set_trace()
node2idx[k] = np.argmax(v)
g[1] = node2idx
G2.append(g)
all_graphs = G2
train_graphs = [all_graphs[i] for i in data_idx] #[torch.from_numpy(data_idx)]
test_graphs = [all_graphs[i] for i in query_idx] #[torch.from_numpy(query_idx)]
time0 = time.time()
k_train = gk.fit_transform(train_graphs)
k_test = gk.transform(test_graphs)
#clf = SVC(kernel='precomputed') #, C=10)
clf = SVC(kernel='precomputed', C=C_opt)
clf.fit(k_train, train_cls)
fit_dur = np.round((time.time()-time0)/60, 2)
sys.stdout.write(' time for actually fitting {}'.format(fit_dur))
pred = clf.predict(k_test)
acc = np.equal(pred.reshape(-1), tgt_cls).sum() / len(k_test)
accs = acc
print('cls acc {}'.format(accs))
return accs, data_sketch, C_opt
def grid_search(gk, train_graphs, y_train):
#k_test = gk.transform(test_graphs)
n_total = min(150, len(train_graphs))
n_train = int(n_total*.33)
train_g = train_graphs[:n_train]
train_cls = y_train[:n_train]
test_g = train_graphs[n_train:n_total]
test_cls = y_train[n_train:n_total]
train_g = gk.fit_transform(train_g)
test_g = gk.transform(test_g)
C_l = [1, 10]
accs = np.zeros(len(C_l))
for i, cur_C in enumerate(C_l):
clf = SVC(kernel='precomputed', C=cur_C)
clf.fit(train_g, train_cls)
pred = clf.predict(test_g)
acc = np.equal(pred.reshape(-1), test_cls).sum() / len(test_cls)
accs[i] = acc
sys.stdout.write('acc for various C {}'.format(accs))
C_opt = C_l[accs.argmax()]
return C_opt
def grid_search_slow(gk, G_train, y_train):
svc = SVC(kernel='precomputed')
param_grid = {'svc__C': [1.5, 10]}
estimator = Pipeline([('kernel', gk), ('svc',svc)])
clf = GridSearchCV(estimator=estimator, param_grid=param_grid, cv=2)
#print(clf.get_params().keys())
clf.fit(G_train, y_train)
C_best = clf.best_estimator_.named_steps['svc'].C
return C_best
def cross_validate(all_graphs, tgt):
kernels = []
for i in range(2, 7):
gk = grakel.GraphKernel(kernel=[{"name": "multiscale_laplacian", 'n_iter':i}], normalize=True) ##normalize!?
kernel = gk.fit_transform()
kernels.append(kernel)
k_fold = 3
accs = grakel.utils.cross_validate_Kfold_SVM([kernels], tgt, n_iter=10, n_splits=k_fold)
print('{} fold cross validation accuracies {}'.format(k_fold, accs))
def reconstruct_mx(upper):
#reconstruct full mx from upper triangular part
n_nodes = int(-.5 + np.sqrt(.25 + 2*len(upper)))
#
mx = torch.zeros((n_nodes, n_nodes))
ones = torch.ones((n_nodes, n_nodes))
try:
mx[ones.triu()>0] = upper
except Exception:
print('exception!')
pdb.set_trace()
mx += mx.triu(diagonal=1).t()
return mx
def classify_graphs(dataset, queries, args, node_labels, q_labels, dataset_cls=None, tgt_cls=None):#dataset_cls, target, args):
"""
Initial dataset filtering to filter out candidates for GW distance.
dataset: dataset of laplacians, not sketched yet
"""
print('using netlsd')
#with open(args.graph_fname, 'rb') as f:
# graphs = pickle.read(f)
n_data = len(dataset)
n_queries = len(queries)
#ot_cost = np.zeros((len(queries), len(dataset)))
gw_cost = np.zeros((len(queries), len(dataset)))
#gwdist = Fused_Gromov_Wasserstein_distance(alpha=args.alpha,features_metric='sqeuclidean')
Ly_mx = []
Lx_mx = []
data_graphs = []
Ly_n = []
dataset_cls1 = []
labels = []
heat_l = []
for i, data in enumerate(tqdm(dataset)):
n_nodes = len(data)
#assert n_nodes >= 10
#L = utils.graph_to_lap(data)
#sketch
#args.Lx = utils.graph_to_lap(g) #graph.graph_dist(args, plot=False)
args.Lx = data
args.m = len(args.Lx)
args.n = math.ceil(args.m/args.compress_fac)
loss, P, Ly = graph.graph_dist(args, plot=False)
#pdb.set_trace()
#pdb.set_trace()
#lo_graphs.append(Ly)
if False: #True: #False:
cur_labels = node_labels[i][P.argmax(0)]
#Ly_mx.append(L[torch.triu(torch.ones(n_nodes, n_nodes), diagonal=1) > 0])
#order node labels
L_ordering = Ly.diag().argsort(descending=True)
cur_labels = cur_labels[L_ordering] ####
labels.append(cur_labels)
L = utils.canonicalize_mx(Ly)
heat_l.append(netlsd.heat(L.numpy()))
'''
L = L[ones > 0]
Ly_n.append( (L**2).sum())#.sqrt())
Ly_mx.append(L)
'''
cur_ranks_ = torch.zeros(n_queries, args.k, dtype=torch.int64)
#pdb.set_trace()
for i, q in enumerate(tqdm(queries, desc='queries')):
#Lx = utils.graph_to_lap(q)
args.Lx = q
args.m = len(q)
args.n = math.ceil(args.m/args.compress_fac) #args.lo_dim #
loss, P, Lx = graph.graph_dist(args, plot=False)
#q_graph = gwGraph.Graph(queries0[i])
#Lx_mx.append(args.Lx)
Lx_n = (args.Lx**2).sum() #.sqrt()
if False: #True: #False:
#pdb.set_trace()
cur_labels = q_labels[i][P.argmax(0)]
#Ly_mx.append(L[torch.triu(torch.ones(n_nodes, n_nodes), diagonal=1) > 0])
#order node labels
#pdb.set_trace()
L_ordering = Lx.diag().argsort(dim=0)
q_label = cur_labels[L_ordering] ###
Lx = utils.canonicalize_mx(Lx) #[ones > 0]
##Lx = torch.cat((Lx, q_label*.03), -1)
#pdb.set_trace()
#dist = Lx_n + Ly_n - 2*torch.mm(Lx.view(1, -1), data_t.t()).view(-1)
#pdb.set_trace()
#dist = torch.abs(Lx.view(1,-1) - data_t).sum(-1)
#'''
dist = []
heat_q = netlsd.heat(Lx.numpy())
for j,d in enumerate(heat_l):
#dist.append(torch.norm(Lx-d, 1) )
dist.append(netlsd.compare(heat_q, heat_l[j]))
dist = torch.Tensor(dist)
#'''
cur_ranks_[i] = torch.topk(dist, args.k, largest=False)[1] #np.argpartition(dist, args.k)[:args.k]
#cur_cls = dataset_cls[cur_ranks_[i]]
#pdb.set_trace()
if dataset_cls is not None:
pdb.set_trace()
pred = dataset_cls[cur_ranks_[:, 0].numpy()]
acc1 = np.equal(pred, tgt_cls).sum()
print('top 1 acc using just mx dist ! {}'.format(acc1/n_queries))
# top-ten voting #
dataset_cls = torch.from_numpy(dataset_cls)
ones = torch.ones(50)
pred10 = np.zeros(n_queries)
for i, q in enumerate(queries):
#cur_ranks = dataset_cls_t[ot_cost_ranks[i]]
ranked = torch.zeros(100) #n_cls*2
cur_ranks = dataset_cls[cur_ranks_[i, :30]]
ranked.scatter_add_(src=ones, index=cur_ranks, dim=-1)
#pdb.set_trace()
pred10[i] = torch.argmax(ranked).item()
acc10 = np.equal(pred, tgt_cls).sum()
print('top 30 voting acc using just mx dist ! {}'.format(acc10/n_queries))
return cur_ranks_
def classify_l1_var_len(dataset, data_idx, query_idx, args, node_labels, q_labels, dataset_cls=None, tgt_cls=None, data_sketch=None):
"""
Initial dataset filtering to filter out candidates for GW distance.
dataset: dataset of laplacians, not sketched yet
"""
print('using sketching l1 var len')
n_data = len(data_idx)
n_queries = len(query_idx)
max_len = max([len(l) for l in dataset])
#max_len = (max_len//5+1)*max_len//5 //2
max_len = (math.ceil(max_len/args.compress_fac)+1)*math.ceil(max_len/args.compress_fac) //2
Lx_mx = []
data_graphs = []
Ly_n = []
dataset_cls1 = []
labels = []
#heat_l = []
if data_sketch is None:
data_sketch = []
for i, data in enumerate(tqdm(dataset)):
n_nodes = len(data)
#L = utils.graph_to_lap(data)
#sketch
#args.Lx = utils.graph_to_lap(g) #graph.graph_dist(args, plot=False)
args.Lx = data
args.m = len(args.Lx)
args.n = math.ceil(args.m/args.compress_fac)
loss, P, Ly = graph.graph_dist(args, plot=False)
ones = torch.ones(args.n, args.n).triu()
if False: #True: #False:
cur_labels = node_labels[i][P.argmax(0)]
#Ly_mx.append(L[torch.triu(torch.ones(n_nodes, n_nodes), diagonal=1) > 0])
#order node labels
L_ordering = Ly.diag().argsort(descending=True)
cur_labels = cur_labels[L_ordering] ####
labels.append(cur_labels)
L = utils.canonicalize_mx(Ly)
#'''
L = L[ones > 0]
#Ly_n.append( (L**2).sum())#.sqrt())
#Ly_mx.append(L)
cur_max_len = min(max_len, len(L))
#Ly_mx[i][:cur_max_len] = L[:cur_max_len]
data_sketch.append(L[:cur_max_len])
#'''
#torch.save(data_sketch, '{}_data_sketch.pt'.format(dataset_name))
Ly_mx = torch.zeros(n_data, max_len)
for i, d_idx in enumerate(data_idx):
cur_len = min(len(data_sketch[d_idx]), max_len)
Ly_mx[i][:cur_len] = data_sketch[d_idx][:cur_len] #Ly_mx[:cur_max_len]
#torch.save(Ly_mx, 'enzyme_data_lap.pt')
#labels = torch.stack(labels)
#data_t = torch.stack(Ly_mx) #.t()
data_t = Ly_mx
#data_t = torch.cat((data_t, labels*.03), -1)
##Ly_n = torch.Tensor(Ly_n)
cur_ranks_ = torch.zeros(n_queries, args.k, dtype=torch.int64)
for i, q_idx in enumerate(tqdm(query_idx, desc='queries')):
'''
args.Lx = q
args.m = len(q)
args.n = math.ceil(args.m/5) #args.lo_dim #
loss, P, Lx = graph.graph_dist(args, plot=False)
ones = torch.ones(args.n, args.n).triu()
#Lx_mx.append(args.Lx)
Lx_n = (args.Lx**2).sum() #.sqrt()
if False: #True: #False:
#pdb.set_trace()
cur_labels = q_labels[i][P.argmax(0)]
#Ly_mx.append(L[torch.triu(torch.ones(n_nodes, n_nodes), diagonal=1) > 0])
#order node labels
#pdb.set_trace()
L_ordering = Lx.diag().argsort(descending=True)
q_label = cur_labels[L_ordering] ###
Lx = utils.canonicalize_mx(Lx)[ones > 0]
'''
#cur_max_len = min(max_len, len(Lx))
Lx_ = torch.zeros(max_len)
Lx_[:len(data_sketch[q_idx])] = data_sketch[q_idx]
##Lx = torch.cat((Lx, q_label*.03), -1)
#pdb.set_trace()
#dist = Lx_n + Ly_n - 2*torch.mm(Lx.view(1, -1), data_t.t()).view(-1)
#pdb.set_trace()
dist = torch.abs(Lx_.view(1,-1) - data_t).sum(-1)
'''
dist = []
heat_q = netlsd.heat(Lx.numpy())
for j,d in enumerate(heat_l):
#dist.append(torch.norm(Lx-d, 1) )
dist.append(netlsd.compare(heat_q, heat_l[j]))
dist = torch.Tensor(dist)
'''
cur_ranks_[i] = torch.topk(dist, args.k, largest=False)[1] #np.argpartition(dist, args.k)[:args.k]
#cur_cls = dataset_cls[cur_ranks_[i]]
#pdb.set_trace()
if dataset_cls is not None:
#pdb.set_trace()
pred = dataset_cls[cur_ranks_[:, 0].numpy()]
acc1 = np.equal(pred, tgt_cls).sum()
print('top 1 acc using just mx dist ! {}'.format(acc1/n_queries))
if True:
return acc1/n_queries, data_sketch #cur_ranks_
# top-ten voting #
dataset_cls = torch.from_numpy(dataset_cls)
ones = torch.ones(50)
pred10 = np.zeros(n_queries)
for i, q in enumerate(query_idx):
#cur_ranks = dataset_cls_t[ot_cost_ranks[i]]
ranked = torch.zeros(100) #n_cls*2
cur_ranks = dataset_cls[cur_ranks_[i, :30]]
ranked.scatter_add_(src=ones, index=cur_ranks, dim=-1)
#pdb.set_trace()
pred10[i] = torch.argmax(ranked).item()
acc10 = np.equal(pred, tgt_cls).sum()
print('top 30 voting acc using just mx dist ! {}'.format(acc10/n_queries))
return cur_ranks_
def classify_netlsd_var_len(dataset, data_idx, query_idx, args, node_labels, q_labels, dataset_cls=None, tgt_cls=None, data_sketch=None):
"""
Initial dataset filtering to filter out candidates for GW distance.
dataset: dataset of laplacians, not sketched yet
"""
print('using netlsd var len')
n_data = len(data_idx)
n_queries = len(query_idx)
max_len = max([len(l) for l in dataset])
#max_len = (max_len//5+1)*max_len//5 //2
#five-fold compression, put in args
max_len = (math.ceil(max_len/args.compress_fac)+1)*math.ceil(max_len/args.compress_fac) //2
Lx_mx = []
data_graphs = []
Ly_n = []
dataset_cls1 = []
labels = []
heat_l = []
if data_sketch is None:
data_sketch = []
for i, data in enumerate(tqdm(dataset)):
n_nodes = len(data)
#L = utils.graph_to_lap(data)
#sketch
#args.Lx = utils.graph_to_lap(g) #graph.graph_dist(args, plot=False)
args.Lx = data
args.m = len(args.Lx)
args.n = math.ceil(args.m/args.compress_fac)
loss, P, Ly = graph.graph_dist(args, plot=False)
ones = torch.ones(args.n, args.n).triu()
if False: #True: #False:
cur_labels = node_labels[i][P.argmax(0)]
#Ly_mx.append(L[torch.triu(torch.ones(n_nodes, n_nodes), diagonal=1) > 0])
#order node labels
L_ordering = Ly.diag().argsort(descending=True)
cur_labels = cur_labels[L_ordering] ####
labels.append(cur_labels)
L = utils.canonicalize_mx(Ly)
#'''
L = L[ones > 0]
#Ly_n.append( (L**2).sum())#.sqrt())
#Ly_mx.append(L)
cur_max_len = min(max_len, len(L))
#Ly_mx[i][:cur_max_len] = L[:cur_max_len]
data_sketch.append(L[:cur_max_len])
#'''
def reconstruct_mx(upper):
#reconstruct full mx from upper triangular part
n_nodes = int(-.5 + np.sqrt(.25 + 2*len(upper)))
#
mx = torch.zeros((n_nodes, n_nodes))
ones = torch.ones((n_nodes, n_nodes))
try:
mx[ones.triu()>0] = upper
except Exception:
print('exception!')
pdb.set_trace()
mx += mx.triu(diagonal=1).t()
return mx
Ly_mx = torch.zeros(n_data, max_len)
for i, d_idx in enumerate(data_idx):
#Ly_mx[i][:len(data_sketch[d_idx])] = data_sketch[d_idx] #Ly_mx[:cur_max_len]
L = reconstruct_mx(data_sketch[d_idx])
#pdb.set_trace()
heat_l.append(netlsd.heat(L.numpy())) #reconstruct! #try normalization!?
#torch.save(Ly_mx, 'enzyme_data_lap.pt')
#labels = torch.stack(labels)
#data_t = torch.stack(Ly_mx) #.t()
data_t = Ly_mx
#data_t = torch.cat((data_t, labels*.03), -1)
##Ly_n = torch.Tensor(Ly_n)
cur_ranks_ = torch.zeros(n_queries, args.k, dtype=torch.int64)
all_dist = torch.zeros(n_queries, len(heat_l))
for i, q_idx in enumerate(tqdm(query_idx, desc='queries')):
'''
args.Lx = q
args.m = len(q)
args.n = math.ceil(args.m/5) #args.lo_dim #
loss, P, Lx = graph.graph_dist(args, plot=False)
ones = torch.ones(args.n, args.n).triu()
#Lx_mx.append(args.Lx)
Lx_n = (args.Lx**2).sum() #.sqrt()
if False: #True: #False:
#pdb.set_trace()
cur_labels = q_labels[i][P.argmax(0)]
#Ly_mx.append(L[torch.triu(torch.ones(n_nodes, n_nodes), diagonal=1) > 0])
#order node labels
#pdb.set_trace()
L_ordering = Lx.diag().argsort(descending=True)
q_label = cur_labels[L_ordering] ###
Lx = utils.canonicalize_mx(Lx)[ones > 0]
'''
#cur_max_len = min(max_len, len(Lx))
#Lx_ = torch.zeros(max_len)
#Lx_[:len(data_sketch[q_idx])] = data_sketch[q_idx]
##Lx = torch.cat((Lx, q_label*.03), -1)
#pdb.set_trace()
#dist = Lx_n + Ly_n - 2*torch.mm(Lx.view(1, -1), data_t.t()).view(-1)
#pdb.set_trace()
#dist = torch.abs(Lx_.view(1,-1) - data_t).sum(-1)
#'''
dist = []
L = reconstruct_mx(data_sketch[q_idx])
heat_q = netlsd.heat(L.numpy()) ##reconstruct!
for j,d in enumerate(heat_l):
#dist.append(torch.norm(Lx-d, 1) )
dist.append(netlsd.compare(heat_q, heat_l[j]))
dist = torch.Tensor(dist)
#'''
#cur_ranks_[i] = torch.topk(dist, args.k, largest=False)[1] #np.argpartition(dist, args.k)[:args.k]
cur_ranks_[i] = torch.topk(dist, args.k, largest=False)[1]
all_dist[i] = dist #torch.topk(dist, len(dist), largest=False)[0]
#cur_cls = dataset_cls[cur_ranks_[i]]
#pdb.set_trace()
print('top ranks ', cur_ranks_.squeeze())
train_cls = np.array([dataset_cls[i] for i in data_idx])
if dataset_cls is not None:
#pdb.set_trace()
pred = train_cls[cur_ranks_[:, 0].numpy()]
acc1 = np.equal(pred, tgt_cls).sum()
print('top 1 acc using just mx dist ! {}'.format(acc1/n_queries))
###
n_cls = 2
pred_cls = []
for i in range(len(all_dist)):
best_cls, best_dist = -1, sys.maxsize
for c in [0,1]: #range(n_cls):
cur_dist = all_dist[i][dataset_cls==c].mean().item()
if cur_dist < best_dist:
best_dist, best_cls = cur_dist, c
pred_cls.append(best_cls)
acc2 = np.equal(np.array(pred_cls), tgt_cls).sum()/n_queries
print('AVG dist acc ', acc2)
###
if True:
return acc1/n_queries, data_sketch #cur_ranks_
def sketch_dataset_dim(dataset, node_labels, args, method):
"""
Sketch dataset using the desired method to the desired cardinalities.
Input: dataset given as graph Laplacians.
Returns: compressed graph Laplacians.
"""
Ly_l = []
n = args.lo_dim
if method == 'copt':
for i, data in enumerate(tqdm(dataset, desc='sketching')):
args.n = lo_dim
args.n_epochs = 230 #250
args.Lx = utils.graph_to_lap(g) #graph.graph_dist(args, plot=False)
args.m = len(args.Lx)
loss, P, Ly = graph.graph_dist(args, plot=False)
Ly_l.append(Ly)
'''
if s:
m = len(data)
compress_ratio = args.lo_dim / m
if method in ['heavy_edge', 'variational_neightborhood', 'variation_edges', 'affinity_GS', 'algebraic_JC']:
C, Gc, Call, Gall = coarsen(g, K=k, r=r, method=method)
compress_ratio = s
args.n = math.ceil(args.m/args.compress_fac)
elif method == 'otc':
s
elif method == 'copt':
'''
return Ly_l
def sketch_dataset(dataset, node_labels, args, tgt_n=None):
"""
Sketch a given dataset to desired compress factor.
Input: dataset is given as as Laplacian matrices of graphs.
"""
max_len = max([len(g) for g in dataset])
#max_len = (max_len//args.compress_fac+1)*max_len//args.compress_fac //2
data_sketch = []
P_sketch = []
#all_node_labels
min_label = min([min(l) for l in node_labels])
max_label = max([max(l) for l in node_labels])
pdb.set_trace()
node_labels -= min_label ###
n_labels = int(max_label - min_label) + 1
#cls_labels_ = torch.arange(max_label-min_label).unsqueeze(-1)
normalize_Ly = False # True Normalize during runtime for flexibility
for i, data in enumerate(tqdm(dataset)):
n_nodes = len(data)
#L = utils.graph_to_lap(data)
#sketch
#args.Lx = utils.graph_to_lap(g) #graph.graph_dist(args, plot=False)
args.Lx = data
args.m = len(args.Lx)
args.n = math.ceil(args.m/args.compress_fac) if tgt_n is None else tgt_n
#P has shape eg 19x7
loss, P, Ly = graph.graph_dist(args, plot=False)
if normalize_Ly:
Ly /= n_nodes
###
#Ly /= Ly.diag().sum()
ones = torch.ones(args.n, args.n).triu()
#compressed number of nodes
n_comp = P.shape[1]
if True: #True: #False:
#pdb.set_trace()
#cls_labels = cls_labels_.repeat(1, n_nodes)
prob_labels = torch.zeros(n_labels, n_comp )
cur_labels = torch.from_numpy(node_labels[i]).to(torch.int64).unsqueeze(-1).expand(-1, n_comp)
#temp = 1 #2
#probs = torch.nn.functional.softmax(P/temp, dim=0)
probs = P / P.sum(0, keepdim=True)
try:
prob_labels.scatter_add_(index=cur_labels, src=probs, dim=0)
except RuntimeError as e:
print('scatter add error!')
pdb.set_trace()
cur_labels = prob_labels.t() #node_labels[i][P.argmax(0)]
###cur_labels = node_labels[i][P.argmax(0)]
#order node labels to be consistent with canonicalization
L_ordering = Ly.diag().argsort(dim=0)
cur_labels = cur_labels[L_ordering] ####
#labels.append(cur_labels)
L = utils.canonicalize_mx(Ly)
#pdb.set_trace()
#'''
L = L[ones > 0]
#Ly_n.append( (L**2).sum())#.sqrt())
#Ly_mx.append(L)
#cur_max_len = min(max_len, len(L))
##data_sketch.append(L[:cur_max_len])
data_sketch.append(L)
P_sketch.append(cur_labels)
#'''
#torch.save(data_sketch, '{}_data_sketch.pt'.format(dataset_name))
return data_sketch, P_sketch
def classify_mutag_l1(dataset, queries, args, node_labels, q_labels, dataset_cls=None, tgt_cls=None):#dataset_cls, target, args):
"""
Can be used for classifying real world graphs eg enzymes or mutag dataset.
dataset: laplacians of sketched graphs.
"""
#with open(args.graph_fname, 'rb') as f:
# graphs = pickle.read(f)
n_data = len(dataset)
n_queries = len(queries)
#ot_cost = np.zeros((len(queries), len(dataset)))
gw_cost = np.zeros((len(queries), len(dataset)))
#gwdist = Fused_Gromov_Wasserstein_distance(alpha=args.alpha,features_metric='sqeuclidean')
Ly_mx = []
Lx_mx = []
data_graphs = []
Ly_n = []
args.lo_dim = 8
ones = torch.ones(args.lo_dim, args.lo_dim).triu()
dataset_cls1 = []
labels = []
heat_l = []
for i, data in enumerate(tqdm(dataset)):
n_nodes = len(data)
#assert n_nodes >= 10
#L = utils.graph_to_lap(data)
#sketch
#args.Lx = utils.graph_to_lap(g) #graph.graph_dist(args, plot=False)
args.Lx = data
args.m = len(args.Lx)
args.n = args.lo_dim #8 #math.ceil(args.m/5)
loss, P, Ly = graph.graph_dist(args, plot=False)
#pdb.set_trace()
#pdb.set_trace()
#lo_graphs.append(Ly)
if False: #True: #False:
cur_labels = node_labels[i][P.argmax(0)]
#Ly_mx.append(L[torch.triu(torch.ones(n_nodes, n_nodes), diagonal=1) > 0])
#order node labels
L_ordering = Ly.diag().argsort(descending=True)
cur_labels = cur_labels[L_ordering] ####
labels.append(cur_labels)
L = utils.canonicalize_mx(Ly)
L = L[ones > 0]
Ly_n.append( (L**2).sum())#.sqrt())
Ly_mx.append(L)
#heat_l.append(netlsd.heat(L.numpy()))
#data_graphs.append(gwGraph.Graph(dataset0[i]))
#torch.save(Ly_mx, 'enzyme_data_lap.pt')
#labels = torch.stack(labels)
data_t = torch.stack(Ly_mx) #.t()
#data_t = torch.cat((data_t, labels*.03), -1)
##Ly_n = torch.Tensor(Ly_n)
cur_ranks_ = torch.zeros(n_queries, args.k, dtype=torch.int64)
#pdb.set_trace()
for i, q in enumerate(tqdm(queries, desc='queries')):
#Lx = utils.graph_to_lap(q)
args.Lx = q
args.m = len(q)
args.n = args.lo_dim #math.ceil(args.m/5)
loss, P, Lx = graph.graph_dist(args, plot=False)
#q_graph = gwGraph.Graph(queries0[i])
#Lx_mx.append(args.Lx)
Lx_n = (args.Lx**2).sum() #.sqrt()
if False: #True: #False:
#pdb.set_trace()
cur_labels = q_labels[i][P.argmax(0)]
#Ly_mx.append(L[torch.triu(torch.ones(n_nodes, n_nodes), diagonal=1) > 0])
#order node labels
#pdb.set_trace()
L_ordering = Lx.diag().argsort(descending=True)
q_label = cur_labels[L_ordering] ###
Lx = utils.canonicalize_mx(Lx)[ones > 0]
#Lx = torch.cat((Lx, q_label*.03), -1)
#pdb.set_trace()
#dist = Lx_n + Ly_n - 2*torch.mm(Lx.view(1, -1), data_t.t()).view(-1)
#pdb.set_trace()
dist = torch.abs(Lx.view(1,-1) - data_t).sum(-1)
'''
dist = []
heat_q = netlsd.heat(Lx.numpy())
for j,d in enumerate(Ly_mx):
#dist.append(torch.norm(Lx-d, 1) )
dist.append(netlsd.compare(heat_q, heat_l[i]))
dist = torch.Tensor(dist)
'''
cur_ranks_[i] = torch.topk(dist, args.k, largest=False)[1] #np.argpartition(dist, args.k)[:args.k]
#cur_cls = dataset_cls[cur_ranks_[i]]
#pdb.set_trace()
if dataset_cls is not None:
pdb.set_trace()
pred = dataset_cls[cur_ranks_[:, 0].numpy()]
acc1 = np.equal(pred, tgt_cls).sum()
print('top 1 acc using just mx dist ! {}'.format(acc1/n_queries))
# top-ten voting #
dataset_cls = torch.from_numpy(dataset_cls)
ones = torch.ones(50)
pred10 = np.zeros(n_queries)
for i, q in enumerate(queries):
#cur_ranks = dataset_cls_t[ot_cost_ranks[i]]
ranked = torch.zeros(100) #n_cls*2
cur_ranks = dataset_cls[cur_ranks_[i, :30]]
ranked.scatter_add_(src=ones, index=cur_ranks, dim=-1)
#pdb.set_trace()
pred10[i] = torch.argmax(ranked).item()
acc10 = np.equal(pred, tgt_cls).sum()
print('top 30 voting acc using just mx dist ! {}'.format(acc10/n_queries))
return cur_ranks_
def classify_l1_var_len_(dataset, data_idx, query_idx, args, node_labels, q_labels, dataset_cls=None, tgt_cls=None, data_sketch=None):
"""
Initial dataset filtering to filter out candidates for GW distance.
dataset: dataset of laplacians, not sketched yet
"""
print('using sketching l1 var len')
n_data = len(data_idx)
n_queries = len(queries)
max_len = max([len(l) for l in dataset])
max_len = (max_len//args.compress_fac+1)*max_len//args.compress_fac //2
Lx_mx = []
data_graphs = []
Ly_n = []
dataset_cls1 = []
labels = []
for i, data in enumerate(tqdm(dataset)):
n_nodes = len(data)
#L = utils.graph_to_lap(data)
#sketch
#args.Lx = utils.graph_to_lap(g) #graph.graph_dist(args, plot=False)
args.Lx = data
args.m = len(args.Lx)
args.n = math.ceil(args.m/args.compress_fac)
loss, P, Ly = graph.graph_dist(args, plot=False)
ones = torch.ones(args.n, args.n).triu()
#pdb.set_trace()
#pdb.set_trace()
#lo_graphs.append(Ly)
if False: #True: #False:
cur_labels = node_labels[i][P.argmax(0)]
#Ly_mx.append(L[torch.triu(torch.ones(n_nodes, n_nodes), diagonal=1) > 0])
#order node labels
L_ordering = Ly.diag().argsort(descending=True)
cur_labels = cur_labels[L_ordering] ####
labels.append(cur_labels)
L = utils.canonicalize_mx(Ly)
#'''
L = L[ones > 0]
#Ly_n.append( (L**2).sum())#.sqrt())
#Ly_mx.append(L)
cur_max_len = min(max_len, len(L))
Ly_mx[i][:cur_max_len] = L[:cur_max_len]
#'''
Ly_mx = torch.zeros(n_data, max_len)
for i, d_idx in enumerate(data_idx):
Ly_mx[i][:len(data_sketch[d_idx])] = data_sketch[d_idx] #Ly_mx[:cur_max_len]
#torch.save(Ly_mx, 'enzyme_data_lap.pt')
#labels = torch.stack(labels)
#data_t = torch.stack(Ly_mx) #.t()
data_t = Ly_mx
#data_t = torch.cat((data_t, labels*.03), -1)
##Ly_n = torch.Tensor(Ly_n)
cur_ranks_ = torch.zeros(n_queries, args.k, dtype=torch.int64)
#pdb.set_trace()
for i, q_idx in enumerate(tqdm(query_idx, desc='queries')):
args.Lx = q
args.m = len(q)
args.n = math.ceil(args.m/args.compress_fac) #args.lo_dim #
loss, P, Lx = graph.graph_dist(args, plot=False)
ones = torch.ones(args.n, args.n).triu()
#q_graph = gwGraph.Graph(queries0[i])
#Lx_mx.append(args.Lx)
Lx_n = (args.Lx**2).sum() #.sqrt()
if False: #True: #False:
#pdb.set_trace()
cur_labels = q_labels[i][P.argmax(0)]
#Ly_mx.append(L[torch.triu(torch.ones(n_nodes, n_nodes), diagonal=1) > 0])
#order node labels
#pdb.set_trace()
L_ordering = Lx.diag().argsort(descending=True)
q_label = cur_labels[L_ordering] ###
Lx = utils.canonicalize_mx(Lx)[ones > 0]
cur_max_len = min(max_len, len(Lx))
Lx_ = torch.zeros(max_len)
Lx_[:cur_max_len] = Lx[:cur_max_len]
##Lx = torch.cat((Lx, q_label*.03), -1)
#pdb.set_trace()
#dist = Lx_n + Ly_n - 2*torch.mm(Lx.view(1, -1), data_t.t()).view(-1)
#pdb.set_trace()
dist = torch.abs(Lx_.view(1,-1) - data_t).sum(-1)
'''
dist = []
heat_q = netlsd.heat(Lx.numpy())
for j,d in enumerate(heat_l):
#dist.append(torch.norm(Lx-d, 1) )
dist.append(netlsd.compare(heat_q, heat_l[j]))
dist = torch.Tensor(dist)
'''
cur_ranks_[i] = torch.topk(dist, args.k, largest=False)[1] #np.argpartition(dist, args.k)[:args.k]
#cur_cls = dataset_cls[cur_ranks_[i]]
#pdb.set_trace()
if dataset_cls is not None:
pdb.set_trace()
pred = dataset_cls[cur_ranks_[:, 0].numpy()]
acc1 = np.equal(pred, tgt_cls).sum()
print('top 1 acc using just mx dist ! {}'.format(acc1/n_queries))
if True:
return acc1 #cur_ranks_
#cur_idx = classify_filter
def classify_filter(dataset, target, args, train_idx, query_idx): #(dataset, queries, args, dataset_cls=None, tgt_cls=None):#dataset_cls, target, args):
"""
Initial dataset filtering to filter out candidates for GW distance.
"""
#args.alpha = 0.8
#with open(args.graph_fname, 'rb') as f:
# graphs = pickle.read(f)
n_data = len(dataset)
n_queries = len(query_idx)
#ot_cost = np.zeros((len(queries), len(dataset)))
#gw_cost = np.zeros((len(queries), len(dataset)))
#gwdist = Fused_Gromov_Wasserstein_distance(alpha=args.alpha,features_metric='sqeuclidean')
Ly_mx = []
Lx_mx = []
data_graphs = []
Ly_n = []
ones = torch.ones(len(dataset[0]), len(dataset[0])) #args.lo_dim, args.lo_dim).triu()
for i, data_idx in enumerate(train_idx):
data = dataset[data_idx]
#n_nodes = len(data.nodes())
#L = utils.graph_to_lap(data)
#Ly_mx.append(L[torch.triu(torch.ones(n_nodes, n_nodes), diagonal=1) > 0])
L = utils.canonicalize_mx(data)
L = L[ones > 0]
Ly_n.append( (L**2).sum())#.sqrt())
Ly_mx.append(L)
#data_graphs.append(gwGraph.Graph(dataset0[i]))
data_t = torch.stack(Ly_mx) #.t()
Ly_n = torch.Tensor(Ly_n)
cur_ranks_ = torch.zeros(n_queries, args.k, dtype=torch.int64)
#pdb.set_trace()
for i, q_idx in enumerate(tqdm(query_idx, desc='queries')):
Lx = dataset[q_idx]
#Lx = utils.graph_to_lap(q)
#pdb.set_trace()
Lx = utils.canonicalize_mx(Lx)
args.Lx = Lx[ones>0]
#q_graph = gwGraph.Graph(queries0[i])
args.m = len(Lx)
Lx_mx.append(args.Lx)
Lx_n = (args.Lx**2).sum() #.sqrt()
Lx = args.Lx
#pdb.set_trace()
#use either l1 or l2 distance for retrieval.
#dist = Lx_n + Ly_n - 2*torch.mm(Lx.view(1, -1), data_t.t()).view(-1)
dist = torch.abs(Lx.view(1,-1) - data_t).sum(-1)
#dist = []
#for j,d in enumerate(Ly_mx):
# dist.append(torch.norm(Lx-d,2) )
#dist = torch.Tensor(dist)
#
cur_ranks_[i] = torch.topk(dist, args.k, largest=False)[1] #np.argpartition(dist, args.k)[:args.k]
#cur_cls = dataset_cls[cur_ranks_[i]]
train_cls = np.array([target[int(i)] for i in train_idx]) #target[train_idx]
if True: #dataset_cls is not None:
tgt_cls = np.array([target[int(i)] for i in query_idx])
pred = target[cur_ranks_[:, 0].numpy()]
acc1 = np.equal(pred, tgt_cls).sum()/n_queries
print('top 1 acc using just mx dist ! {}'.format(acc1))
# top-ten voting #
'''
dataset_cls = torch.from_numpy(dataset_cls)
ones = torch.ones(50)
pred10 = np.zeros(n_queries)
for i, q in enumerate(queries):
#cur_ranks = dataset_cls_t[ot_cost_ranks[i]]
ranked = torch.zeros(100) #n_cls*2
cur_ranks = dataset_cls[cur_ranks_[i, :30]]
ranked.scatter_add_(src=ones, index=cur_ranks, dim=-1)
#pdb.set_trace()
pred10[i] = torch.argmax(ranked).item()
acc10 = np.equal(pred, tgt_cls).sum()
print('top 10 voting acc using just mx dist ! {}'.format(acc10/n_queries))
'''
return cur_ranks_, acc1
def classify_filter_copt(dataset, queries, args, dataset_cls=None, tgt_cls=None):#dataset_cls, target, args):
"""
Initial dataset filtering to filter out candidates for GW distance.
"""
#args.alpha = 0.8
#with open(args.graph_fname, 'rb') as f:
# graphs = pickle.read(f)
n_data = len(dataset)
n_queries = len(queries)
#ot_cost = np.zeros((len(queries), len(dataset)))
gw_cost = np.zeros((len(queries), len(dataset)))
#gwdist = Fused_Gromov_Wasserstein_distance(alpha=args.alpha,features_metric='sqeuclidean')
Ly_mx = []
Lx_mx = []
data_graphs = []
Ly_n = []