-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.py
executable file
·1424 lines (1069 loc) · 83 KB
/
main.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
import os,sys,shutil,argparse,random,numpy,math
from numpy import array
from functools import partial
from tensorflow.contrib import rnn
from datasetGenerators import *
import tensorflow as tf
tf.logging.set_verbosity(tf.logging.ERROR)
def makeRandomPredCompletions(shape,conceptSpace,roleSpace,syn):
rando = []
for i in range(shape[0]):
kb = []
for j in range(shape[1]):
step = []
inner = int(shape[2]/4)
split = random.randint(0,inner)
gen = GenERator(numCType1=split,numCType2=0,numCType3=(inner - split),numCType4=0,numRoleSub=0,numRoleChains=0,conceptNamespace=conceptSpace,roleNamespace=roleSpace,CTypeNull=[],CType1=[],CType2=[],CType3=[],CType4=[],roleSubs=[],roleChains=[])
gen.genERate()
for k in range(0,len(gen.CType1)):
step.append([gen.CType1[k].antecedent.toString(),gen.CType1[k].consequent.toString()])
for k in range(0,len(gen.CType3)):
step.append([gen.CType3[k].antecedent.toString(),gen.CType3[k].consequent.role.toString(),gen.CType3[k].consequent.concept.toString()])
kb.append(step)
rando.append(kb)
numpy.savez("saves/randoPred" if syn else "ssaves/randoPred",rando)
return rando
def makeRandomStrCompletions(shape,conceptSpace,roleSpace,syn):
rando = []
for i in range(shape[0]):
kb = []
for j in range(shape[1]):
step = []
inner = int(shape[2]/4)
split = random.randint(0,inner)
gen = GenERator(numCType1=split,numCType2=0,numCType3=(inner - split),numCType4=0,numRoleSub=0,numRoleChains=0,conceptNamespace=conceptSpace+1,roleNamespace=roleSpace+1,CTypeNull=[],CType1=[],CType2=[],CType3=[],CType4=[],roleSubs=[],roleChains=[])
gen.genERate()
for k in range(0,len(gen.CType1)):
#print(gen.CType1[k].toString())
if gen.CType1[k].antecedent.name == 0:
gen.CType1[k].antecedent.name = conceptSpace
if gen.CType1[k].consequent.name == 0:
gen.CType1[k].consequent.name = conceptSpace
step.append(gen.CType1[k].toString())
for k in range(0,len(gen.CType3)):
#print(gen.CType3[k].toString())
if gen.CType3[k].antecedent.name == 0:
gen.CType3[k].antecedent.name = conceptSpace
if gen.CType3[k].consequent.concept.name == 0:
gen.CType3[k].consequent.concept.name = conceptSpace
if gen.CType3[k].consequent.role.name == 0:
gen.CType3[k].consequent.role.name = roleSpace
step.append(gen.CType3[k].toString())
kb.append(step)
rando.append(kb)
numpy.savez("saves/randoStr" if syn else "ssaves/randoStr",rando)
return rando
def collapseLabelMap(localMap,classes,roles,labels):
for mapping in localMap:
for entry in mapping:
mapping[entry] = labels[classes[mapping[entry]]] if mapping[entry] > 0 else labels[roles[mapping[entry]]]
return localMap
def getSynDataFromFile(filename):
print("Loading data from "+filename)
data = numpy.load(filename,allow_pickle=True)
return data['arr_0'],data['arr_1'],data['arr_2']
def getSnoDataFromFile(filename):
print("Loading data from "+filename)
data = numpy.load(filename,allow_pickle=True)
return data['arr_0'],data['arr_1'],data['arr_2'],data['arr_3'],data['arr_4']
def writeVectorFileWithMap(filename,vector,mapping):
file = open(filename,"w")
for i in range(len(vector)):
print(mapping[i])
file.write("Trial: {}\n".format(i))
for j in range(len(vector[i])):
file.write("\tStep: {}\n".format(j))
for k in range(len(vector[i][j])):
file.write("\t\t{}\n".format(vector[i][j][k]))
file.write("\n")
file.close()
def writeVectorFile(filename,vector):
file = open(filename,"w")
for i in range(len(vector)):
file.write("Trial: {}\n".format(i))
for j in range(len(vector[i])):
file.write("\tStep: {}\n".format(j))
for k in range(len(vector[i][j])):
file.write("\t\t{}\n".format(vector[i][j][k]))
file.write("\n")
file.close()
def pad(arr,maxlen1=0,maxlen2=0):
for i in range(0,len(arr)):
if len(arr[i]) > maxlen1: maxlen1 = len(arr[i])
for j in range(0,len(arr[i])):
if len(arr[i][j]) > maxlen2: maxlen2 = len(arr[i][j])
newarr = numpy.zeros(shape=(len(arr),maxlen1,maxlen2),dtype=float)
for i in range(0,len(arr)):
for j in range(0,len(arr[i])):
for k in range(0,len(arr[i][j])):
newarr[i][j][k] = arr[i][j][k]
return newarr
def vecToStatement(vec,conceptSpace,roleSpace):
four = []
statementStr = []
statementPred = []
for j in range(len(vec)):
stepStr = []
stepPred = []
for k in range(len(vec[j])):
if len(four) == 3:
four.append(vec[j][k])
pred,stri = convertToStatement(four,conceptSpace,roleSpace)
if stri != None: stepStr.append(stri)
if pred != None: stepPred.append(pred)
four = []
else:
four.append(vec[j][k])
if len(stepStr) > 0:
statementStr.append(stepStr)
if len(stepPred) > 0:
statementPred.append(stepPred)
return statementPred,statementStr
def vecToStatements(vec,conceptSpace,roleSpace):
four = []
statementStr = []
statementPred = []
for i in range(len(vec)):
trialStr = []
trialPred = []
for j in range(len(vec[i])):
stepStr = []
stepPred = []
for k in range(len(vec[i][j])):
if len(four) == 3:
four.append(vec[i][j][k])
pred,stri = convertToStatement(four,conceptSpace,roleSpace)
if stri != None: stepStr.append(stri)
if pred != None: stepPred.append(pred)
four = []
else:
four.append(vec[i][j][k])
if len(stepStr) > 0:
trialStr.append(stepStr)
if len(stepPred) > 0:
trialPred.append(stepPred)
statementStr.append(trialStr)
statementPred.append(trialPred)
return statementPred,statementStr
def vecToStatementsWithLabels(vec,conceptSpace,roleSpace,labels):
four = []
statementStr = []
statementPred = []
for i in range(len(vec)):
trialStr = []
trialPred = []
for j in range(len(vec[i])):
stepStr = []
stepPred = []
for k in range(len(vec[i][j])):
if len(four) == 3:
four.append(vec[i][j][k])
pred,stri = convertToStatementWithLabels(four,conceptSpace,roleSpace,labels[i])
if stri != None: stepStr.append(stri)
if pred != None: stepPred.append(pred)
four = []
else:
four.append(vec[i][j][k])
if len(stepStr) > 0:
trialStr.append(stepStr)
if len(stepPred) > 0:
trialPred.append(stepPred)
statementStr.append(trialStr)
statementPred.append(trialPred)
return statementPred,statementStr
def convertToStatementWithLabels(four,conceptSpace,roleSpace,labels):
new = []
text = []
for number in four:
if isinstance(number,numpy.float32):
number = number.item()
if number < 0 and number >= -1:
if int(number * roleSpace * -1) == 0: pass
else:
number = int(number * roleSpace * -1)
text.append(labels[-number]) if (-number) in labels.keys() else text.append("undefinedRelationTo{}".format(number))
new.append("R{}".format(number))
elif number > 0 and number <= 1:
if int(number * conceptSpace) == 0: pass
else:
number = int(number * conceptSpace)
text.append(labels[number]) if number in labels.keys() else text.append("UndefinedConcept{}".format(number))
new.append("C{}".format(number))
if len(new) == 0:
return None,None
elif len(new) == 1:
return None,None#new,new[0]
elif len(new) == 2:# and ((four[1] > 0 and four[2] > 0) or (four[1] < 0 and four[2] < 0)):
return new,"{}\n\t\t\ta {}".format(" ⊑ ".join(new)," is a ".join(text))
#elif len(new) == 2:
#return new,None
elif len(new) == 3:
if four[1] > 0 and four[2] < 0 and four[3] > 0:
return new,"{} ⊑ ∃{}.{}\n\t\t\tif something is a {} then there is a {} that it is {}".format(new[0],new[1],new[2],text[0],text[2],text[1])
elif four[1] > 0 and four[0] < 0 and four[2] > 0:
return new,"∃{}.{} ⊑ {}\n\t\t\tif there is a {} that is {} another thing then the other thing is a {}".format(new[0],new[1],new[2],text[1],text[0],text[2])
elif four[1] > 0 and four[0] > 0 and four[2] > 0:
return new,"{} ⊓ {} ⊑ {}\n\t\t\tif something is both a {} and a {}, then it is also a {}".format(new[0],new[1],new[2],text[0],text[1],text[2])
elif four[1] < 0 and four[0] < 0 and four[2] < 0:
return new,"{} ∘ {} ⊑ {}\n\t\t\tif a first thing is {} anything that is {} a third thing, then the first is {} the third".format(new[0],new[1],new[2],text[0],text[1],text[2])
return None,None
def convertToStatement(four,conceptSpace,roleSpace):
new = []
for number in four:
if isinstance(number,numpy.float32):
number = number.item()
#if number < 0: pass
if number < 0 and number >= -1:
if int(number * roleSpace * -1) == 0: pass
else: new.append("R{}".format(int(number * roleSpace * -1)))
elif number > 0 and number <= 1:
if int(number * conceptSpace) == 0: pass
else: new.append("C{}".format(int(number * conceptSpace)))
if len(new) == 0:
return None,None
elif len(new) == 1:
return None,None# new,new[0]
elif len(new) == 2:# and ((four[1] > 0 and four[2] > 0) or (four[1] < 0 and four[2] < 0)):
return new," ⊑ ".join(new)
#elif len(new) == 2:
#return new,None
elif len(new) == 3:
if four[1] > 0 and four[2] < 0 and four[3] > 0:
return new,"{} ⊑ ∃{}.{}".format(new[0],new[1],new[2])
elif four[1] > 0 and four[0] < 0 and four[2] > 0:
return new,"∃{}.{} ⊑ {}".format(new[0],new[1],new[2])
elif four[1] > 0 and four[0] > 0 and four[2] > 0:
return new,"{} ⊓ {} ⊑ {}".format(new[0],new[1],new[2])
elif four[1] < 0 and four[0] < 0 and four[2] < 0:
return new,"{} ∘ {} ⊑ {}".format(new[0],new[1],new[2])
return None,None#" ".join(new)
def splitTensors(inputs,outputs, size):
inTest, inTrain = numpy.split(inputs,[int(len(inputs)*size)])
outTest, outTrain = numpy.split(outputs,[int(len(outputs)*size)])
return inTrain, inTest, outTrain, outTest
#https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#Python
def levenshtein(s1, s2):
if len(s1) < len(s2):
return levenshtein(s2, s1)
# len(s1) >= len(s2)
if len(s2) == 0:
return len(s1)
previous_row = range(len(s2) + 1)
for i, c1 in enumerate(s1):
current_row = [i + 1]
for j, c2 in enumerate(s2):
insertions = previous_row[j + 1] + 1 # j+1 instead of j since previous_row and current_row are one character longer
deletions = current_row[j] + 1 # than s2
substitutions = previous_row[j] + (c1 != c2)
current_row.append(min(insertions, deletions, substitutions))
previous_row = current_row
return previous_row[-1]
def levenshteinIgnoreNum(s1, s2):
if len(s1) < len(s2):
return levenshteinIgnoreNum(s2, s1)
s1,s2 = convertAllNumsToAtoms(s1,s2)
if len(s1) < len(s2):
return levenshteinIgnoreNum(s2, s1)
# len(s1) >= len(s2)
if len(s2) == 0:
return len(s1)
previous_row = range(len(s2) + 1)
for i, c1 in enumerate(s1):
current_row = [i + 1]
for j, c2 in enumerate(s2):
insertions = previous_row[j + 1] + 1 # j+1 instead of j since previous_row and current_row are one character longer
deletions = current_row[j] + 1 # than s2
substitutions = previous_row[j] + (c1 != c2)
current_row.append(min(insertions, deletions, substitutions))
previous_row = current_row
return previous_row[-1]
def convertAllNumsToAtoms(s1,s2):
dic = {}
a = 'a'
st = ""
longer = False
for i in range(len(s1)):
if s1[i].isdigit() and not longer:
st = s1[i]
for j in range(i+1,len(s1)):
if s1[j].isdigit():
longer = True
st = st + s1[j]
else: break
if not int(st) in dic.keys():
dic[int(st)] = a
a = chr(ord(a) + 1)
elif not s1[i].isdigit(): longer = False
longer = False
for i in range(len(s2)):
if s2[i].isdigit() and not longer:
st = s2[i]
for j in range(i+1,len(s2)):
if s2[j].isdigit():
longer = True
st = st + s2[j]
else: break
if not int(st) in dic.keys():
dic[int(st)] = a
a = chr(ord(a) + 1)
elif not s1[i].isdigit(): longer = False
for key in sorted(dic, reverse=True):
s1 = s1.replace(str(key),dic[key])
s2 = s2.replace(str(key),dic[key])
s1 = s1.replace(" ","")
s2 = s2.replace(" ","")
return s1,s2
def findBestMatchNoNums(statement,reasonerSteps):
return min(map(partial(levenshteinIgnoreNum,statement),reasonerSteps))
def levDistanceNoNums(shape,newStatements,trueStatements,conceptSpace,roleSpace,syn,mix):
if (syn and os.path.isfile("saves/randoStr.npz")) or os.path.isfile("ssaves/randoStr.npz"):
rando = numpy.load(("saves/randoStr.npz" if syn else "ssaves/randoStr.npz"),allow_pickle=True)
rando = rando['arr_0'].tolist()
else:
rando = makeRandomStrCompletions(shape,conceptSpace,roleSpace,syn)
flatTrue = [[item for sublist in x for item in sublist] for x in trueStatements]
flatRand = [[item for sublist in x for item in sublist] for x in rando]
flatNew = [[item for sublist in x for item in sublist] for x in newStatements]
F1s = array([0,sum([len(x) for x in flatNew]),sum([len(x) for x in flatTrue])])
rF1s = array([0,0,0])
levTR = 0
levRT = 0
levTN = 0
levNT = 0
sizeRan = 0
sizeTrue = 0
sizeNew = 0
for i in range(len(rando)):
for j in range(len(rando[i])):
for k in range(len(rando[i][j])):
sizeRan = sizeRan + 1
if len(trueStatements) > i and len(trueStatements[i]) > j and len(trueStatements[i][j]) > k: #FOR VERY TRUE STATEMENT
sizeTrue = sizeTrue + 1 #if there is a true KB corresponding to this random data, compare the random statement to its best match in the true statements
levRT = levRT + findBestMatchNoNums(rando[i][j][k],flatTrue[i])
best = findBestMatchNoNums(trueStatements[i][j][k],flatRand[i]) #compare to best match in random
if best == 0: rF1s[0] = rF1s[0] + 1
levTR = levTR + best
if (len(newStatements) > i and len(newStatements[i]) > 0):
levTN = levTN + findBestMatchNoNums(trueStatements[i][j][k],flatNew[i]) #if there are predictions for this KB, compare to best match in there
elif not mix: levTN = levTN + levenshteinIgnoreNum(trueStatements[i][j][k],'') #otherwise compare with no prediction
if len(newStatements) > i and len(newStatements[i]) > j and len(newStatements[i][j]) > k: #FOR EVERY PREDICTION
sizeNew = sizeNew + 1
if (len(trueStatements) > i and len(trueStatements[i]) > 0):
best = findBestMatchNoNums(newStatements[i][j][k],flatTrue[i])
if best == 0: F1s[0] = F1s[0] + 1
levNT = levNT + best #if there are true values for this KB, compare to best match in there
elif not mix: levNT = levNT + levenshteinIgnoreNum(newStatements[i][j][k],'') #otherwise compare with no true value
F1s[1] = sizeNew - F1s[0]
F1s[2] = sizeTrue - F1s[0]
rF1s[1] = sizeRan - rF1s[0]
rF1s[2] = sizeTrue - rF1s[0]
return levTR,levRT,levTN,levNT,sizeTrue,sizeNew,sizeRan,F1s,rF1s
def levDistance(shape,newStatements,trueStatements,conceptSpace,roleSpace,syn,mix):
if (syn and os.path.isfile("saves/randoStr.npz")) or os.path.isfile("ssaves/randoStr.npz"):
rando = numpy.load("saves/randoStr.npz" if syn else "ssaves/randoStr.npz",allow_pickle=True)
rando = rando['arr_0'].tolist()
else:
rando = makeRandomStrCompletions(shape,conceptSpace,roleSpace,syn)
flatTrue = [[item for sublist in x for item in sublist] for x in trueStatements]
flatRand = [[item for sublist in x for item in sublist] for x in rando]
flatNew = [[item for sublist in x for item in sublist] for x in newStatements]
F1s = array([0,0,0])
rF1s = array([0,0,0])
levTR = 0
levRT = 0
levTN = 0
levNT = 0
countRan = 0
countTrue = 0
countNew = 0
for i in range(len(rando)):
for j in range(len(rando[i])):
for k in range(len(rando[i][j])):
countRan = countRan + 1
if len(trueStatements) > i and len(trueStatements[i]) > j and len(trueStatements[i][j]) > k: #FOR VERY TRUE STATEMENT
countTrue = countTrue + 1
levTR = levTR + findBestMatch(trueStatements[i][j][k],flatRand[i]) #compare to best match in random and vice versa
best = findBestMatch(rando[i][j][k],flatTrue[i])
if best == 0: rF1s[0] = rF1s[0] + 1
levRT = levRT + best
if (len(newStatements) > i and len(newStatements[i]) > 0):
levTN = levTN + findBestMatch(trueStatements[i][j][k],flatNew[i]) #if there are predictions for this KB, compare to best match in there
elif not mix: levTN = levTN + levenshtein(trueStatements[i][j][k],'') #otherwise compare with no prediction
if len(newStatements) > i and len(newStatements[i]) > j and len(newStatements[i][j]) > k: #FOR EVERY PREDICTION
countNew = countNew + 1
if (len(trueStatements) > i and len(trueStatements[i]) > 0):
best = findBestMatch(newStatements[i][j][k],flatTrue[i])
if best == 0: F1s[0] = F1s[0] + 1
levNT = levNT + best #if there are true values for this KB, compare to best match in there
elif not mix: levNT = levNT + levenshtein(newStatements[i][j][k],'') #otherwise compare with no true value
F1s[1] = countNew - F1s[0]
F1s[2] = countTrue - F1s[0]
rF1s[1] = countRan - rF1s[0]
rF1s[2] = countTrue - rF1s[0]
return levTR,levRT,levTN,levNT,countTrue,countNew,countRan,F1s,rF1s
def findBestMatch(statement,reasonerSteps):
return min(map(partial(levenshtein,statement),reasonerSteps))
def custom(conceptSpace,roleSpace,s1,s2):
if len(s1) < len(s2): return custom(conceptSpace,roleSpace,s2,s1)
dist = 0
for k in range(len(s1)):
string1 = s1[k]
string2 = s2[k] if len(s2) > k else ""
if string2 == "":
dist = dist + int(''.join(x for x in string1 if x.isdigit())) # + (conceptSpace if string1[0] == 'C' else roleSpace)
else:
if (string1[0] == 'C' and string2[0] == 'R') or (string1[0] == 'R' and string2[0] == 'C'):
dist = dist + abs(int(''.join(x for x in string1 if x.isdigit())) + int(''.join(x for x in string2 if x.isdigit())))
else:
dist = dist + abs(int(''.join(x for x in string1 if x.isdigit())) - int(''.join(x for x in string2 if x.isdigit())))
return dist
def customDistance(shape,newPred,truePred,conceptSpace,roleSpace,syn,mix):
if (syn and os.path.isfile("saves/randoPred.npz")) or os.path.isfile("ssaves/randoPred.npz"):
rando = numpy.load("saves/randoPred.npz" if syn else "ssaves/randoPred.npz",allow_pickle=True)
rando = rando['arr_0'].tolist()
else:
rando = makeRandomPredCompletions(shape,conceptSpace,roleSpace,syn)
flatTrue = [[item for sublist in x for item in sublist] for x in truePred]
flatRand = [[item for sublist in x for item in sublist] for x in rando]
flatNew = [[item for sublist in x for item in sublist] for x in newPred]
F1s = array([0,0,0])
rF1s = array([0,0,0])
custTR = 0
custRT = 0
custTN = 0
custNT = 0
countRan = 0
countTrue = 0
countNew = 0
for i in range(len(rando)): #KB
for j in range(len(rando[i])): #Step
for k in range(len(rando[i][j])): #Statement
countRan = countRan + 1
if (len(truePred) > i and len(truePred[i]) > j and len(truePred[i][j]) > k):
countTrue = countTrue + 1
custTR = custTR + findBestPredMatch(truePred[i][j][k],flatRand[i],conceptSpace,roleSpace)
best = findBestPredMatch(rando[i][j][k],flatTrue[i],conceptSpace,roleSpace)
if best == 0: rF1s[0] = rF1s[0] + 1
custRT = custRT + best
if (len(newPred) > i and len(newPred[i]) > 0):
custTN = custTN + findBestPredMatch(truePred[i][j][k],flatNew[i],conceptSpace,roleSpace)
elif not mix: custTN = custTN + custom(conceptSpace,roleSpace,truePred[i][j][k],[])
if (len(newPred) > i and len(newPred[i]) > j and len(newPred[i][j]) > k):
countNew = countNew + 1
if (len(truePred) > i and len(truePred[i]) > 0):
best = findBestPredMatch(newPred[i][j][k],flatTrue[i],conceptSpace,roleSpace)
if best == 0: F1s[0] = F1s[0] + 1
custNT = custNT + best
elif not mix: custNT = custNT + custom(conceptSpace,roleSpace,newPred[i][j][k],[])
F1s[1] = countNew - F1s[0]
F1s[2] = countTrue - F1s[0]
rF1s[1] = countRan - rF1s[0]
rF1s[2] = countTrue - rF1s[0]
return custTR,custRT,custTN,custNT,countTrue,countNew,countRan,F1s,rF1s
def findBestPredMatch(statement,otherKB,conceptSpace,roleSpace):
return min(map(partial(custom,conceptSpace,roleSpace,statement),otherKB))
def repeatAndSplitKBs(kbs,steps,splitSize):
newKBs = numpy.empty([kbs.shape[0],steps,kbs.shape[1]],dtype=numpy.float32)
for i in range(len(newKBs)):
for j in range(steps):
newKBs[i][j] = kbs[i]
return numpy.split(newKBs,[int(len(newKBs)*splitSize)])
def formatDataSynth(log,conceptSpace,roleSpace,KBs,supports,output):
fileShapes1 = [max(len(max(supports, key=lambda coll: len(coll))),len(max(output, key=lambda coll: len(coll)))),len(max(supports, key=lambda coll: len(coll[0]))[0]),len(max(output, key=lambda coll: len(coll[0]))[0])]
KBs_test,KBs_train = repeatAndSplitKBs(KBs,fileShapes1[0],0.1)
X_train, X_test, y_train,y_test = splitTensors(supports, output, 0.1)
X_train = pad(X_train,maxlen1=fileShapes1[0],maxlen2=fileShapes1[1])
X_test = pad(X_test,maxlen1=fileShapes1[0],maxlen2=fileShapes1[1])
y_train = pad(y_train,maxlen1=fileShapes1[0],maxlen2=fileShapes1[2])
y_test = pad(y_test,maxlen1=fileShapes1[0],maxlen2=fileShapes1[2])
print("KBs shape:\t\t{}\nExtended KBs shape:\t{}{}\nDependencies shape:\t{}{}\nOutput shape:\t\t{}{}\n\n".format(KBs.shape,KBs_train.shape,KBs_test.shape,X_train.shape,X_test.shape,y_train.shape,y_test.shape))
log.write("KBs shape,{}\nExtended KBs shape,{},{}\nDependencies shape,{},{}\nOutput shape,{},{}\n\n".format(KBs.shape,KBs_train.shape,KBs_test.shape,X_train.shape,X_test.shape,y_train.shape,y_test.shape))
KBvec,KBstr = vecToStatements(KBs_test,conceptSpace,roleSpace)
truePreds,trueStatements = vecToStatements(y_test,conceptSpace,roleSpace)
placeholder,inputs = vecToStatements(X_test,conceptSpace,roleSpace)
writeVectorFile("output/KBsIn.txt",KBstr)
writeVectorFile("output/supports.txt",inputs)
writeVectorFile("output/reasonerCompletion.txt",trueStatements)
return KBs_test,KBs_train,X_train,X_test,y_train,y_test,truePreds,trueStatements,None
def formatDataSno(log,conceptSpace,roleSpace,KBs,supports,output,localMaps,stats):
labels = collapseLabelMap(localMaps,stats[0][2],stats[1][2],stats[4][1])
fileShapes1 = [max(len(max(supports, key=lambda coll: len(coll))),len(max(output, key=lambda coll: len(coll)))),len(max(supports, key=lambda coll: len(coll[0]))[0]),len(max(output, key=lambda coll: len(coll[0]))[0])]
KBs_test,KBs_train = repeatAndSplitKBs(KBs,fileShapes1[0],0.33)
testLabels = labels[:len(KBs_test)]
trainLabels = labels[len(KBs_test):]
X_train, X_test, y_train, y_test = splitTensors(supports, output, 0.33)
X_train = pad(X_train,maxlen1=fileShapes1[0],maxlen2=fileShapes1[1])
X_test = pad(X_test,maxlen1=fileShapes1[0],maxlen2=fileShapes1[1])
y_train = pad(y_train,maxlen1=fileShapes1[0],maxlen2=fileShapes1[2])
y_test = pad(y_test,maxlen1=fileShapes1[0],maxlen2=fileShapes1[2])
print("KBs shape:\t\t{}\nExtended KBs shape:\t{}{}\nDependencies shape:\t{}{}\nOutput shape:\t\t{}{}\n\n".format(KBs.shape,KBs_train.shape,KBs_test.shape,X_train.shape,X_test.shape,y_train.shape,y_test.shape))
log.write("KBs shape,{}\nExtended KBs shape,{},{}\nDependencies shape,{},{}\nOutput shape,{},{}\n\n".format(KBs.shape,KBs_train.shape,KBs_test.shape,X_train.shape,X_test.shape,y_train.shape,y_test.shape))
KBvec,KBstr = vecToStatementsWithLabels(KBs_test,conceptSpace,roleSpace,testLabels)
preds,trueStatements = vecToStatementsWithLabels(y_test,conceptSpace,roleSpace,testLabels)
placeholder,inputs = vecToStatementsWithLabels(X_test,conceptSpace,roleSpace,testLabels)
writeVectorFile("snoutput/KBsIn.txt",KBstr)
writeVectorFile("snoutput/supports.txt",inputs)
writeVectorFile("snoutput/reasonerCompletion.txt",trueStatements)
truePreds,trueStatements = vecToStatements(y_test,conceptSpace,roleSpace)
return KBs_test,KBs_train,X_train,X_test,y_train,y_test,truePreds,trueStatements,labels
def formatDataSyn2Sno(log,conceptSpace,roleSpace,KBs,supports,output,sKBs,ssupports,soutput,localMaps,stats):
labels = collapseLabelMap(localMaps,stats[0][2],stats[1][2],stats[4][1])
fileShapes1 = [max(len(max(supports, key=lambda coll: len(coll))),len(max(output, key=lambda coll: len(coll)))),len(max(supports, key=lambda coll: len(coll[0]))[0]),len(max(output, key=lambda coll: len(coll[0]))[0])]
KBs_test,KBs_train = repeatAndSplitKBs(KBs,fileShapes1[0],0.33)
KBs_test,a = repeatAndSplitKBs(sKBs,fileShapes1[0],0.33)
testLabels = labels[:len(KBs_test)]
trainLabels = labels[len(KBs_test):]
X_train,X_test, y_train,y_test = splitTensors(supports, output, 0.33)
a,X_test,a,y_test = splitTensors(ssupports,soutput,0.33)
X_train = pad(X_train,maxlen1=fileShapes1[0],maxlen2=fileShapes1[1])
X_test = pad(X_test,maxlen1=fileShapes1[0],maxlen2=fileShapes1[1])
y_train = pad(y_train,maxlen1=fileShapes1[0],maxlen2=fileShapes1[2])
y_test = pad(y_test,maxlen1=fileShapes1[0],maxlen2=fileShapes1[2])
print("KBs shape:\t\t{}\nExtended KBs shape:\t{}{}\nDependencies shape:\t{}{}\nOutput shape:\t\t{}{}\n\n".format(KBs.shape,KBs_train.shape,KBs_test.shape,X_train.shape,X_test.shape,y_train.shape,y_test.shape))
log.write("KBs shape,{}\nExtended KBs shape,{},{}\nDependencies shape,{},{}\nOutput shape,{},{}\n\n".format(KBs.shape,KBs_train.shape,KBs_test.shape,X_train.shape,X_test.shape,y_train.shape,y_test.shape))
truePreds,trueStatements = vecToStatements(y_test,conceptSpace,roleSpace)
return KBs_test,KBs_train,X_train,X_test,y_train,y_test,truePreds,trueStatements,testLabels
def formatDataSno2Syn(log,conceptSpace,roleSpace,KBs,supports,output,sKBs,ssupports,soutput,localMaps,stats):
labels = collapseLabelMap(localMaps,stats[0][2],stats[1][2],stats[4][1])
fileShapes1 = [max(len(max(supports, key=lambda coll: len(coll))),len(max(output, key=lambda coll: len(coll)))),len(max(supports, key=lambda coll: len(coll[0]))[0]),len(max(output, key=lambda coll: len(coll[0]))[0])]
a,KBs_train = repeatAndSplitKBs(KBs,fileShapes1[0],0.33)
KBs_test,a = repeatAndSplitKBs(sKBs,fileShapes1[0],0.33)
testLabels = labels[:len(KBs_test)]
trainLabels = labels[len(KBs_test):]
X_train, X_test, y_train,y_test = splitTensors(supports, output, 0.33)
a,X_test,a,y_test = splitTensors(ssupports,soutput,0.33)
X_train = pad(X_train,maxlen1=fileShapes1[0],maxlen2=fileShapes1[1])
X_test = pad(X_test,maxlen1=fileShapes1[0],maxlen2=fileShapes1[1])
y_train = pad(y_train,maxlen1=fileShapes1[0],maxlen2=fileShapes1[2])
y_test = pad(y_test,maxlen1=fileShapes1[0],maxlen2=fileShapes1[2])
print("KBs shape:\t\t{}\nExtended KBs shape:\t{}{}\nDependencies shape:\t{}{}\nOutput shape:\t\t{}{}\n\n".format(KBs.shape,KBs_train.shape,KBs_test.shape,X_train.shape,X_test.shape,y_train.shape,y_test.shape))
log.write("KBs shape,{}\nExtended KBs shape,{},{}\nDependencies shape,{},{}\nOutput shape,{},{}\n\n".format(KBs.shape,KBs_train.shape,KBs_test.shape,X_train.shape,X_test.shape,y_train.shape,y_test.shape))
truePreds,trueStatements = vecToStatements(y_test,conceptSpace,roleSpace)
return KBs_test,KBs_train,X_train,X_test,y_train,y_test,truePreds,trueStatements,testLabels
def precision(TP,FP):
return 0 if TP == 0 and FP == 0 else TP / (TP + FP)
def recall(TP,FN):
return 0 if TP == 0 and FN == 0 else TP / (TP + FN)
def F1(precision,recall):
return 0 if precision == 0 and recall == 0 else 2 * (precision * recall) / (precision + recall)
def writeAccMeasures(F,rF,log):
TPs,FPs,FNs = F
pre = precision(TPs,FPs)
rec = recall(TPs,FNs)
F = F1(pre,rec)
log.write("\nPrediction Accuracy For this Distance Measure\nTrue Positives,{}\nFalse Positives,{}\nFalse Negatives,{}\nPrecision,{}\nRecall,{}\nF1 Score,{}\n".format(TPs,FPs,FNs,pre,rec,F))
x = array([TPs,FPs,FNs,pre,rec,F])
TPs,FPs,FNs = rF
pre = precision(TPs,FPs)
rec = recall(TPs,FNs)
F = F1(pre,rec)
log.write("\nRandom Accuracy For this Distance Measure\nTrue Positives,{}\nFalse Positives,{}\nFalse Negatives,{}\nPrecision,{}\nRecall,{}\nF1 Score,{}\n".format(TPs,FPs,FNs,pre,rec,F))
return array([x,array([TPs,FPs,FNs,pre,rec,F])])
def distanceEvaluations(log,shape,newPreds,truePreds,newStatements,trueStatements,conceptSpace,roleSpace,syn,mix,newErrs,newErrStatements):
if mix:
levTR,levRT,levTN,levNT,sizeTrue,sizeNew,sizeRan,F11,F111 = levDistanceNoNums(shape,newStatements,trueStatements,conceptSpace,roleSpace,syn,False)
log.write("\nRegular Distance\n\nNo Nums\nLevenshtein Distance From Reasoner to Random Data,{}\nLevenshtein Distance From Random to Reasoner Data,{}\nLevenshtein Distance From Reasoner to Predicted Data,{}\nLevenshtein Distance From Prediction to Reasoner Data,{}\n".format(levTR,levRT,levTN,levNT))
log.write("Average Levenshtein Distance From Reasoner to Random Statement,{}\nAverage Levenshtein Distance From Random to Reasoner Statement,{}\nAverage Levenshtein Distance From Reasoner to Predicted Statement,{}\nAverage Levenshtein Distance From Prediction to Reasoner Statement,{}\n".format(levTR/sizeTrue,levRT/sizeRan,levTN/sizeTrue,0 if sizeNew == 0 else levNT/sizeNew))
a = writeAccMeasures(F11,F111,log)
levTR2,levRT2,levTN2,levNT2,sizeTrue2,sizeNew2,sizeRan2,F12,F121 = levDistance(shape,newStatements,trueStatements,conceptSpace,roleSpace,syn,False)
log.write("\nNums\nLevenshtein Distance From Reasoner to Random Data,{}\nLevenshtein Distance From Random to Reasoner Data,{}\nLevenshtein Distance From Reasoner to Predicted Data,{}\nLevenshtein Distance From Prediction to Reasoner Data,{}\n".format(levTR2,levRT2,levTN2,levNT2))
log.write("Average Levenshtein Distance From Reasoner to Random Statement,{}\nAverage Levenshtein Distance From Random to Reasoner Statement,{}\nAverage Levenshtein Distance From Reasoner to Predicted Statement,{}\nAverage Levenshtein Distance From Prediction to Reasoner Statement,{}\n".format(levTR2/sizeTrue2,levRT2/sizeRan2,levTN2/sizeTrue2,0 if sizeNew2 == 0 else levNT2/sizeNew2))
b = writeAccMeasures(F12,F121,log)
custTR,custRT,custTN,custNT,countTrue,countNew,countRan,F13,F131 = customDistance(shape,newPreds,truePreds,conceptSpace,roleSpace,syn,False)
log.write("\nCustom\nCustom Distance From Reasoner to Random Data,{}\nCustom Distance From Random to Reasoner Data,{}\nCustom Distance From Reasoner to Predicted Data,{}\nCustom Distance From Predicted to Reasoner Data,{}\n".format(custTR,custRT,custTN,custNT))
log.write("Average Custom Distance From Reasoner to Random Statement,{}\nAverage Custom Distance From Random to Reasoner Statement,{}\nAverage Custom Distance From Reasoner to Predicted Statement,{}\nAverage Custom Distance From Prediction to Reasoner Statement,{}\n".format(custTR/countTrue,custRT/countRan,custTN/countTrue,0 if countNew == 0 else custNT/countNew))
c = writeAccMeasures(F13,F131,log)
x = array([array([levTR,levRT,levTN,levNT,sizeTrue,sizeNew,sizeRan,a]),array([levTR2,levRT2,levTN2,levNT2,sizeTrue2,sizeNew2,sizeRan2,b]),array([custTR,custRT,custTN,custNT,countTrue,countNew,countRan,c])])
levTR,levRT,levTN,levNT,sizeTrue,sizeNew,sizeRan,F11,F111 = levDistanceNoNums(shape,newStatements,trueStatements,conceptSpace,roleSpace,syn,mix)
log.write("\nDistance Ignoring Prediction Gaps\n\nNo Nums\nLevenshtein Distance From Reasoner to Random Data,{}\nLevenshtein Distance From Random to Reasoner Data,{}\nLevenshtein Distance From Reasoner to Predicted Data,{}\nLevenshtein Distance From Prediction to Reasoner Data,{}\n".format(levTR,levRT,levTN,levNT))
log.write("Average Levenshtein Distance From Reasoner to Random Statement,{}\nAverage Levenshtein Distance From Random to Reasoner Statement,{}\nAverage Levenshtein Distance From Reasoner to Predicted Statement,{}\nAverage Levenshtein Distance From Prediction to Reasoner Statement,{}\n".format(levTR/sizeTrue,levRT/sizeRan,levTN/sizeTrue,0 if sizeNew == 0 else levNT/sizeNew))
a = writeAccMeasures(F11,F111,log)
levTR2,levRT2,levTN2,levNT2,sizeTrue2,sizeNew2,sizeRan2,F12,F121 = levDistance(shape,newStatements,trueStatements,conceptSpace,roleSpace,syn,mix)
log.write("\nNums\nLevenshtein Distance From Reasoner to Random Data,{}\nLevenshtein Distance From Random to Reasoner Data,{}\nLevenshtein Distance From Reasoner to Predicted Data,{}\nLevenshtein Distance From Prediction to Reasoner Data,{}\n".format(levTR2,levRT2,levTN2,levNT2))
log.write("Average Levenshtein Distance From Reasoner to Random Statement,{}\nAverage Levenshtein Distance From Random to Reasoner Statement,{}\nAverage Levenshtein Distance From Reasoner to Predicted Statement,{}\nAverage Levenshtein Distance From Prediction to Reasoner Statement,{}\n".format(levTR2/sizeTrue2,levRT2/sizeRan2,levTN2/sizeTrue2,0 if sizeNew2 == 0 else levNT2/sizeNew2))
b = writeAccMeasures(F12,F121,log)
custTR,custRT,custTN,custNT,countTrue,countNew,countRan,F13,F131 = customDistance(shape,newPreds,truePreds,conceptSpace,roleSpace,syn,mix)
log.write("\nCustom\nCustom Distance From Reasoner to Random Data,{}\nCustom Distance From Random to Reasoner Data,{}\nCustom Distance From Reasoner to Predicted Data,{}\nCustom Distance From Predicted to Reasoner Data,{}\n".format(custTR,custRT,custTN,custNT))
log.write("Average Custom Distance From Reasoner to Random Statement,{}\nAverage Custom Distance From Random to Reasoner Statement,{}\nAverage Custom Distance From Reasoner to Predicted Statement,{}\nAverage Custom Distance From Prediction to Reasoner Statement,{}\n".format(custTR/countTrue,custRT/countRan,custTN/countTrue,0 if countNew == 0 else custNT/countNew))
c = writeAccMeasures(F13,F131,log)
return x,array([array([levTR,levRT,levTN,levNT,sizeTrue,sizeNew,sizeRan,a]),array([levTR2,levRT2,levTN2,levNT2,sizeTrue2,sizeNew2,sizeRan2,b]),array([custTR,custRT,custTN,custNT,countTrue,countNew,countRan,c])])
elif newErrs:
levTR,levRT,levTN,levNT,sizeTrue,sizeNew,sizeRan,F11,F111 = levDistanceNoNums(shape,newStatements,trueStatements,conceptSpace,roleSpace,syn,mix)
f,g,h,i, j,k,l, m,n = levDistanceNoNums(shape,newErrStatements,trueStatements,conceptSpace,roleSpace,syn,mix)
log.write("\nNo Nums\nLevenshtein Distance From Reasoner to Random Data,{}\nLevenshtein Distance From Random to Reasoner Data,{}\nLevenshtein Distance From Reasoner to Error Data,{}\nLevenshtein Distance From Error to Reasoner Data,{}\n".format(levTR,levRT,levTN,levNT))
log.write("Levenshtein Distance From Reasoner to Error Data,{}\nLevenshtein Distance From Error to Reasoner Data,{}\n".format(h,i))
log.write("Average Levenshtein Distance From Reasoner to Random Statement,{}\nAverage Levenshtein Distance From Random to Reasoner Statement,{}\nAverage Levenshtein Distance From Reasoner to Predicted Statement,{}\nAverage Levenshtein Distance From Prediction to Reasoner Statement,{}\n".format(levTR/sizeTrue,levRT/sizeRan,levTN/sizeTrue,0 if sizeNew == 0 else levNT/sizeNew))
log.write("Average Levenshtein Distance From Reasoner to Error Statement,{}\nAverage Levenshtein Distance From Error to Reasoner Statement,{}\n".format(h/j,0 if k == 0 else i/k))
a = writeAccMeasures(F11,F111,log)
TPs,FPs,FNs = m
pre = precision(TPs,FPs)
rec = recall(TPs,FNs)
F = F1(pre,rec)
log.write("\nError Accuracy For this Distance Measure\nTrue Positives,{}\nFalse Positives,{}\nFalse Negatives,{}\nPrecision,{}\nRecall,{}\nF1 Score,{}\n".format(TPs,FPs,FNs,pre,rec,F))
x = array([h,i,j,k,array([TPs,FPs,FNs,pre,rec,F])])
levTR2,levRT2,levTN2,levNT2,sizeTrue2,sizeNew2,sizeRan2,F12,F121 = levDistance(shape,newStatements,trueStatements,conceptSpace,roleSpace,syn,mix)
f1,g1,h1,i1,j1,k1,l1,m1,n1 = levDistance(shape,newErrStatements,trueStatements,conceptSpace,roleSpace,syn,mix)
log.write("\nNums\nLevenshtein Distance From Reasoner to Random Data,{}\nLevenshtein Distance From Random to Reasoner Data,{}\nLevenshtein Distance From Reasoner to Predicted Data,{}\nLevenshtein Distance From Prediction to Reasoner Data,{}\n".format(levTR2,levRT2,levTN2,levNT2))
log.write("Levenshtein Distance From Reasoner to Error Data,{}\nLevenshtein Distance From Error to Reasoner Data,{}\n".format(f1,g1))
log.write("Average Levenshtein Distance From Reasoner to Random Statement,{}\nAverage Levenshtein Distance From Random to Reasoner Statement,{}\nAverage Levenshtein Distance From Reasoner to Predicted Statement,{}\nAverage Levenshtein Distance From Prediction to Reasoner Statement,{}\n".format(levTR2/sizeTrue2,levRT2/sizeRan2,levTN2/sizeTrue2,0 if sizeNew2 == 0 else levNT2/sizeNew2))
log.write("Average Levenshtein Distance From Reasoner to Error Statement,{}\nAverage Levenshtein Distance From Error to Reasoner Statement,{}\n".format(h1/j1,0 if k1 == 0 else i1/k1))
b = writeAccMeasures(F12,F121,log)
TPs,FPs,FNs = m1
pre = precision(TPs,FPs)
rec = recall(TPs,FNs)
F = F1(pre,rec)
log.write("\nError Accuracy For this Distance Measure\nTrue Positives,{}\nFalse Positives,{}\nFalse Negatives,{}\nPrecision,{}\nRecall,{}\nF1 Score,{}\n".format(TPs,FPs,FNs,pre,rec,F))
x1 = array([h1,i1,j1,k1,array([TPs,FPs,FNs,pre,rec,F])])
custTR,custRT,custTN,custNT,countTrue,countNew,countRan,F13,F131 = customDistance(shape,newPreds,truePreds,conceptSpace,roleSpace,syn,mix)
f2,g2,h2,i2,j2,k2,l2,m2,n2 = customDistance(shape,newErrs,truePreds,conceptSpace,roleSpace,syn,mix)
log.write("\nCustom\nCustom Distance From Reasoner to Random Data,{}\nCustom Distance From Random to Reasoner Data,{}\nCustom Distance From Reasoner to Predicted Data,{}\nCustom Distance From Predicted to Reasoner Data,{}\n".format(custTR,custRT,custTN,custNT))
log.write("Custom Distance From Reasoner to Error Data,{}\nCustom Distance From Error to Reasoner Data,{}\n".format(f2,g2))
log.write("Average Custom Distance From Reasoner to Random Statement,{}\nAverage Custom Distance From Random to Reasoner Statement,{}\nAverage Custom Distance From Reasoner to Predicted Statement,{}\nAverage Custom Distance From Prediction to Reasoner Statement,{}\n".format(custTR/countTrue,custRT/countRan,custTN/countTrue,0 if countNew == 0 else custNT/countNew))
log.write("Average Custom Distance From Reasoner to Error Statement,{}\nAverage Custom Distance From Error to Reasoner Statement,{}\n".format(h2/j2,0 if k2 == 0 else i2/k2))
c = writeAccMeasures(F13,F131,log)
TPs,FPs,FNs = m2
pre = precision(TPs,FPs)
rec = recall(TPs,FNs)
F = F1(pre,rec)
log.write("\nError Accuracy For this Distance Measure\nTrue Positives,{}\nFalse Positives,{}\nFalse Negatives,{}\nPrecision,{}\nRecall,{}\nF1 Score,{}\n".format(TPs,FPs,FNs,pre,rec,F))
x2 = array([h2,i2,j2,k2,array([TPs,FPs,FNs,pre,rec,F])])
return array([array([levTR,levRT,levTN,levNT,sizeTrue,sizeNew,sizeRan,a,x]),array([levTR2,levRT2,levTN2,levNT2,sizeTrue2,sizeNew2,sizeRan2,b,x1]),array([custTR,custRT,custTN,custNT,countTrue,countNew,countRan,c,x2])])
else:
levTR,levRT,levTN,levNT,sizeTrue,sizeNew,sizeRan,F11,F111 = levDistanceNoNums(shape,newStatements,trueStatements,conceptSpace,roleSpace,syn,mix)
log.write("\nNo Nums\nLevenshtein Distance From Reasoner to Random Data,{}\nLevenshtein Distance From Random to Reasoner Data,{}\nLevenshtein Distance From Reasoner to Predicted Data,{}\nLevenshtein Distance From Prediction to Reasoner Data,{}\n".format(levTR,levRT,levTN,levNT))
log.write("Average Levenshtein Distance From Reasoner to Random Statement,{}\nAverage Levenshtein Distance From Random to Reasoner Statement,{}\nAverage Levenshtein Distance From Reasoner to Predicted Statement,{}\nAverage Levenshtein Distance From Prediction to Reasoner Statement,{}\n".format(levTR/sizeTrue,levRT/sizeRan,levTN/sizeTrue,0 if sizeNew == 0 else levNT/sizeNew))
a = writeAccMeasures(F11,F111,log)
levTR2,levRT2,levTN2,levNT2,sizeTrue2,sizeNew2,sizeRan2,F12,F121 = levDistance(shape,newStatements,trueStatements,conceptSpace,roleSpace,syn,mix)
log.write("\nNums\nLevenshtein Distance From Reasoner to Random Data,{}\nLevenshtein Distance From Random to Reasoner Data,{}\nLevenshtein Distance From Reasoner to Predicted Data,{}\nLevenshtein Distance From Prediction to Reasoner Data,{}\n".format(levTR2,levRT2,levTN2,levNT2))
log.write("Average Levenshtein Distance From Reasoner to Random Statement,{}\nAverage Levenshtein Distance From Random to Reasoner Statement,{}\nAverage Levenshtein Distance From Reasoner to Predicted Statement,{}\nAverage Levenshtein Distance From Prediction to Reasoner Statement,{}\n".format(levTR2/sizeTrue2,levRT2/sizeRan2,levTN2/sizeTrue2,0 if sizeNew2 == 0 else levNT2/sizeNew2))
b = writeAccMeasures(F12,F121,log)
custTR,custRT,custTN,custNT,countTrue,countNew,countRan,F13,F131 = customDistance(shape,newPreds,truePreds,conceptSpace,roleSpace,syn,mix)
log.write("\nCustom\nCustom Distance From Reasoner to Random Data,{}\nCustom Distance From Random to Reasoner Data,{}\nCustom Distance From Reasoner to Predicted Data,{}\nCustom Distance From Predicted to Reasoner Data,{}\n".format(custTR,custRT,custTN,custNT))
log.write("Average Custom Distance From Reasoner to Random Statement,{}\nAverage Custom Distance From Random to Reasoner Statement,{}\nAverage Custom Distance From Reasoner to Predicted Statement,{}\nAverage Custom Distance From Prediction to Reasoner Statement,{}\n".format(custTR/countTrue,custRT/countRan,custTN/countTrue,0 if countNew == 0 else custNT/countNew))
c = writeAccMeasures(F13,F131,log)
return array([array([levTR,levRT,levTN,levNT,sizeTrue,sizeNew,sizeRan,a]),array([levTR2,levRT2,levTN2,levNT2,sizeTrue2,sizeNew2,sizeRan2,b]),array([custTR,custRT,custTN,custNT,countTrue,countNew,countRan,c])])
def trainingStats(log,mseNew,mse0,mseL):
log.write("Training Statistics\nPrediction Mean Squared Error,{}\nLearned Reduction MSE,{}\nIncrease MSE on Test,{}\nTraining Percent Change MSE,{}\n".format(numpy.float32(mseNew),mse0-mseL,numpy.float32(mseNew)-mseL,(mseL - mse0)/mse0*100))
def shallowSystem(n_epochs0,learning_rate0,trainlog,evallog,conceptSpace,roleSpace,allTheData,syn,mix,n):
KBs_test,KBs_train,X_train,X_test,y_train,y_test,truePreds,trueStatements,labels,errPreds,errStatements = allTheData
trainlog.write("Piecewise LSTM Part One\nEpoch,Mean Squared Error,Root Mean Squared Error\n")
evallog.write("Piecewise LSTM Part One\n")
print("")
n_neurons0 = X_train.shape[2]
X0 = tf.placeholder(tf.float32, shape=[None,KBs_train.shape[1],KBs_train.shape[2]])
y0 = tf.placeholder(tf.float32, shape=[None,X_train.shape[1],X_train.shape[2]])
outputs0, states0 = tf.nn.dynamic_rnn(tf.contrib.rnn.LSTMCell(num_units=n_neurons0), X0, dtype=tf.float32)
loss0 = tf.losses.mean_squared_error(y0,outputs0)
optimizer0 = tf.train.AdamOptimizer(learning_rate=learning_rate0)
training_op0 = optimizer0.minimize(loss0)
#saver = tf.train.Saver()
init0 = tf.global_variables_initializer()
with tf.Session() as sess:
init0.run()
mse0 = 0
mseL = 0
for epoch in range(n_epochs0):
print("Piecewise System\tEpoch: {}".format(epoch))
ynew,a = sess.run([outputs0,training_op0],feed_dict={X0: KBs_train,y0: X_train})
mse = loss0.eval(feed_dict={outputs0: ynew, y0: X_train})
if epoch == 0: mse0 = mse
if epoch == n_epochs0 - 1: mseL = mse
trainlog.write("{},{},{}\n".format(epoch,mse,math.sqrt(mse)))
if mse < 0.00001:
mseL = mse
break
print("\nTesting first half\n")
y_pred = sess.run(outputs0,feed_dict={X0: KBs_test,y0: X_test})
mseNew = loss0.eval(feed_dict={outputs0: y_pred, y0: X_test})
newPreds,newStatements = vecToStatements(y_pred,conceptSpace,roleSpace)
trainingStats(evallog,mseNew,mse0,mseL)
writeVectorFile("crossValidationFolds/{}output/learnedSupportsP[{}].txt".format("" if syn else "sn",n),newStatements)
numpy.savez("crossValidationFolds/{}saves/halfwayData[{}]".format("" if syn else "s",n), y_pred)
#saver.save(sess,"{}{}saves/firstHalfModel[{}]".format("" if n == 1 else "crossValidationFolds/","" if syn else "s",n))
tf.reset_default_graph()
trainlog.write("Piecewise LSTM Part Two\nEpoch,Mean Squared Error,Root Mean Squared Error\n")
evallog.write("\nPiecewise LSTM Part Two\n")
n_neurons1 = y_train.shape[2]
X1 = tf.placeholder(tf.float32, shape=[None,X_train.shape[1],X_train.shape[2]])
y1 = tf.placeholder(tf.float32, shape=[None,y_train.shape[1],y_train.shape[2]])
outputs1, states1 = tf.nn.dynamic_rnn(tf.contrib.rnn.LSTMCell(num_units=n_neurons1), X1, dtype=tf.float32)
loss1 = tf.losses.mean_squared_error(y1,outputs1)
optimizer1 = tf.train.AdamOptimizer(learning_rate=learning_rate0)
training_op1 = optimizer1.minimize(loss1)
#saver = tf.train.Saver()
init1 = tf.global_variables_initializer()
with tf.Session() as sess:
init1.run()
mse0 = 0
mseL = 0
for epoch in range(n_epochs0):
print("Piecewise System\tEpoch: {}".format(epoch+n_epochs0))
ynew,a = sess.run([outputs1,training_op1],feed_dict={X1: X_train,y1: y_train})
mse = loss1.eval(feed_dict={outputs1: ynew, y1: y_train})
if epoch == 0: mse0 = mse
if epoch == n_epochs0 - 1: mseL = mse
trainlog.write("{},{},{}\n".format(epoch,mse,math.sqrt(mse)))
if mse < 0.00001:
mseL = mse
break
print("\nTesting second half")
y_pred = sess.run(outputs1,feed_dict={X1: X_test})
mseNew = loss1.eval(feed_dict={outputs1: y_pred, y1: y_test})
trainingStats(evallog,mseNew,mse0,mseL)
print("\nEvaluating Result")
evallog.write("\nReasoner Support Test Data Evaluation\n")
newPreds,newStatements = vecToStatements(y_pred,conceptSpace,roleSpace)
writeVectorFile("crossValidationFolds/{}output/predictedOutLeftOverSupportTest[{}].txt".format("" if syn else "sn",n),newStatements)
evals = distanceEvaluations(evallog,y_pred.shape,newPreds,truePreds,newStatements,trueStatements,conceptSpace,roleSpace,syn,mix,False,False)
data = numpy.load("crossValidationFolds/{}saves/halfwayData[{}].npz".format("" if syn else "s",n),allow_pickle=True)
data = data['arr_0']
evallog.write("\nSaved Test Data From Previous LSTM Evaluation\n")
y_pred = sess.run(outputs1,feed_dict={X1: data})
mseNew = loss1.eval(feed_dict={outputs1: y_pred, y1: y_test})
evallog.write("\nTesting Statistic\nIncrease MSE on Saved,{}\n".format(numpy.float32(mseNew)-mseL))
newPreds,newStatements = vecToStatementsWithLabels(y_pred,conceptSpace,roleSpace,labels) if (not mix and not syn) else vecToStatements(y_pred,conceptSpace,roleSpace)
writeVectorFile("crossValidationFolds/{}output/predictionSavedKBPipeline[{}].txt".format("" if syn else "sn",n),newStatements)
if (not mix and not syn):
newPreds,newStatements = vecToStatements(y_pred,conceptSpace,roleSpace)
#saver.save(sess,"{}{}saves/secondHalfModel[{}]".format("" if n == 1 else "crossValidationFolds/","" if syn else "s",n))
return distanceEvaluations(evallog,y_pred.shape,newPreds,truePreds,newStatements,trueStatements,conceptSpace,roleSpace,syn,mix,errPreds,errStatements)
def deepSystem(n_epochs2,learning_rate2,trainlog,evallog,conceptSpace,roleSpace,allTheData,syn,mix,n):
KBs_test,KBs_train,X_train,X_test,y_train,y_test,truePreds,trueStatements,labels,errPreds,errStatements = allTheData
trainlog.write("Deep LSTM\nEpoch,Mean Squared Error,Root Mean Squared Error\n")
evallog.write("\nDeep LSTM\n\n")
print("")
X0 = tf.placeholder(tf.float32, shape=[None,KBs_train.shape[1],KBs_train.shape[2]])
y1 = tf.placeholder(tf.float32, shape=[None,y_train.shape[1],y_train.shape[2]])
outputs2, states2 = tf.nn.dynamic_rnn(tf.contrib.rnn.MultiRNNCell([tf.contrib.rnn.LSTMCell(num_units=X_train.shape[2]),tf.contrib.rnn.LSTMCell(num_units=y_train.shape[2])]), X0, dtype=tf.float32)
loss2 = tf.losses.mean_squared_error(y1,outputs2)
optimizer2 = tf.train.AdamOptimizer(learning_rate=learning_rate2)
training_op2 = optimizer2.minimize(loss2)
#saver = tf.train.Saver()
init2 = tf.global_variables_initializer()
with tf.Session() as sess:
init2.run()
mse0 = 0
mseL = 0
for epoch in range(n_epochs2):
print("Deep System\t\tEpoch: {}".format(epoch))
ynew,a = sess.run([outputs2,training_op2],feed_dict={X0: KBs_train,y1: y_train})
mse = loss2.eval(feed_dict={outputs2: ynew, y1: y_train})
if epoch == 0: mse0 = mse
if epoch == n_epochs2 - 1: mseL = mse
trainlog.write("{},{},{}\n".format(epoch,mse,math.sqrt(mse)))
if mse < 0.0001:
mseL = mse
break
print("\nEvaluating Result\n")
y_pred = sess.run(outputs2,feed_dict={X0: KBs_test})
mseNew = loss2.eval(feed_dict={outputs2: y_pred, y1: y_test})
trainingStats(evallog,mseNew,mse0,mseL)