-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathrecognitionModel.py
More file actions
1471 lines (1274 loc) · 66.5 KB
/
Copy pathrecognitionModel.py
File metadata and controls
1471 lines (1274 loc) · 66.5 KB
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
from spatial_transformer import *
from mixtureDensityNetwork import *
from distanceExamples import *
from architectures import architectures
from batch import BatchIterator
from language import *
from render import render,animateMatrices
from utilities import *
from distanceMetrics import blurredDistance,asymmetricBlurredDistance,analyzeAsymmetric
from makeSyntheticData import randomScene
from groundTruthParses import getGroundTruthParse
from loadTrainingExamples import *
from recurrentNetwork import RecurrentNetwork
import argparse
import sys
import tensorflow as tf
import os
import io
from time import time
import pickle
import cProfile
from multiprocessing import Pool
import random
TESTINGFRACTION = 0.05
CONTINUOUSROUNDING = 1
ATTENTIONCANROTATE = True
[STOP,CIRCLE,LINE,RECTANGLE,LABEL] = range(5)
class StandardPrimitiveDecoder():
def makeNetwork(self,imageRepresentation):
# A placeholder for each target
self.targetPlaceholder = [ (tf.placeholder(tf.int32, [None]) if t == int
else tf.placeholder(tf.float32, [None]))
for t,d in self.outputDimensions ]
if not hasattr(self, 'hiddenSizes'):
self.hiddenSizes = [None]*len(self.outputDimensions)
if not hasattr(self, 'attentionIndices'):
self.attentionIndices = []
self.attentionTransforms = []
# A prediction for each target
self.prediction = []
# "hard" predictions (integers or floats)
self.hard = []
# "soft" predictions (logits: only for categorical variables)
self.soft = []
# variable in the graph representing the loss of this decoder
self.loss = []
# populate the above arrays
predictionInputs = [flattenImageOutput(imageRepresentation)]
for j,(t,d) in enumerate(self.outputDimensions):
# should we modify the image representation using a spatial transformer?
if j in self.attentionIndices:
theta0 = np.array([[1., 0, 0], [0, 1., 0]]).astype('float32').flatten()
theta = tf.layers.dense(tf.concat(predictionInputs[1:],axis = 1),
6,
activation = tf.nn.tanh,
bias_initializer=tf.constant_initializer(theta0),
kernel_initializer = tf.zeros_initializer())
if not ATTENTIONCANROTATE:
# force the off diagonal entries to be 0
theta = tf.multiply(theta, np.array([[1., 0, 1], [0, 1., 1]]).astype('float32').flatten())
# save the transform as a field so that we can visualize it later
self.attentionTransforms += [theta]
# clobber the existing image input with the region that attention is focusing on
C = int(imageRepresentation.shape[3]) # channel count
transformed = spatial_transformer_network(imageRepresentation,
theta,
(self.attentionSize,self.attentionSize))
flat = tf.reshape(transformed,
[-1, self.attentionSize*self.attentionSize*C])
predictionInputs[0] = flat
# construct the intermediate representation, if the decoder has one
# also pass along the transformation if we have it
if j in self.attentionIndices:
intermediateRepresentation = tf.concat(predictionInputs + [theta],axis = 1)
else:
intermediateRepresentation = tf.concat(predictionInputs,axis = 1)
if self.hiddenSizes[j] != None and self.hiddenSizes[j] > 0:
intermediateRepresentation = tf.layers.dense(intermediateRepresentation,
self.hiddenSizes[j],
activation = tf.nn.relu)
# decoding of categorical variables
if t == int:
# p = prediction
p = tf.layers.dense(intermediateRepresentation, d, activation = None)
self.prediction.append(p)
predictionInputs.append(tf.one_hot(self.targetPlaceholder[j], d))
self.hard.append(tf.cast(tf.argmax(p,dimension = 1),tf.int32))
self.soft.append(tf.nn.log_softmax(p))
self.loss.append(tf.nn.sparse_softmax_cross_entropy_with_logits(labels = self.targetPlaceholder[j],
logits = p))
elif t == float:
mixtureParameters = mixtureDensityLayer(d,intermediateRepresentation,
epsilon = 0.01,
bounds = (0,MAXIMUMCOORDINATE))
self.prediction.append(mixtureParameters)
predictionInputs.append(tf.reshape(self.targetPlaceholder[j], [-1,1]))
self.loss.append(-mixtureDensityLogLikelihood(mixtureParameters,
self.targetPlaceholder[j]))
self.soft += [None]
self.hard += [None]
self.loss = sum(self.loss)
def accuracyVector(self):
'''For each example in the batch, do hard predictions match the target? ty = [None,bool]'''
hard = [tf.equal(h,t) for h,t in zip(self.hard,self.targetPlaceholder)
if h != None ]
if hard != []:
return reduce(tf.logical_and, hard)
else:
return True
def placeholders(self): return self.targetPlaceholder
@property
def token(self): return self.__class__.token
def beamTrace(self, session, feed, beamSize):
originalFeed = feed
# makes a copy of the feed
feed = dict([(k,feed[k]) for k in feed])
# traces is a list of tuples of (log likelihood, sequence of predictions)
traces = [(0.0,[])]
for j in range(len(self.outputDimensions)):
for k in range(j):
feed[self.targetPlaceholder[k]] = np.array([ t[1][k] for t in traces ])
for p in originalFeed:
feed[p] = np.repeat(originalFeed[p], len(traces), axis = 0)
if self.outputDimensions[j][0] == int:
soft = session.run(self.soft[j], feed_dict = feed)
traces = [(s + coordinateScore, trace + [coordinateIndex])
for traceIndex,(s,trace) in enumerate(traces)
for coordinateIndex,coordinateScore in enumerate(soft[traceIndex]) ]
elif self.outputDimensions[j][0] == float:
[u,v,p] = session.run(list(self.prediction[j]), feed_dict = feed)
traces = [(s + coordinateScore, trace + [coordinate])
for traceIndex,(s,trace) in enumerate(traces)
for coordinate, coordinateScore in
beamMixture(u[traceIndex],v[traceIndex],p[traceIndex],
1,MAXIMUMCOORDINATE-1,CONTINUOUSROUNDING,
beamSize)]
traces = sorted(traces, key = lambda t: -t[0])[:beamSize]
return traces
def sampleTrace(self, session, feed):
originalFeed = feed
# makes a copy of the feed
feed = dict([(k,feed[k]) for k in feed])
# traces is a list of tuples of (log likelihood, sequence of predictions)
trace = []
for j in range(len(self.outputDimensions)):
for k in range(j):
feed[self.targetPlaceholder[k]] = np.array([ trace[k] ])
for p in originalFeed:
feed[p] = np.repeat(originalFeed[p], 1, axis = 0)
if self.outputDimensions[j][0] == int:
soft = session.run(self.soft[j], feed_dict = feed)
trace.append(sampleLogMultinomial(soft[0]))
elif self.outputDimensions[j][0] == float:
[u,v,p] = session.run(list(self.prediction[j]), feed_dict = feed)
trace.append(sampleMixture(u[0],v[0],p[0]))
return trace
def attentionSequence(self, session, feed, l):
# what is the sequence of attention transformations when decoding line l?
ts = self.__class__.extractTargets(l)
# makes a copy of the feed
feed = dict([(k,feed[k]) for k in feed])
for t,p in zip(ts,self.targetPlaceholder): feed[p] = np.array([t])
return session.run(self.attentionTransforms,
feed_dict = feed)
class CircleDecoder(StandardPrimitiveDecoder):
token = CIRCLE
languagePrimitive = Circle
def __init__(self, imageRepresentation, continuous, attention):
if attention > 0:
self.attentionIndices = [1,2]
self.attentionSize = attention
if continuous:
self.outputDimensions = [(float,MAXIMUMCOORDINATE)]*3 # x,y,r
self.hiddenSizes = [None,None,None]
else:
self.outputDimensions = [(int,MAXIMUMCOORDINATE)]*3 # x,y,r
self.hiddenSizes = [None, None, None]
if NIPSPRIMITIVES(): # fixed radius: radius is the last thing so remove that
if attention > 0:
self.attentionIndices = self.attentionIndices[:-1]
self.outputDimensions = self.outputDimensions[:-1]
self.hiddenSizes = self.hiddenSizes[:-1]
self.makeNetwork(imageRepresentation)
def beam(self, session, feed, beamSize):
if NIPSPRIMITIVES():
r = 1
return [(s, Circle(AbsolutePoint(x,y),r))
for s,[x,y] in self.beamTrace(session, feed, beamSize)
if x - r > 0 and y - r > 0 and x + r < MAXIMUMCOORDINATE and y + r < MAXIMUMCOORDINATE]
else:
return [(s, Circle(AbsolutePoint(x,y),r))
for s,[x,y,r] in self.beamTrace(session, feed, beamSize)
if x - r > 0 and y - r > 0 and x + r < MAXIMUMCOORDINATE and y + r < MAXIMUMCOORDINATE]
def sample(self, session, feed):
if NIPSPRIMITIVES():
r = 1
[x,y] = self.sampleTrace(session, feed)
return Circle(AbsolutePoint(x,y),r)
else: assert False
@staticmethod
def extractTargets(l):
if l != None and isinstance(l,Circle):
return [l.center.x,
l.center.y] + ([] if NIPSPRIMITIVES() else [l.radius])
return [0,0] + ([] if NIPSPRIMITIVES() else [0])
class LabelDecoder(StandardPrimitiveDecoder):
token = LABEL
languagePrimitive = Label
def __init__(self, imageRepresentation, continuous, attention):
if attention > 0:
self.attentionIndices = [1,2]
self.attentionSize = attention
if continuous:
self.outputDimensions = [(float,MAXIMUMCOORDINATE)]*2+[(int,len(Label.allowedLabels))] # x,y,c
self.hiddenSizes = [None, None, None]
else:
self.outputDimensions = [(int,MAXIMUMCOORDINATE)]*2+[(int,len(Label.allowedLabels))] # x,y,c
self.hiddenSizes = [None, None, None]
self.makeNetwork(imageRepresentation)
def beam(self, session, feed, beamSize):
return [(s, Label(AbsolutePoint(x,y),Label.allowedLabels[l]))
for s,[x,y,l] in self.beamTrace(session, feed, beamSize)
if x > 0 and y > 0 and x < MAXIMUMCOORDINATE and y < MAXIMUMCOORDINATE ]
@staticmethod
def extractTargets(l):
if l != None and isinstance(l,Label):
return [l.p.x,
l.p.y,
Label.allowedLabels.index(l.c)]
return [0,0,0]
class RectangleDecoder(StandardPrimitiveDecoder):
token = RECTANGLE
languagePrimitive = Rectangle
def __init__(self, imageRepresentation, continuous, attention):
if attention > 0:
self.attentionIndices = [1,2,3]
self.attentionSize = attention
if continuous:
self.outputDimensions = [(float,MAXIMUMCOORDINATE)]*4 # x,y
self.hiddenSizes = [None]*4
else:
self.outputDimensions = [(int,MAXIMUMCOORDINATE)]*4 # x,y
self.hiddenSizes = [None]*4
self.makeNetwork(imageRepresentation)
def beam(self, session, feed, beamSize):
return [(s, Rectangle.absolute(x1,y1,x2,y2))
for s,[x1,y1,x2,y2] in self.beamTrace(session, feed, beamSize)
if x1 < x2 and y1 < y2 and x1 > 0 and x2 > 0 and y1 > 0 and y2 > 0 ]
def sample(self, session, feed):
[x1,y1,x2,y2] = self.sampleTrace(session, feed)
return Rectangle.absolute(x1,y1,x2,y2)
@staticmethod
def extractTargets(l):
if l != None and isinstance(l,Rectangle):
return [l.p1.x,
l.p1.y,
l.p2.x,
l.p2.y]
return [0]*4
class LineDecoder(StandardPrimitiveDecoder):
token = LINE
languagePrimitive = Line
def __init__(self, imageRepresentation, continuous, attention):
if attention > 0:
self.attentionIndices = [1,2,3,4,5]
self.attentionSize = attention
if continuous:
self.outputDimensions = [(float,MAXIMUMCOORDINATE)]*4 + [(int,2)]*2 # x,y for beginning and end; arrow/-
else:
self.outputDimensions = [(int,MAXIMUMCOORDINATE)]*4 + [(int,2)]*2 # x,y for beginning and end; arrow/-
self.hiddenSizes = [None,
32,
32,
32,
None,
None]
self.makeNetwork(imageRepresentation)
def beam(self, session, feed, beamSize):
return [(s, Line.absolute(x1,y1,x2,y2,arrow = arrow == 1,solid = solid == 1))
for s,[x1,y1,x2,y2,arrow,solid] in self.beamTrace(session, feed, beamSize)
if (x1 - x2)*(x1 - x2) + (y1 - y2)*(y1 - y2) > 0 and x1 > 0 and y1 > 0 and x2 > 0 and y2 > 0 ]
def sample(self, session, feed):
[x1,y1,x2,y2,arrow,solid] = self.sampleTrace(session, feed)
return Line.absolute(x1,y1,x2,y2,arrow = arrow == 1,solid = solid == 1)
@staticmethod
def extractTargets(l):
if l != None and isinstance(l,Line):
return [l.points[0].x,l.points[0].y,l.points[1].x,l.points[1].y,
int(l.arrow),
int(l.solid)]
return [0]*6
class StopDecoder():
def __init__(self, imageRepresentation, continuous, attention):
self.outputDimensions = []
self.loss = 0.0
token = STOP
languagePrimitive = None
def placeholders(self): return []
def softPredictions(self): return []
@staticmethod
def extractTargets(_): return []
class PrimitiveDecoder():
# It shouldn't matter in what order these are listed. If it does then I will consider that a bug.
decoderClasses = [CircleDecoder, RectangleDecoder, LineDecoder, StopDecoder] if NIPSPRIMITIVES() else [CircleDecoder, RectangleDecoder, LineDecoder, LabelDecoder, StopDecoder]
def __init__(self, imageRepresentation, trainingPredicatePlaceholder, continuous, attention):
self.decoders = [k(imageRepresentation,continuous,attention) for k in PrimitiveDecoder.decoderClasses]
self.imageRepresentation = imageRepresentation
self.prediction = tf.layers.dense(flattenImageOutput(self.imageRepresentation), len(self.decoders))
self.hard = tf.cast(tf.argmax(self.prediction,dimension = 1),tf.int32)
self.soft = tf.nn.log_softmax(self.prediction)
self.targetPlaceholder = tf.placeholder(tf.int32, [None])
self.trainingPredicatePlaceholder = trainingPredicatePlaceholder
def loss(self):
# the first label is for the primitive category
ll = tf.reduce_sum(tf.nn.sparse_softmax_cross_entropy_with_logits(labels = self.targetPlaceholder,
logits = self.prediction))
for decoder in self.decoders:
decoderMask = tf.cast(tf.equal(self.targetPlaceholder, decoder.token), tf.float32)
decoderLoss = tf.reduce_sum(tf.multiply(decoderMask,decoder.loss))
ll += decoderLoss
return ll
def accuracy(self):
a = tf.equal(self.hard,self.targetPlaceholder)
for decoder in self.decoders:
if decoder.token != STOP:
vector = decoder.accuracyVector()
if vector != True:
a = tf.logical_and(a,
tf.logical_or(vector, tf.not_equal(self.hard,decoder.token)))
return tf.reduce_mean(tf.cast(a, tf.float32))
def placeholders(self):
p = [self.targetPlaceholder]
for d in self.decoders: p += d.placeholders()
return p
@staticmethod
def extractTargets(l):
'''Given a line of code l, what is the array of targets (int's for categorical and float's for continuous) we expect the decoder to produce?'''
t = [STOP]
for d in PrimitiveDecoder.decoderClasses:
if l != None and isinstance(l,d.languagePrimitive):
t = [d.token]
break
for d in PrimitiveDecoder.decoderClasses:
t += d.extractTargets(l)
return t
def beam(self, session, feed, beamSize, maximumLength = None):
assert maximumLength == None
feed[self.trainingPredicatePlaceholder] = False
# to accelerate beam decoding, we can cash the image representation
[tokenScores,imageRepresentation] = session.run([self.soft,self.imageRepresentation], feed_dict = feed)
tokenScores = tokenScores[0]
# print "token scores ",
# for s in tokenScores: print s," "
# print "\nToken rectangle score: %f"%tokenScores[RectangleDecoder.token]
feed[self.imageRepresentation] = imageRepresentation
b = [(tokenScores[STOP], None)] # STOP
for d in self.decoders:
if d.token == STOP: continue
b += [ (s + tokenScores[d.token], program)
for (s, program) in d.beam(session, feed, beamSize) ]
# for s,p in b:
# print s,p
# assert False
return b
def sample(self, session, feed, maximumLength = None):
assert maximumLength == None
feed[self.trainingPredicatePlaceholder] = False
[tokenScores,imageRepresentation] = session.run([self.soft,self.imageRepresentation], feed_dict = feed)
tokenScores = tokenScores[0]
feed[self.imageRepresentation] = imageRepresentation
whichCommand = sampleLogMultinomial(tokenScores)
for d in self.decoders:
if d.token == whichCommand:
if d.token == STOP: return None
return d.sample(session, feed)
assert False
def attentionSequence(self, session, feed, l):
imageRepresentation = session.run(self.imageRepresentation, feed_dict = feed)
feed[self.imageRepresentation] = imageRepresentation
for d in self.decoders:
if isinstance(l,d.__class__.languagePrimitive):
if d.attentionTransforms == []: return []
return d.attentionSequence(session, feed, l)
class RecurrentDecoder():
def __init__(self, imageFeatures, trainingPredicatePlaceholder, continuous, attention):
assert not continuous
assert not attention
assert NIPSPRIMITIVES()
RECURRENTDICTIONARYSIZE = 16
MAXIMUMPRIMITIVES = 36
MAXIMUMRECURRENT = 1 + MAXIMUMPRIMITIVES*(7) # + 1stop symbol, MAXIMUMPRIMITIVES instructions, 6+1 arguments for a line
self.trainingPredicatePlaceholder = trainingPredicatePlaceholder
self.outputPlaceholder = tf.placeholder(tf.int32, shape = [None,MAXIMUMRECURRENT],
name = 'recurrentOutputPlaceholder')
self.imageRepresentation = flattenImageOutput(imageFeatures)
self.unit = RecurrentNetwork(arguments.LSTM,
RECURRENTDICTIONARYSIZE,
MAXIMUMRECURRENT,
self.imageRepresentation,
alwaysProvideInput = True)
@staticmethod
def targetsOfProgram(s):
t = []
for l in s.lines:
for j,k in enumerate(PrimitiveDecoder.decoderClasses):
if isinstance(l,k.languagePrimitive):
t.append(j)
t += k.extractTargets(l)
break
# append the stop symbol
t += [PrimitiveDecoder.decoderClasses.index(StopDecoder)]
return t
def accuracy(self):
return self.unit.decodesIntoAccuracy(self.outputPlaceholder)
def loss(self):
return self.unit.decodesIntoLoss(self.outputPlaceholder)
def beam(self, session, feed, k, maximumLength = None):
feed = {self.imageRepresentation: session.run(self.imageRepresentation, feed)[0]}
primitiveArguments = [[MAXIMUMCOORDINATE,MAXIMUMCOORDINATE], # circle
[MAXIMUMCOORDINATE]*4, # rectangle
[MAXIMUMCOORDINATE]*4 + [2,2], # line
[]] # stop
builders = [lambda x,y: Circle(AbsolutePoint(x,y),1),
lambda a,b,p,q: Rectangle.absolute(a,b,p,q),
lambda a,b,p,q,arrow, solid: Line.absolute(a,b,p,q,arrow = arrow == 1,solid = solid == 1)]
def Checker(sequence):
#print "checking sequence:",sequence
j = 0
while j < len(sequence):
if sequence[j] >= len(primitiveArguments):
#print "Invalid"
return RecurrentNetwork.INVALIDSEQUENCE
k = PrimitiveDecoder.decoderClasses[sequence[j]]
if k == StopDecoder:
#print "Finished"
assert j == len(sequence) - 1
return RecurrentNetwork.FINISHEDSEQUENCE
j += 1
for upperBound in primitiveArguments[sequence[j - 1]]:
if j == len(sequence):
#print "valid and in the middle of parsing the primitive"
return RecurrentNetwork.VALIDSEQUENCE
if sequence[j] < upperBound: j += 1
else:
#print "invalid because out of range"
return RecurrentNetwork.INVALIDSEQUENCE
#print "valid because expecting next primitive"
return RecurrentNetwork.VALIDSEQUENCE
def decodeSequence(sequence):
lines = []
j = 0
while j < len(sequence):
primitiveIndex = sequence[j]
k = PrimitiveDecoder.decoderClasses[primitiveIndex]
if k == StopDecoder:
assert j == len(sequence) - 1
return Sequence(lines)
j += 1
arguments = []
for upperBound in primitiveArguments[primitiveIndex]:
assert j < len(sequence)
assert sequence[j] < upperBound
arguments.append(sequence[j])
j += 1
lines.append(builders[primitiveIndex](*arguments))
assert False
return [ (s,decodeSequence(q)) for s,q in self.unit.beam(session,
k,
sequenceChecker = Checker,
baseFeed = feed,
maximumLength = maximumLength) ]
class RecognitionModel():
def __init__(self, arguments):
self.noisy = arguments.noisy
self.arguments = arguments
self.graph = tf.Graph()
self.session = tf.Session(graph = self.graph)
with self.session.graph.as_default():
# current and goal images
if not self.arguments.LSTM:
self.currentPlaceholder = tf.placeholder(tf.float32, [None, 256, 256])
self.goalPlaceholder = tf.placeholder(tf.float32, [None, 256, 256])
self.trainingPredicatePlaceholder = tf.placeholder(tf.bool)
if self.arguments.LSTM:
imageInput = tf.stack([self.goalPlaceholder], axis = 3)
else:
imageInput = tf.stack([self.currentPlaceholder,self.goalPlaceholder], axis = 3)
c1 = architectures[self.arguments.architecture].makeModel(imageInput)
decoderClass = RecurrentDecoder if self.arguments.LSTM else PrimitiveDecoder
self.decoder = decoderClass(c1, self.trainingPredicatePlaceholder,
arguments.continuous,
arguments.attention)
self.loss = self.decoder.loss()
self.averageAccuracy = self.decoder.accuracy()
self.optimizer = tf.train.AdamOptimizer(learning_rate=self.arguments.learningRate).minimize(self.loss)
@property
def checkpointPath(self):
return "checkpoints/recognition_%s_%s_%s%s%s.checkpoint"%(self.arguments.architecture,
"noisy" if self.arguments.noisy else "clean",
"continuous" if self.arguments.continuous else "discrete",
("_attention%d"%self.arguments.attention) if self.arguments.attention > 0 else '',
("_recurrent%d"%self.arguments.LSTM if self.arguments.LSTM else ''))
def loadCheckpoint(self):
path = self.checkpointPath
print "Loading recognition model checkpoint:",path
with self.session.graph.as_default():
saver = tf.train.Saver()
saver.restore(self.session, path)
def train(self, numberOfExamples, restore = False):
noisyTarget,programs = loadExamples(numberOfExamples, self.arguments.trainingData)
iterator = BatchIterator(10,(np.array(noisyTarget),np.array(programs)),
testingFraction = TESTINGFRACTION, stringProcessor = loadImage)
flushEverything()
with self.session.graph.as_default():
initializer = tf.global_variables_initializer()
saver = tf.train.Saver()
if not restore:
self.session.run(initializer)
else:
saver.restore(self.session, self.checkpointPath)
for e in range(100):
epicLoss = []
epicAccuracy = []
for ts,ps in iterator.epochExamples():
feed = self.makeTrainingFeed(ts,ps)
feed[self.trainingPredicatePlaceholder] = True
_,l,accuracy = self.session.run([self.optimizer, self.loss, self.averageAccuracy],
feed_dict = feed)
if len(epicAccuracy)%1000 == 0:
print "\t",len(epicAccuracy),l,accuracy
epicLoss.append(l)
epicAccuracy.append(accuracy)
print "Epoch %d: accuracy = %f, loss = %f"%((e+1),sum(epicAccuracy)/len(epicAccuracy),sum(epicLoss)/len(epicLoss))
testingAccuracy = []
for ts,ps in iterator.testingExamples():
feed = self.makeTrainingFeed(ts,ps)
feed[self.trainingPredicatePlaceholder] = False
testingAccuracy.append(self.session.run(self.averageAccuracy, feed_dict = feed))
print "\tTesting accuracy = %f"%(sum(testingAccuracy)/len(testingAccuracy))
print "Saving checkpoint: %s" % saver.save(self.session, self.checkpointPath)
flushEverything()
def makeTrainingFeed(self, targets, programs):
# goal, current, predictions
gs = []
cs = []
ps = []
for target, program in zip(targets, programs):
if not self.arguments.noisy:
target = program.draw()
if self.arguments.randomizeOrder:
program = Sequence(randomlyPermuteList(program.lines))
if self.arguments.LSTM:
gs.append(target)
ps.append(self.decoder.__class__.targetsOfProgram(program))
else:
cs += program.drawTrace()
for j in range(len(program) + 1):
gs.append(target)
l = None
if j < len(program): l = program.lines[j]
ps.append(self.decoder.extractTargets(l))
gs = np.array(gs)
if self.arguments.noisy: gs = augmentData(gs)
if self.arguments.LSTM:
feed = self.decoder.unit.decodingTrainingFeed(ps, self.decoder.outputPlaceholder)
feed.update({self.goalPlaceholder: gs})
return feed
cs = np.array(cs)
ps = np.array(ps)
if False:
for j in range(10):
print ps[j,:]
showImage(np.concatenate([gs[j],cs[j]]))
f = {self.goalPlaceholder: gs,
self.currentPlaceholder: cs}
for j,p in enumerate(self.decoder.placeholders()):
f[p] = ps[:,j] #np.array([ ps[i][j] for i in range(len(ps)) ])
return f
def beam(self, current, goal, beamSize, maximumLength = None):
if self.arguments.LSTM:
feed = {self.goalPlaceholder: np.array([goal])}
else:
feed = {self.currentPlaceholder: np.array([current]),
self.goalPlaceholder: np.array([goal])}
return sorted(self.decoder.beam(self.session, feed, beamSize, maximumLength = maximumLength),
reverse = True)
def sample(self, current, goal):
assert not self.arguments.LSTM
feed = {self.currentPlaceholder: np.array([current]),
self.goalPlaceholder: np.array([goal])}
return self.decoder.sample(self.session, feed, maximumLength = None)
def attentionSequence(self, current, goal, l):
feed = {self.currentPlaceholder: np.array([current]),
self.goalPlaceholder: np.array([goal])}
return self.decoder.attentionSequence(self.session, feed, l)
def analyzeFailures(self, numberOfExamples):
failures = []
noisyTarget,programs = loadExamples(numberOfExamples, self.arguments.trainingData)
iterator = BatchIterator(1,(np.array(noisyTarget),np.array(programs)),
testingFraction = TESTINGFRACTION, stringProcessor = loadImage)
with self.session.graph.as_default():
saver = tf.train.Saver()
saver.restore(self.session, self.checkpointPath)
totalNumberOfAttempts = 0
for ts,ps in iterator.testingExamples():
if len(failures) > 100: break
targetProgram = ps[0]
feed = self.makeTrainingFeed(ts,ps)
# break the feed up into single actions
for j in range(len(targetProgram)):
if len(failures) > 100: break
singleFeed = dict([(placeholder, np.array([feed[placeholder][j,...]]))
for placeholder in feed ])
current, goal = singleFeed[self.currentPlaceholder][0], singleFeed[self.goalPlaceholder][0]
target = targetProgram.lines[j]
if self.arguments.continuous: target = target.round(CONTINUOUSROUNDING)
singleFeed[self.trainingPredicatePlaceholder] = False
predictions = self.beam(current, goal, 100)
totalNumberOfAttempts += 1
if predictions[0][1] != target:
failures.append({'current': current, 'goal': goal,
'target': target,
'predictions': predictions})
print "(failure)"
print "\tExpected:",target
print "\tActually:",predictions[0][1]
else:
print "(success)"
if self.arguments.attention > 0:
attention = self.attentionSequence(current, goal, target)
if attention != []:
print attention
print target
illustration = drawAttentionSequence(goal, attention, target)
saveMatrixAsImage(illustration, 'attentionIllustrations/%d.png'%(totalNumberOfAttempts - len(failures)))
# report failures
print "%d/%d (%f%%) failure rate"%(len(failures),totalNumberOfAttempts,
100*float(len(failures))/totalNumberOfAttempts)
# compute the average rank of the failure
ranks = [ None if not f['target'] in map(snd,f['predictions']) else map(snd,f['predictions']).index(f['target']) + 1
for f in failures ]
print ranks
print "In the frontier %d/%d"%(len([r for r in ranks if r != None ]),len(ranks))
ranks = [r for r in ranks if r != None ]
print ranks
if len(ranks) > 0:
print "Average rank: %f"%(sum(ranks)/float(len(ranks)))
# How many failures were of each type
print "Circle failures: %d"%(len([ None for f in failures
if isinstance(f['target'],Circle)]))
print "Line failures: %d"%(len([ None for f in failures
if isinstance(f['target'],Line)]))
print "Rectangle failures: %d"%(len([ None for f in failures
if isinstance(f['target'],Rectangle)]))
print "Label failures: %d"%(len([ None for f in failures
if isinstance(f['target'],Label)]))
print "Stop failures: %d"%(len([ None for f in failures
if None == f['target']]))
for j,failure in enumerate(failures):
saveMatrixAsImage(255*failure['current'], 'failures/%d-current.png'%j)
saveMatrixAsImage(255*failure['goal'], 'failures/%d-goal.png'%j)
p = failure['predictions'][0][1]
if p == None: p = []
else: p = [p]
p = Sequence(p).draw()
saveMatrixAsImage(255*(p + failure['current']), 'failures/%d-predicted.png'%j)
# Particle in sequential Monte Carlo
class Particle():
def __init__(self, program = None,
time = 0.0,
parent = None,
output = None,
distance = None,
count = None,
logLikelihood = None,
score = None):
self.time = time
self.score = score
self.count = count
self.program = program
self.parent = parent
self.output = output
self.distance = distance
self.logLikelihood = logLikelihood
# once a program is finished we wrap it up in a sedquence object
def finished(self): return isinstance(self.program, Sequence)
# wraps it up in a sequence object if it hasn't already
def sequence(self):
if self.finished(): return self.program
return Sequence(self.program)
def render(self):
if self.output is None:
self.output = self.sequence().draw()
return self.output
class DistanceModel():
def __init__(self,arguments):
self.arguments = arguments
if self.arguments.continuous:
setSnapToGrid(False)
self.graph = tf.Graph()
self.session = tf.Session(graph = self.graph)
with self.session.graph.as_default():
# current and goal images
self.currentPlaceholder = tf.placeholder(tf.float32, [None, 256, 256])
self.goalPlaceholder = tf.placeholder(tf.float32, [None, 256, 256])
imageInput = tf.stack([self.currentPlaceholder,self.goalPlaceholder], axis = 3)
c1 = architectures[self.arguments.architecture].makeModel(imageInput)
c1d = int(c1.shape[1]*c1.shape[2]*c1.shape[3])
f1 = tf.reshape(c1, [-1, c1d])
# Value function learning
self.valueTargets = tf.placeholder(tf.float32, [None,2]) # (extra target, extra current)
# this line of code collapses all of the filters into batchSize*numberOfFilters
#f2 = tf.reduce_sum(c1, [1,2])
f2 = f1
self.distanceFunction = tf.layers.dense(f2, 2, activation = tf.nn.relu)
self.distanceLoss = tf.reduce_mean(tf.squared_difference(self.valueTargets, self.distanceFunction))
self.distanceOptimizer = tf.train.AdamOptimizer(learning_rate=self.arguments.learningRate).minimize(self.distanceLoss)
@property
def checkpointPath(self):
return "checkpoints/distance_%s_%s.checkpoint"%(self.arguments.architecture,
"noisy" if self.arguments.noisy else "clean")
def learnedDistances(self, currentBatch, goalBatch):
return self.session.run(self.distanceFunction,
feed_dict = {self.currentPlaceholder: currentBatch,
self.goalPlaceholder: goalBatch})
def learnedParticleDistances(self, goal, particles):
if particles == []: return
# only do it for 50 particles at a time
maximumBatchSize = 50
if len(particles) > maximumBatchSize:
self.learnedParticleDistances(goal, particles[maximumBatchSize:])
particles = particles[:maximumBatchSize]
d = self.learnedDistances(np.array([ p.render() for p in particles ]),
np.tile(goal, (len(particles), 1, 1)))
for j,p in enumerate(particles):
if self.arguments.showParticles:
print "Distance vector:",d[j,:]
print "Likelihood:",p.logLikelihood
showImage(p.output + goal)
p.distance = (d[j,0], d[j,1])
def loadCheckpoint(self):
print "Loading distance checkpoint from",self.checkpointPath
with self.session.graph.as_default():
saver = tf.train.Saver()
saver.restore(self.session, self.checkpointPath)
def train(self, numberOfExamples, restore = False):
assert self.arguments.noisy
targetImages,targetPrograms = loadExamples(numberOfExamples, self.arguments.trainingData)
iterator = BatchIterator(5,tuple([np.array(targetImages),np.array(targetPrograms)]),
testingFraction = TESTINGFRACTION, stringProcessor = loadImage)
# use the session to make sure that we save or initialize the right things
with self.session.graph.as_default():
initializer = tf.global_variables_initializer()
saver = tf.train.Saver()
flushEverything()
if not restore:
self.session.run(initializer)
else:
saver.restore(self.session, self.checkpointPath)
for e in range(20):
runningAverage = 0.0
runningAverageCount = 0
lastUpdateTime = time()
for images,programs in iterator.epochExamples():
targets, current, distances = makeDistanceExamples(images, programs,
continuous = self.arguments.continuous,
reportTime = runningAverageCount == 0)
_,l = self.session.run([self.distanceOptimizer, self.distanceLoss],
feed_dict = {self.currentPlaceholder: current,
self.goalPlaceholder: targets,
self.valueTargets: distances})
runningAverage += l
runningAverageCount += 1
if time() - lastUpdateTime > 120:
lastUpdateTime = time()
print "\t\tRunning average loss: %f"%(runningAverage/runningAverageCount)
flushEverything()
print "Epoch %d: loss = %f"%(e,runningAverage/runningAverageCount)
flushEverything()
testingLosses = [ self.session.run(self.distanceLoss,
feed_dict = {self.currentPlaceholder: current,
self.goalPlaceholder: targets,
self.valueTargets: distances})
for images,programs in iterator.testingExamples()
for [targets, current, distances] in [makeDistanceExamples(images, programs)] ]
testingLosses = sum(testingLosses)/len(testingLosses)
print "\tTesting loss: %f"%testingLosses
print "Saving checkpoint: %s"%(saver.save(self.session, self.checkpointPath))
flushEverything()
def analyzeGroundTruth(self):
self.loadCheckpoint()
targetNames = [ "drawings/expert-%d.png"%j for j in range(100) ]
targetImages = map(loadImage,targetNames)
targetSequences = map(getGroundTruthParse,targetNames)
for j in range(100):
s = targetSequences[j]
for m in range(3):
sp = s
if m > 0:
for _ in range(choice([1,2,3,4])): sp = sp.mutate()
d = self.learnedDistances(np.array([sp.draw()]),
np.array([targetImages[j]]))[0]
d1 = len(set(map(str,s.lines)) - set(map(str,sp.lines)))
d2 = len(set(map(str,sp.lines)) - set(map(str,s.lines)))
print "%f\t%f"%(d[0],d[1])
if int(round(d[0])) != d1 or int(round(d[1])) != d2:
print "\tvs:%d\t%d"%(d1,d2)
showImage(targetImages[j] + sp.draw())
class SearchModel():
def __init__(self,arguments):
self.arguments = arguments
self.recognizer = RecognitionModel(arguments)
self.distance = DistanceModel(arguments)
# load the networks
if not self.arguments.unguided:
self.recognizer.loadCheckpoint()
if self.arguments.distance:
assert self.arguments.noisy
self.distance.loadCheckpoint()
def sample(self, targetImage, maximumLength):
currentImage = np.zeros(targetImage.shape)
currentProgram = []
for j in range(maximumLength):
nextCommand = self.recognizer.sample(currentImage, targetImage)
if nextCommand == None or j == maximumLength - 1: return Sequence(currentProgram)
currentProgram.append(nextCommand)
currentImage = Sequence(currentProgram).draw()
def SMC(self, targetImage, beamSize = 10, beamLength = 10):
assert not self.arguments.LSTM
totalNumberOfRenders = 0
targetImage = np.reshape(targetImage,(256,256))
beam = [Particle(program = [],
output = np.zeros(targetImage.shape),
logLikelihood = 0.0,
count = beamSize,
time = 0.0,
distance = 999999999)]
finishedPrograms = []
searchStartTime = time()
for iteration in range(beamLength if beamLength > 0 else 50):
lastIteration = iteration == beamLength - 1 # are we the last iteration
children = []
startTime = time()
for parent in beam:
childCount = beamSize if self.arguments.beam else parent.count
if not self.arguments.unguided:
# neural network guide: decoding
kids = self.recognizer.beam(parent.output, targetImage, childCount)
else:
# no neural network guide: sample from the prior
kids = [ (0.0, randomCode) for _ in range(childCount)
for randomCode in [randomLineOfCode()] if randomCode != None ]
kids += [(0.0, None)]
# remove children that duplicate an existing line of code
existingLinesOfCode = map(str,parent.program)
kids = [ child for child in kids
if not (str(child[1]) in existingLinesOfCode) ]
kids.sort(key = lambda k: k[0], reverse = True)
# in evaluation mode we want to make sure that there are at least some finished programs