-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbag_tasks.py
executable file
·1507 lines (1220 loc) · 44.2 KB
/
bag_tasks.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
"""Tasks to work with bag representation of Software Verification Graphs."""
from .bag import ProgramBags, normalize_gram, enumerateable, indexMap
from pyTasks.task import Task, Parameter
from pyTasks.task import Optional, containerHash
from pyTasks.target import CachedTarget, LocalTarget
from pyTasks.target import JsonService, FileTarget
from .kernel_function import select_full
import numpy as np
from .classification import select_classifier, rank_y
from .rank_scores import select_score
import math
import time
from sklearn.model_selection import KFold
from sklearn.grid_search import ParameterGrid
from sklearn.manifold import MDS
import matplotlib.pyplot as plt
import os
from scipy.sparse import issparse, coo_matrix
from .prepare_tasks import select_svcomp
import re
from .svcomp15 import MissingPropertyTypeException
import json
def is_correct(label):
"""Check if given label represents a correct solution."""
return label['solve'] == 1
def is_false(label):
"""Check if given label represents a incorrect solution."""
return label['solve'] == -1
def is_faster(labelA, labelB, major=False):
"""
Check which tool is faster in computation.
A tool is faster if it has a lower cputime.
However, we don't know the ground if the runtime is above 900s.
In the case we haven't time information (both runtimes are above 900s),
major gives a general tendency.
"""
if labelB['time'] >= 900:
return labelA['time'] < 900 or major
return labelA['time'] < labelB['time']
def index(x, y, n):
"""
Return a single index for given coordinates.
Map given coordinates to an index in a linear memoryself.
It is important that (x, y) and (y, x) share the same index.
The output ranges between 0 and n(n+1)/2.
"""
if x >= n:
raise ValueError('x: %d is out of range 0 to %d' % (x, n))
if y >= n:
raise ValueError('y: %d is out of range 0 to %d' % (y, n))
if y == x:
return x
if x > y:
tmp = y
y = x
x = tmp
return int(x * (n - 0.5*(x+1))
+ (y - (x+1))
+ n)
def reverse_index(i, n):
"""Inverse operation to index."""
if i < n:
return i, i
i = i - n + 1
x = 0
while int(x * (n - 0.5*(x+1))) < i:
x += 1
x -= 1
y = i - int(x * (n - 0.5*(x+1))) + x
return x, y
def is_dict(D):
"""Check if the given object is a dictionary."""
try:
D.items()
return True
except AttributeError:
return False
def mean_std(L):
"""Calculate mean of dictionary lists."""
O = {}
for k in L[0]:
if 'raw' in k:
continue
coll = [l[k] for l in L]
if is_dict(coll[0]):
coll = mean_std(coll)
else:
coll = {
'mean': np.mean(coll),
'median': np.median(coll),
'std': np.std(coll)
}
O[k] = coll
return O
def dominates(A, B):
"""
Test if A dominates B.
A vector A dominates a vector B if every entry of A is smaller than the
matching entry of B.
"""
for i, a in enumerate(A):
if a < B[i]:
return False
return True
def pareto_front(knownSet, entity, key):
"""Search for Pareto front in a given set."""
front = []
entity_add = True
entity_k = key(entity)
for knownEntity in knownSet:
k = key(knownEntity)
if dominates(k, entity_k):
return knownSet.copy()
elif not dominates(entity_k, k):
front.append(knownEntity)
if entity_add:
front.append(entity)
return front
def is_better(ci, cj, fij):
"""
Decide which tool is better.
ci: 1 if tool_i can solve the problem
cj: 1 if tool_j can solve the problem
fij: 1 if tool_i is faster than tool_j
"""
return ci > cj or (ci == cj and fij == 1)
def borda_major(bag):
"""
Generate a majority ranking for a set of bags.
The majority ranking is decided by Borda' method.
"""
votes = {}
for k, B in bag.items():
for tool_x, label_x in B['label'].items():
for tool_y, label_y in B['label'].items():
if tool_x < tool_y:
if tool_x not in votes:
votes[tool_x] = 0
if tool_y not in votes:
votes[tool_y] = 0
ci =\
1 if is_correct(label_x) else \
(-1 if is_false(label_x) else 0)
cj =\
1 if is_correct(label_y) else \
(-1 if is_false(label_y) else 0)
fij = 1 if is_faster(label_x, label_y) else 0
fij = -1 if fij == 0 and is_faster(label_x, label_y) else fij
if max([ci, cj, fij]) == min([ci, cj, fij]) and fij == 0:
continue
votes[tool_x if is_better(ci, cj, fij) else tool_y] += 1
votes = [t[0] for t in sorted(list(votes.items()), key=lambda X: X[1], reverse=True)]
return {k: i for i, k in enumerate(votes)}
def ranking(row, n):
"""Decode a ranking from a label matrix."""
N = np.zeros(n)
for i in range(n):
correct_i = row[index(i, i, n)]
for j in range(n):
if i < j:
correct_j = row[index(j, j, n)]
faster_i = row[index(i, j, n)]
N[i if is_better(correct_i, correct_j, faster_i) else j] += 1
return N.argsort()[::-1]
class FeatureJsonService:
"""A service to decode and encode sparse matrix representation."""
def __init__(self, s):
"""
Init service.
Parameter s is a service endpoint.
"""
self.__src = s
def emit(self, obj):
"""Emit a sparse matrix to a service endpoint."""
for k, V in obj.items():
if issparse(V):
NZ = V.nonzero()
data = V[NZ].A
shape = V.get_shape()
obj[k] = {
'sparse': True,
'rows': NZ[0].tolist(),
'columns': NZ[1].tolist(),
'data': data.tolist()[0],
'row_shape': shape[0],
'column_shape': shape[1]
}
json.dump(obj, self.__src, indent=4)
def query(self):
"""Load a sparse matrix from a service endpoint."""
obj = json.load(self.__src)
for k, V in obj.items():
if 'sparse' in V:
obj[k] = coo_matrix((V['data'], (V['rows'], V['columns'])),
shape=(V['row_shape'],
V['column_shape'])).tocsr()
return obj
def isByte(self):
"""Check if we use a binary representation."""
return False
class BagLoadingTask(Task):
"""Load a bag representation from memory."""
pattern = Parameter('./task_%d_%d.json')
def __init__(self, h, D):
"""
Init tasks with loading parameter.
h: The iteration depth.
D: The AST depth.
"""
self.h = h
self.D = D
def require(self):
"""Requirements."""
return None
def __taskid__(self):
"""Task id for the loading task."""
return 'BagLoadingTask_%d_%d' % (self.h, self.D)
def output(self):
"""Output for the task."""
try:
src_path = self.pattern.value % (self.h, self.D)
except TypeError:
print('Source is not formattable: %s. Continue without parameter.'
% self.pattern.value)
src_path = self.pattern.value
return CachedTarget(
LocalTarget(src_path, service=JsonService)
)
def run(self):
"""Nothing to do here."""
pass
class BagFilterTask(Task):
"""Filter bag repres for given category and task_type."""
out_dir = Parameter('./gram/')
svcomp = Parameter('svcomp18')
def __init__(self, h, D, category=None, task_type=None, by_id=False):
"""
Init Task.
h: iteration depth for loading task
D: AST depth for loading task
category: Task category (e.g. array-examples)
task_type: type of task (e.g. reach for reachability problems)
by_id: Apply filter on task id instead of file name.
"""
self.h = h
self.D = D
self.category = category
self.task_type = task_type
self.by_id = by_id
def _init_filter(self):
categories = set(enumerateable(self.category))
self._svcomp = select_svcomp(self.svcomp.value)
prop = self._svcomp.select_propety(self.task_type)
def filter(category, property):
print(property)
if prop is not None and prop not in property:
return False
if self.category is None:
return True
return category in categories
self._filter = filter
def _detect_property(self, path):
try:
return self._svcomp.set_of_properties(path)
except MissingPropertyTypeException:
print('Problem with property. Ignore')
return None
def _detect_category(self, path):
reg = re.compile('sv-benchmarks\/c\/[^\/]+\/')
o = reg.search(path)
if o is None:
return 'unknown'
return o.group()[16:-1]
def require(self):
"""Require to load the bag first."""
return BagLoadingTask(self.h, self.D)
def __taskid__(self):
"""Task id."""
s = 'BagFilterTask_%d_%d' % (self.h, self.D)
if self.category is not None:
s += '_'+str(containerHash(self.category))
if self.task_type is not None:
s += '_'+str(self.task_type)
return s
def output(self):
"""Define a json output."""
path = self.out_dir.value + self.__taskid__() + '.json'
return CachedTarget(
LocalTarget(path, service=JsonService)
)
def run(self):
"""Filter loaded bag and emit."""
self._init_filter()
with self.input()[0] as i:
B = i.query()
D = set([])
for name, V in B.items():
if self.by_id:
f = name
else:
f = V['file']
if not self._filter(
self._detect_category(f),
self._detect_property(f)
):
D.add(name)
B = {b: V for b, V in B.items() if b not in D}
with self.output() as o:
o.emit(B)
class BagGraphIndexTask(Task):
"""Generate a index for graph id."""
out_dir = Parameter('./gram/')
def __init__(self, h, D, category=None, task_type=None):
"""
Init Task.
h: iteration depth for loading task
D: AST depth for loading task
category: Task category (e.g. array-examples)
task_type: type of task (e.g. reach for reachability problems)
Caution: Ids between iterations should be the same. They can change
between AST depths. Standard usage: Generate graph index only for
one iteration depth (e.g. h=0) and use the index for all
remaining cases.
"""
self.h = h
self.D = D
self.category = category
self.task_type = task_type
def require(self):
"""Load a filter task."""
return BagFilterTask(self.h, self.D,
self.category, self.task_type)
def __taskid__(self):
"""Task id."""
s = 'BagGraphIndexTask_%d' % (self.D)
if self.category is not None:
s += '_'+str(containerHash(self.category))
if self.task_type is not None:
s += '_'+str(self.task_type)
return s
def output(self):
"""Output as Json."""
path = self.out_dir.value + self.__taskid__() + '.json'
return CachedTarget(
LocalTarget(path, service=JsonService)
)
def run(self):
"""Index the ids of the given bag."""
with self.input()[0] as i:
D = i.query()
out = {}
for k in D:
indexMap(k, out)
with self.output() as o:
o.emit(out)
class BagLabelMatrixTask(Task):
"""
Generate a matrix for the given label set.
Layout is depended on the number of tools N.
A entry (r, c) is 1 if r < N and tool_r can solve task_c.
A entry (r, c) is 1 if
+ r >= N
+ x, y = reverse_index(r, N)
+ tool_x is faster than tool_y on task_c
A entry (r, c) is -1 if
+ r >= N
+ x, y = reverse_index(r, N)
+ tool_x is slower than tool_y on task_c
Otherwise, the entry is 0.
"""
out_dir = Parameter('./gram/')
allowed = Parameter(None)
def __init__(self, h, D, category=None, task_type=None):
"""Init Task."""
self.h = h
self.D = D
self.category = category
self.task_type = task_type
def require(self):
"""Requirement (Graph index and filtered input)."""
return [BagGraphIndexTask(self.h,
self.D,
self.category, self.task_type),
BagFilterTask(self.h, self.D,
self.category, self.task_type)]
def __taskid__(self):
"""Task id."""
s = 'BagLabelMatrixTask_%d_%d' % (self.h, self.D)
if self.category is not None:
s += '_'+str(containerHash(self.category))
if self.task_type is not None:
s += '_'+str(self.task_type)
return s
def output(self):
"""Output as Json"""
path = self.out_dir.value + self.__taskid__() + '.json'
return CachedTarget(
LocalTarget(path, service=JsonService)
)
@staticmethod
def common_tools(bag):
"""Retrieve all tools that are common to all tasks."""
F = len(bag)
C = {}
for B in bag.values():
for tool in B['label'].keys():
if tool not in C:
C[tool] = 0
C[tool] += 1
tools = [k for k, v in C.items() if v == F]
for B in bag.values():
for d in [d for d in B['label'].keys() if d not in tools]:
del B['label'][d]
return tools
def run(self):
"""Generate label matrix."""
with self.input()[0] as i:
graphIndex = i.query()
with self.input()[1] as i:
bag = i.query()
self.tools = BagLabelMatrixTask.common_tools(bag)
self.major = borda_major(bag)
if self.allowed.value is not None:
self.tools = [t for t in self.tools if t in self.allowed.values]
n = len(self.tools)
label_matrix = np.zeros((graphIndex['counter'], int(0.5*n*(n+1))))
rankings = np.array([None]*graphIndex['counter'])
tool_index = {t: i for i, t in enumerate(self.tools)}
for k, B in bag.items():
if k not in graphIndex:
continue
index_g = graphIndex[k]
for tool_x, label_x in B['label'].items():
index_x = tool_index[tool_x]
label_matrix[index_g, index(index_x, index_x, n)] =\
1 if is_correct(label_x) else \
(-1 if is_false(label_x) else 0)
for tool_y, label_y in B['label'].items():
index_y = tool_index[tool_y]
if index_y > index_x:
major = self.major[tool_x] < self.major[tool_y]
v = 1 if is_faster(label_x, label_y, major) else 0
v = -1 if v == 0 and is_faster(label_x, label_y, major) else v
label_matrix[index_g, index(index_x, index_y, n)] =\
v
rank = ranking(label_matrix[index_g, :], n)
rankings[index_g] = [self.tools[i] for i in rank]
with self.output() as o:
o.emit(
{
'tools': self.tools,
'label_matrix': label_matrix.tolist(),
'rankings': rankings.tolist()
}
)
class BagFeatureTask(Task):
"""DEPRECATED."""
out_dir = Parameter('./gram/')
svcomp = Parameter('svcomp15')
def __init__(self, h, D, category=None, task_type=None):
self.h = h
self.D = D
self.category = category
self.task_type = task_type
def require(self):
return [BagGraphIndexTask(self.h,
self.D,
self.category, self.task_type),
BagFilterTask(self.h, self.D,
self.category, self.task_type)]
def __taskid__(self):
cat = 'all'
if self.category is not None:
cat = str(containerHash(self.category))
tt = ''
if self.task_type is not None:
tt = '_'+str(self.task_type)
return 'BagFeatureTask_%d_%d_%s' % (self.h, self.D, cat)\
+ tt
def output(self):
path = self.out_dir.value + self.__taskid__() + '.json'
return CachedTarget(
LocalTarget(path, service=FeatureJsonService)
)
def run(self):
with self.input()[0] as i:
graphIndex = i.query()
with self.input()[1] as i:
bag = ProgramBags(content=i.query(), svcomp=self.svcomp.value)
bag.graphIndex = graphIndex
features = bag.features()
out = {
'graphIndex': bag.graphIndex,
'nodeIndex': bag.nodeIndex,
'features': features
}
with self.output() as o:
o.emit(out)
class BagGramTask(Task):
"""Generate the gram matrix for a given bags."""
out_dir = Parameter('./gram/')
svcomp = Parameter('svcomp18')
def __init__(self, h, D, category=None, task_type=None, kernel='linear'):
"""
Init task.
h: iteration depth for loading task
D: AST depth for loading task
category: Task category (e.g. array-examples)
task_type: type of task (e.g. reach for reachability problems)
kernel: The kernel function to apply (see kernel_function.py)
"""
self.h = h
self.D = D
self.category = category
self.task_type = task_type
self.kernel = kernel
def require(self):
"""Requirement."""
return [BagGraphIndexTask(self.h,
self.D,
self.category, self.task_type),
BagFilterTask(self.h, self.D,
self.category, self.task_type)]
def __taskid__(self):
"""Task id."""
cat = 'all'
if self.category is not None:
cat = str(containerHash(self.category))
tt = ''
if self.task_type is not None:
tt = '_'+str(self.task_type)
return 'BagGramTask_%d_%d_%s_%s' % (self.h, self.D, self.kernel, cat)\
+ tt
def output(self):
"""Output as Json."""
path = self.out_dir.value + self.__taskid__() + '.json'
return CachedTarget(
LocalTarget(path, service=JsonService)
)
def run(self):
"""
Generate kernel from input bags.
Bags are firstly represented as a vector (indexing labels in bag).
Then the kernel function will be applied.
"""
with self.input()[0] as i:
graphIndex = i.query()
with self.input()[1] as i:
bag = ProgramBags(content=i.query(), svcomp=self.svcomp.value)
bag.graphIndex = graphIndex
print(bag.graphIndex['counter'])
if self.kernel == 'linear':
gram = bag.gram().toarray()
else:
kernel = select_full(self.kernel)
if kernel is None:
raise ValueError('Unknown kernel %s' % self.kernel)
gram = bag.gram(kernel=kernel)
if issparse(gram):
gram = gram.toarray()
print(gram.shape)
data = gram.tolist()
out = {
'graphIndex': bag.graphIndex,
'data': data
}
with self.output() as o:
o.emit(out)
class BagSumGramTask(Task):
"""A task to sum individual grams into one gram."""
out_dir = Parameter('./gram/')
def __init__(self, hSet, D, category=None,
task_type=None, kernel='linear'):
"""
Init task.
hSet: a set of iteration bounds to sum.
D: AST depth bound
category: Task category (e.g. array-examples)
task_type: type of task (e.g. reach for reachability problems)
kernel: The kernel function to apply (see kernel_function.py)
"""
self.hSet = hSet
self.D = D
self.category = category
self.task_type = task_type
self.kernel = kernel
def require(self):
"""Requirement."""
return [
BagGramTask(h, self.D, self.category, self.task_type, self.kernel)
for h in self.hSet
]
def __taskid__(self):
"""Task id."""
cat = 'all'
if self.category is not None:
cat = str(containerHash(self.category))
tt = ''
if self.task_type is not None:
tt = '_'+str(self.task_type)
return 'BagSumGramTask_%s_%d_%s_%s' % (str(
containerHash(self.hSet)
),
self.D, self.kernel, cat
)\
+ tt
def output(self):
"""Output as Json."""
path = self.out_dir.value + self.__taskid__() + '.json'
return CachedTarget(
LocalTarget(path, service=JsonService)
)
def run(self):
"""Calculate sum."""
GR = None
for inp in self.input():
with inp as i:
D = i.query()
gI = D['graphIndex']
gram = np.array(D['data'])
del D
if GR is None:
GR = gram
else:
GR += gram
del gram
data = GR.tolist()
out = {
'graphIndex': gI,
'data': data
}
with self.output() as o:
o.emit(out)
class BagNormalizeGramTask(Task):
"""Kernel normalization task."""
out_dir = Parameter('./gram/')
def __init__(self, h, D, category=None, task_type=None, kernel='linear'):
"""
Init task.
h: a set of iteration bounds for normalization (h=2 <==> h={2})
D: AST depth bound
category: Task category (e.g. array-examples)
task_type: type of task (e.g. reach for reachability problems)
kernel: The kernel function to apply (see kernel_function.py)
"""
self.h = h
self.D = D
self.category = category
self.task_type = task_type
self.kernel = kernel
def require(self):
"""Requirement."""
hSet = [h for h in enumerateable(self.h)]
if len(hSet) == 1:
return BagGramTask(hSet[0], self.D,
self.category, self.task_type, self.kernel)
else:
return BagSumGramTask(hSet, self.D,
self.category, self.task_type, self.kernel)
def __taskid__(self):
"""Task id."""
cat = 'all'
if self.category is not None:
cat = str(containerHash(self.category))
tt = ''
if self.task_type is not None:
tt = '_'+str(self.task_type)
return 'BagNormGramTask_%s_%d_%s_%s' % (str(
containerHash(self.h)
),
self.D, self.kernel, cat
)\
+ tt
def output(self):
"""Output as Json."""
path = self.out_dir.value + self.__taskid__() + '.json'
return CachedTarget(
LocalTarget(path, service=JsonService)
)
def run(self):
"""Normalize input gram matrix."""
with self.input()[0] as i:
D = i.query()
graphIndex = D['graphIndex']
gram = np.array(D['data'])
del D
data = normalize_gram(gram).tolist()
out = {
'graphIndex': graphIndex,
'data': data
}
with self.output() as o:
o.emit(out)
class BagClassifierEvalutionTask(Task):
"""DEPRECATED."""
out_dir = Parameter('./eval/')
def __init__(self, clf_type, clf_params,
h, D, scores,
train_index, test_index,
category=None,
task_type=None,
kernel='linear'):
self.clf_type = clf_type
self.clf_params = clf_params
self.kernel = kernel
self.h = h
self.D = D
self.scores = scores
self.train_index = train_index
self.test_index = test_index
self.category = category
self.task_type = task_type
def require(self):
h = [h for h in range(self.h+1)]
return [BagFilterTask(self.h, self.D,
self.category, self.task_type),
BagNormalizeGramTask(h, self.D, self.category, self.task_type,
self.kernel)]
def __taskid__(self):
return 'BagClassifierEvalutionTask_%s' % (str(
containerHash(
list(
self.get_params().items()
)
)
)
)
def output(self):
path = self.out_dir.value + self.__taskid__() + '.json'
return CachedTarget(
LocalTarget(path, service=JsonService)
)
def _build_classifier(self):
clf = select_classifier(self.clf_type)
return clf(**self.clf_params)
def _build_maps(self):
with self.input()[0] as i:
D = i.query()
map_to_labels = {k: v['label'] for k, v in D.items()}
map_to_times = {k: v['time'] if 'time' in v else math.inf for k, v in D.items()}
del D
return map_to_labels, map_to_times
def _build_score(self, labels, times):
scores = {}
for k in self.scores:
scores[k] = select_score(k, labels, times)
return scores
@staticmethod
def _index_map(index, mapping):
mapping = {k: v for k, v in mapping.items() if k in index}
V = [
m for m in sorted(list(mapping.items()), key=lambda x: index[x[0]])
]
graphs = [m[0] for m in V]
return graphs, np.array([m[1] for m in V])
def run(self):
with self.input()[1] as i:
D = i.query()
graphIndex = D['graphIndex']
X = np.array(D['data'])
del D
y, times = self._build_maps()
scores = self._build_score(y, times)
graphs, y = BagClassifierEvalutionTask._index_map(graphIndex, y)
train_index = self.train_index
test_index = self.test_index
X_train, X_test = X[train_index][:, train_index], X[test_index][:, train_index]
y_train, y_test = y[train_index], y[test_index]
y_test = rank_y(y_test)
clf = self._build_classifier()
start_time = time.time()
clf.fit(X_train, y_train)
train_time = time.time() - start_time
times['train'] = train_time
start_time = time.time()
prediction = clf.predict_rank(X_test)
test_time = (time.time() - start_time) / len(y_test)
times['prediction'] = test_time
empirical = {}
raw_empircal = {}
for i, pred in enumerate(prediction):
expected = y_test[i]
g = graphs[test_index[i]]
for k, score in scores.items():
if k not in empirical:
empirical[k] = 0.0
raw_empircal[k] = []
s = score(pred, expected, g)
empirical[k] += s / len(y_test)
raw_empircal[k].append(s)
with self.output() as emitter:
emitter.emit(
{
'parameter': self.get_params(),
'train_time': train_time,
'test_time': test_time,
'result': empirical,
'raw_results': raw_empircal
}
)
class BagKFoldTask(Task):
"""DEPRECATED."""
k = Parameter(10)
out_dir = Parameter('./eval/')