forked from art-programmer/FloorNet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrain.py
executable file
·1570 lines (1309 loc) · 84 KB
/
train.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 multiprocessing as mp
import sys
import tensorflow as tf
import numpy as np
import cv2
import tflearn
import random
import math
import os
import time
import zlib
import socket
import traceback
try:
import Queue
except Exception:
import queue as Queue
import sys
#import tf_nndistance
try:
import cPickle as pickle
except:
import pickle
import argparse
from RecordReader import *
from utils import *
#import matplotlib.pyplot as plt
if 'xrange' not in globals():
xrange = range
pass
import tensorflow.contrib.slim as slim
from tensorflow import nn
from tensorflow.python.client import timeline
#from evaluate import *
bn_func = tflearn.layers.normalization.batch_normalization
DATASETS = ['syn', 'real', 'scannet', "matterport", "SUNCG"]
HEATMAP_SCALE = 3
def mergeFeatures(features):
if True:
return tf.add_n(features)
else:
return tf.concat(features, axis=-1)
pass
def dumpOutputs(corners, semantics=None):
corners = sigmoid(corners)
corners = np.transpose(corners, [0, 3, 1, 2])
#print(corners.shape)
np.save('output/corners.npy', corners)
return
def build_graph_pointnet(options, input_dict):
nChannels = [7, 64, 64, 64, 128, 1024]
sizes = [HEIGHT, HEIGHT // 2, HEIGHT // 4, HEIGHT // 8, HEIGHT // 16, HEIGHT // 32]
with tf.device('/gpu:%s'%options.gpu_id[0]):
tflearn.config.init_training_mode()
#tflearn.init_graph(seed=1029,num_cores=2,gpu_memory_fraction=1.0,soft_placement=True)
#tf.set_random_seed(1029)
pointcloud_inp = input_dict['points']
pointcloud_indices_inp = input_dict['point_indices']
pointcloud_indices_inp += tf.expand_dims(tf.range(options.batchSize) * sizes[0] * sizes[0], -1)
# batchIndexOffsets = []
# for c in xrange(6):
# batchIndexOffsets.append(tf.range(options.batchSize) * sizes[c] * sizes[c])
# continue
# batchIndexOffsets = tf.expand_dims(tf.stack(batchIndexOffsets, axis=1), -1)
# indices_maps = tf.unstack(pointcloud_indices_inp + batchIndexOffsets, axis=1)
x0 = tf.expand_dims(pointcloud_inp, -1)
x1 = slim.conv2d(x0, nChannels[1], (1, nChannels[0]), stride=1, activation_fn=nn.relu, padding='valid', normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5))
x2 = slim.conv2d(x1, nChannels[2], (1, 1), stride=1, activation_fn=nn.relu, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5))
x3 = slim.conv2d(x2, nChannels[3], (1, 1), stride=1, activation_fn=nn.relu, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5))
x4 = slim.conv2d(x3, nChannels[4], (1, 1), stride=1, activation_fn=nn.relu, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5))
x5 = slim.conv2d(x4, nChannels[5], (1, 1), stride=1, activation_fn=nn.relu, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5))
x_fc_topdown = tflearn.layers.max_pool_2d(x5, (options.numPoints, 1), strides=1, padding='valid')
x_fc = x_fc_topdown
# x_fc = tf.reshape(x_fc, (options.batchSize, -1))
# x_fc = slim.fully_connected(x_fc, 256, activation_fn=nn.relu, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5))
# x_fc = slim.fully_connected(x_fc, nChannels[5], activation_fn=nn.relu, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5))
# x_fc = tf.reshape(x_fc, (options.batchSize, 1, 1, -1))
x_fc_up = tf.tile(x_fc, (1, options.numPoints, 1, 1))
x_fc_up = tf.concat([x_fc_up, x3], axis=-1)
x5_up = slim.conv2d(x_fc_up, 512, (1, 1), stride=1, activation_fn=nn.relu, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5))
x4_up = slim.conv2d(x5_up, 256, (1, 1), stride=1, activation_fn=nn.relu, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5))
x3_up = slim.conv2d(x4_up, 128, (1, 1), stride=1, activation_fn=nn.relu, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5))
x2_up = slim.conv2d(x3_up, 128, (1, 1), stride=1, activation_fn=nn.relu, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5))
#x2_up = tf.unsorted_segment_sum(tf.reshape(x2_up, (-1, 128)), tf.reshape(pointcloud_indices_inp, (-1, )), num_segments=options.batchSize * sizes[0] * sizes[0]) / options.sumScale
x2_up = tf.maximum(tf.unsorted_segment_max(tf.reshape(x2_up, (-1, 128)), tf.reshape(pointcloud_indices_inp, (-1, )), num_segments=options.batchSize * sizes[0] * sizes[0], name="project"), 0)
x2_up = tf.reshape(x2_up, (options.batchSize, sizes[0], sizes[0], -1))
x1_up = x2_up
#x1_up = slim.conv2d(x2_up, nChannels[1], (3, 3), stride=1, activation_fn=nn.relu, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5))
#x0_topdown = tf.reshape(x0_topdown, (options.batchSize, sizes[0], sizes[0], -1))
if False:
pred_corner = slim.conv2d(x1_up, 64, [3, 3], stride=1, activation_fn=nn.relu, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5), scope='pred_corner')
pred_icon = slim.conv2d(x1_up, 64, [3, 3], stride=1, activation_fn=nn.relu, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5), scope='pred_icon')
pred_room = slim.conv2d(x1_up, 64, [3, 3], stride=1, activation_fn=nn.relu, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5), scope='pred_room')
pred_corner = slim.conv2d(pred_corner, NUM_CORNERS, (1, 1), stride=1, activation_fn=None, normalizer_fn=None, weights_regularizer=slim.l2_regularizer(1e-5))
pred_icon = slim.conv2d(pred_icon, NUM_ICONS, (1, 1), stride=1, activation_fn=None, normalizer_fn=None, weights_regularizer=slim.l2_regularizer(1e-5))
pred_room = slim.conv2d(pred_room, NUM_ROOMS, (1, 1), stride=1, activation_fn=None, normalizer_fn=None, weights_regularizer=slim.l2_regularizer(1e-5))
else:
pred_corner = slim.conv2d(x1_up, NUM_CORNERS, [3, 3], stride=1, activation_fn=None, normalizer_fn=None, weights_regularizer=slim.l2_regularizer(1e-5), scope='pred_corner')
pred_icon = slim.conv2d(x1_up, NUM_ICONS, [3, 3], stride=1, activation_fn=None, normalizer_fn=None, weights_regularizer=slim.l2_regularizer(1e-5), scope='pred_icon')
pred_room = slim.conv2d(x1_up, NUM_ROOMS, [3, 3], stride=1, activation_fn=None, normalizer_fn=None, weights_regularizer=slim.l2_regularizer(1e-5), scope='pred_room')
pass
pred_dict = {'corner': pred_corner, 'icon': pred_icon, 'room': pred_room}
x0_topdown = tf.unsorted_segment_sum(tf.reshape(x0, (-1, NUM_CHANNELS[0])), tf.reshape(pointcloud_indices_inp, (-1, )), num_segments=options.batchSize / len(options.gpu_id) * SIZES[0] * SIZES[0]) / options.sumScale
x0_topdown = tf.reshape(x0_topdown, (options.batchSize/len(options.gpu_id), SIZES[0], SIZES[0], -1))
debug_dict = {'x0_topdown': x0_topdown}
pass
return pred_dict, debug_dict
def build_graph_image(options, input_dict):
image_features_all = input_dict['image_features']
if len(options.gpu_id) > 1:
img_features = [tf.split(features, len(options.gpu_id), axis=0) for k, features in image_features_all.iteritems()]
else:
img_features = [[features for k, features in image_features_all.iteritems()]]
pass
#pointcloud_inp = tf.placeholder(tf.float32,shape=(options.batchSize, options.numPoints, options.numInputChannels),name='pointcloud_inp')
#pointcloud_indices_inp = tf.placeholder(tf.int32,shape=(options.batchSize, 6, options.numPoints),name='pointcloud_indices_inp')
pred_dicts = []
debug_dicts = []
reused = False
for i, img_feature in zip(options.gpu_id, img_features):
with tf.device('/gpu:%s'%int(i)), tf.variable_scope('floorplan_net', reuse=reused), slim.arg_scope([slim.model_variable, slim.variable], device='/cpu:0'):
x5_up = img_feature[4]
x4_up = slim.conv2d_transpose(x5_up, NUM_CHANNELS[4], [5, 5], stride=2, activation_fn=nn.relu, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5))
x4_up = mergeFeatures([x4_up, img_feature[3]])
x3_up = slim.conv2d_transpose(x4_up, NUM_CHANNELS[3], [5, 5], stride=2, activation_fn=nn.relu, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5))
#print(x3_up)
x3_up = mergeFeatures([x3_up, img_feature[2]])
x2_up = slim.conv2d_transpose(x3_up, NUM_CHANNELS[2], [5, 5], stride=2, activation_fn=nn.relu, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5))
x2_up = mergeFeatures([x2_up, img_feature[1]])
x1_up = slim.conv2d_transpose(x2_up, NUM_CHANNELS[1], [5, 5], stride=2, activation_fn=nn.relu, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5))
x1_up = mergeFeatures([x1_up, img_feature[0]])
if True:
pred_corner = slim.conv2d_transpose(x1_up, NUM_CHANNELS[1], [5, 5], stride=2, activation_fn=nn.relu, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5), scope='pred_corner')
pred_icon = slim.conv2d_transpose(x1_up, NUM_CHANNELS[1], [5, 5], stride=2, activation_fn=nn.relu, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5), scope='pred_icon')
pred_room = slim.conv2d_transpose(x1_up, NUM_CHANNELS[1], [5, 5], stride=2, activation_fn=nn.relu, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5), scope='pred_room')
pred_corner = slim.conv2d(pred_corner, NUM_CORNERS, (1, 1), stride=1, activation_fn=None, normalizer_fn=None, weights_regularizer=slim.l2_regularizer(1e-5))
pred_icon = slim.conv2d(pred_icon, NUM_ICONS, (1, 1), stride=1, activation_fn=None, normalizer_fn=None, weights_regularizer=slim.l2_regularizer(1e-5))
pred_room = slim.conv2d(pred_room, NUM_ROOMS, (1, 1), stride=1, activation_fn=None, normalizer_fn=None, weights_regularizer=slim.l2_regularizer(1e-5))
else:
pred_corner = slim.conv2d_transpose(x1_up, NUM_CORNERS, [5, 5], stride=2, activation_fn=None, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5), scope='pred_corner')
pred_icon = slim.conv2d_transpose(x1_up, NUM_ICONS, [5, 5], stride=2, activation_fn=None, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5), scope='pred_icon')
pred_room = slim.conv2d_transpose(x1_up, NUM_ROOMS, [5, 5], stride=2, activation_fn=None, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5), scope='pred_room')
pass
pred_dict = {'corner': pred_corner, 'icon': pred_icon, 'room': pred_room}
debug_dict = {'x0_topdown': tf.zeros((options.batchSize, HEIGHT, WIDTH, options.numInputChannels))}
pred_dicts.append(pred_dict)
debug_dicts.append(debug_dict)
pass
continue
pred_dict = pred_dicts[0]
for pred in pred_dicts[1:]:
for k,v in pred.items():
pred_dict[k] = tf.concat([pred_dict[k], v], axis=0)
debug_dict = debug_dicts[0]
for de in debug_dicts[1:]:
for k,v in de.items():
debug_dict[k] = tf.concat([debug_dict[k], v], axis=0)
return pred_dict, debug_dict
def build_graph(options, input_dict):
branches_options = set(options.branches)
simple_option = set(['0', '6', '7'])
if (simple_option | branches_options) == simple_option:
return build_graph_pointnet(options, input_dict)
if options.branches == '4':
return build_graph_image(options, input_dict)
pointcloud_inp_all = input_dict['points']
pointcloud_indices_inp_all = input_dict['point_indices']
if len(options.gpu_id) > 1:
pointcloud_inps = tf.split(pointcloud_inp_all, len(options.gpu_id), axis=0)
pointcloud_indices_inps = tf.split(pointcloud_indices_inp_all, len(options.gpu_id), axis=0)
else:
pointcloud_inps = [pointcloud_inp_all]
pointcloud_indices_inps = [pointcloud_indices_inp_all]
pass
#print(pointcloud_inps)
#print(pointcloud_inps[0])
if '4' in options.branches:
image_features_all = input_dict['image_features']
if len(options.gpu_id) > 1:
img_features = [tf.split(features, len(options.gpu_id), axis=0) for k, features in image_features_all.iteritems()]
else:
img_features = [[features for k, features in image_features_all.iteritems()]]
pass
else:
img_features = [None for _ in xrange(len(options.gpu_id))]
pass
#pointcloud_inp = tf.placeholder(tf.float32,shape=(options.batchSize, options.numPoints, options.numInputChannels),name='pointcloud_inp')
#pointcloud_indices_inp = tf.placeholder(tf.int32,shape=(options.batchSize, 6, options.numPoints),name='pointcloud_indices_inp')
pred_dicts = []
debug_dicts = []
reused = False
for i, pointcloud_inp, pointcloud_indices_inp, img_feature in zip(options.gpu_id, pointcloud_inps, pointcloud_indices_inps, img_features):
#for i in range(1):
with tf.device('/gpu:%s'%int(i)), tf.variable_scope('floorplan_net', reuse=reused), slim.arg_scope([slim.model_variable, slim.variable], device='/cpu:0'):
# if True:
# pointcloud_inp = input_dict['points']
# pointcloud_indices_inp = input_dict['point_indices']
# if '4' in options.branches:
# img_feature = input_dict['image_features']
# pass
# with tf.device('/gpu:0'):
reused=True
debug_dict = {}
tf.set_random_seed(1029)
#tflearn.init_graph(seed=1029,num_cores=2,gpu_memory_fraction=1.0,soft_placement=False, log_device=True)
if 'd' in options.augmentation:
#keep_prob = tf.random_uniform([1], minval=0.5, maxval=1.0)[0]
keep_prob = 0.5
pointcloud_inp = tf.nn.dropout(pointcloud_inp, keep_prob, noise_shape=[options.batchSize, NUM_POINTS, 1]) * keep_prob
pointcloud_indices_inp = tf.cast(tf.round(tf.nn.dropout(tf.cast(pointcloud_indices_inp, np.float32), keep_prob) * keep_prob), tf.int32)
pass
pointcloud_indices_inp = getCoarseIndicesMapsBatch(pointcloud_indices_inp, WIDTH, HEIGHT)
batchIndexOffsets = []
for c in xrange(6):
batchIndexOffsets.append((np.arange(options.batchSize/len(options.gpu_id), dtype=np.int32)) * SIZES[c] * SIZES[c])
continue
batchIndexOffsets = tf.expand_dims(tf.stack(batchIndexOffsets, axis=0), -1)
#print(pointcloud_indices_inp, batchIndexOffsets)
#exit(1)
indices_maps = pointcloud_indices_inp + batchIndexOffsets
x0 = tf.expand_dims(pointcloud_inp, -1)
x0_topdown = tf.unsorted_segment_sum(tf.reshape(x0, (-1, NUM_CHANNELS[0])), tf.reshape(indices_maps[0], (-1, )), num_segments=options.batchSize/len(options.gpu_id) * SIZES[0] * SIZES[0]) / options.sumScale
x0_topdown = tf.reshape(x0_topdown, (options.batchSize/len(options.gpu_id), SIZES[0], SIZES[0], -1))
x0_down = x0_topdown
if options.branches == '1':
x1_down = slim.conv2d(x0_down, NUM_CHANNELS[1], (3, 3), stride=2, activation_fn=nn.relu, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5))
x2_down = slim.conv2d(x1_down, NUM_CHANNELS[2], (3, 3), stride=2, activation_fn=nn.relu, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5))
x3_down = slim.conv2d(x2_down, NUM_CHANNELS[3], (3, 3), stride=2, activation_fn=nn.relu, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5))
x4_down = slim.conv2d(x3_down, NUM_CHANNELS[4], (3, 3), stride=2, activation_fn=nn.relu, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5))
x5_down = slim.conv2d(x4_down, NUM_CHANNELS[5], (3, 3), stride=2, activation_fn=nn.relu, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5))
x5_up = x5_down
else:
x1 = slim.conv2d(x0, NUM_CHANNELS[1], (1, NUM_CHANNELS[0]), stride=1, activation_fn=nn.relu, padding='valid', normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5))
if options.poolingTypes[0] == 's':
x1_topdown = tf.unsorted_segment_sum(tf.reshape(x1, (-1, NUM_CHANNELS[1])), tf.reshape(indices_maps[1], (-1, )), num_segments=options.batchSize/len(options.gpu_id) * SIZES[1] * SIZES[1]) / min(options.sumScale * 4, (options.sumScale - 1) * 10000 + 1)
else:
x1_topdown = tf.maximum(tf.unsorted_segment_max(tf.reshape(x1, (-1, NUM_CHANNELS[1])), tf.reshape(indices_maps[1], (-1, )), num_segments=options.batchSize/len(options.gpu_id) * SIZES[1] * SIZES[1]), 0)
pass
x1_topdown = tf.reshape(x1_topdown, (options.batchSize/len(options.gpu_id), SIZES[1], SIZES[1], -1))
x1_down = slim.conv2d(x0_down, NUM_CHANNELS[1], (3, 3), stride=2, activation_fn=nn.relu, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5))
if '2' in options.branches:
x1_unproject = tf.reshape(tf.gather(tf.reshape(x1_down, (-1, NUM_CHANNELS[1])), indices_maps[1], validate_indices=False), (options.batchSize/len(options.gpu_id), options.numPoints, -1))
x1 = mergeFeatures([x1, tf.expand_dims(x1_unproject, 2)])
pass
if '0' in options.branches:
x1_down = mergeFeatures([x1_topdown, x1_down])
pass
x2 = slim.conv2d(x1, NUM_CHANNELS[2], (1, 1), stride=1, activation_fn=nn.relu, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5))
if options.poolingTypes[1] == 's':
x2_topdown = tf.unsorted_segment_sum(tf.reshape(x2, (-1, NUM_CHANNELS[2])), tf.reshape(indices_maps[2], (-1, )), num_segments=options.batchSize/len(options.gpu_id) * SIZES[2] * SIZES[2]) / min(options.sumScale * 16, (options.sumScale - 1) * 10000 + 1)
else:
x2_topdown = tf.maximum(tf.unsorted_segment_max(tf.reshape(x2, (-1, NUM_CHANNELS[2])), tf.reshape(indices_maps[2], (-1, )), num_segments=options.batchSize/len(options.gpu_id) * SIZES[2] * SIZES[2]), 0)
pass
x2_topdown = tf.reshape(x2_topdown, (options.batchSize/len(options.gpu_id), SIZES[2], SIZES[2], -1))
x2_down = slim.conv2d(x1_down, NUM_CHANNELS[2], (3, 3), stride=2, activation_fn=nn.relu, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5))
if '2' in options.branches:
x2_unproject = tf.reshape(tf.gather(tf.reshape(x2_down, (-1, NUM_CHANNELS[2])), indices_maps[2], validate_indices=False), (options.batchSize/len(options.gpu_id), options.numPoints, -1))
x2 = mergeFeatures([x2, tf.expand_dims(x2_unproject, 2)])
pass
if '0' in options.branches:
x2_down = mergeFeatures([x2_topdown, x2_down])
pass
x3 = slim.conv2d(x2, NUM_CHANNELS[3], (1, 1), stride=1, activation_fn=nn.relu, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5))
if options.poolingTypes[2] == 's':
x3_topdown = tf.unsorted_segment_sum(tf.reshape(x3, (-1, NUM_CHANNELS[3])), tf.reshape(indices_maps[3], (-1, )), num_segments=options.batchSize/len(options.gpu_id) * SIZES[3] * SIZES[3]) / min(options.sumScale * 64, (options.sumScale - 1) * 10000 + 1)
else:
x3_topdown = tf.maximum(tf.unsorted_segment_max(tf.reshape(x3, (-1, NUM_CHANNELS[3])), tf.reshape(indices_maps[3], (-1, )), num_segments=options.batchSize/len(options.gpu_id) * SIZES[3] * SIZES[3]), 0)
pass
x3_topdown = tf.reshape(x3_topdown, (options.batchSize/len(options.gpu_id), SIZES[3], SIZES[3], -1))
x3_down = slim.conv2d(x2_down, NUM_CHANNELS[3], (3, 3), stride=2, activation_fn=nn.relu, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5))
if '2' in options.branches:
x3_unproject = tf.reshape(tf.gather(tf.reshape(x3_down, (-1, NUM_CHANNELS[3])), indices_maps[3], validate_indices=False), (options.batchSize/len(options.gpu_id), options.numPoints, -1))
x3 = mergeFeatures([x3, tf.expand_dims(x3_unproject, 2)])
pass
if '0' in options.branches:
x3_down = mergeFeatures([x3_topdown, x3_down])
pass
x4 = slim.conv2d(x3, NUM_CHANNELS[4], (1, 1), stride=1, activation_fn=nn.relu, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5))
if options.poolingTypes[3] == 's':
x4_topdown = tf.unsorted_segment_sum(tf.reshape(x4, (-1, NUM_CHANNELS[4])), tf.reshape(indices_maps[4], (-1, )), num_segments=options.batchSize/len(options.gpu_id) * SIZES[4] * SIZES[4]) / min(options.sumScale * 256, (options.sumScale - 1) * 10000 + 1)
else:
x4_topdown = tf.maximum(tf.unsorted_segment_max(tf.reshape(x4, (-1, NUM_CHANNELS[4])), tf.reshape(indices_maps[4], (-1, )), num_segments=options.batchSize/len(options.gpu_id) * SIZES[4] * SIZES[4]), 0)
pass
x4_topdown = tf.reshape(x4_topdown, (options.batchSize/len(options.gpu_id), SIZES[4], SIZES[4], -1))
x4_down = slim.conv2d(x3_down, NUM_CHANNELS[4], (3, 3), stride=2, activation_fn=nn.relu, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5))
if '2' in options.branches:
x4_unproject = tf.reshape(tf.gather(tf.reshape(x4_down, (-1, NUM_CHANNELS[4])), indices_maps[4], validate_indices=False), (options.batchSize/len(options.gpu_id), options.numPoints, -1))
x4 = mergeFeatures([x4, tf.expand_dims(x4_unproject, 2)])
pass
if '0' in options.branches:
x4_down = mergeFeatures([x4_topdown, x4_down])
pass
x5 = slim.conv2d(x4, NUM_CHANNELS[5], (1, 1), stride=1, activation_fn=nn.relu, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5))
if options.poolingTypes[4] == 's':
x5_topdown = tf.unsorted_segment_sum(tf.reshape(x5, (-1, NUM_CHANNELS[5])), tf.reshape(indices_maps[5], (-1, )), num_segments=options.batchSize/len(options.gpu_id) * SIZES[5] * SIZES[5]) / min(options.sumScale * 1024, (options.sumScale - 1) * 10000 + 1)
else:
x5_topdown = tf.maximum(tf.unsorted_segment_max(tf.reshape(x5, (-1, NUM_CHANNELS[5])), tf.reshape(indices_maps[5], (-1, )), num_segments=options.batchSize/len(options.gpu_id) * SIZES[5] * SIZES[5]), 0)
pass
x5_topdown = tf.reshape(x5_topdown, (options.batchSize/len(options.gpu_id), SIZES[5], SIZES[5], -1))
x5_down = slim.conv2d(x4_down, NUM_CHANNELS[5], (3, 3), stride=2, activation_fn=nn.relu, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5))
if '2' in options.branches:
x5_unproject = tf.reshape(tf.gather(tf.reshape(x5_down, (-1, NUM_CHANNELS[5])), indices_maps[5], validate_indices=False), (options.batchSize/len(options.gpu_id), options.numPoints, -1))
x5 = mergeFeatures([x5, tf.expand_dims(x5_unproject, 2)])
pass
if '0' in options.branches:
x5_down = mergeFeatures([x5_topdown, x5_down])
pass
x_fc_topdown = tflearn.layers.max_pool_2d(x5, (options.numPoints, 1), strides=1, padding='valid')
x_fc_down = tflearn.layers.max_pool_2d(x5_down, (SIZES[5], SIZES[5]), strides=1, padding='valid')
if '0' in options.branches:
x_fc_down = mergeFeatures([x_fc_topdown, x_fc_down])
pass
# no fully connected layer in the middle
#x_fc = tf.reshape(x_fc, (options.batchSize/len(options.gpu_id), -1))
#x_fc = slim.fully_connected(x_fc, 256, activation_fn=nn.relu, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5))
#x_fc = slim.fully_connected(x_fc, NUM_CHANNELS[5], activation_fn=nn.relu, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5))
#x_fc = tf.reshape(x_fc, (options.batchSize/len(options.gpu_id), 1, 1, -1))
x_fc_up = tf.tile(x_fc_down, (1, SIZES[5], SIZES[5], 1))
x5_up = mergeFeatures([x_fc_up, x5_down])
pass
if '3' in options.branches:
if '0' in options.branches:
x_fc = tf.tile(x_fc_down, (1, options.numPoints, 1, 1))
else:
x_fc = tf.tile(x_fc_topdown, (1, options.numPoints, 1, 1))
pass
# merge local point features and global point features
x_fc = tf.concat([x_fc, x3], axis=-1)
x5 = slim.conv2d(x_fc, NUM_CHANNELS[5], (1, 1), stride=1, activation_fn=nn.relu, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5))
pass
if '4' in options.branches:
x5_up = mergeFeatures([x5_up, img_feature[4]])
pass
x4_up = slim.conv2d_transpose(x5_up, NUM_CHANNELS[4], [5, 5], stride=2, activation_fn=nn.relu, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5))
x4_up = mergeFeatures([x4_up, x4_down])
if '3' in options.branches:
x4 = slim.conv2d(x5, NUM_CHANNELS[4], (1, 1), stride=1, activation_fn=nn.relu, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5))
if '2' in options.branches:
x4_up_unproject = tf.reshape(tf.gather(tf.reshape(x4_up, (-1, NUM_CHANNELS[4])), indices_maps[4], validate_indices=False), (options.batchSize/len(options.gpu_id), options.numPoints, -1))
#x4 = tf.add(x4, tf.expand_dims(x4_up_unproject, 2))
x4 = mergeFeatures([x4, tf.expand_dims(x4_up_unproject, 2)])
pass
x4_up_topdown = tf.maximum(tf.unsorted_segment_max(tf.reshape(x4, (-1, NUM_CHANNELS[4])), tf.reshape(indices_maps[4], (-1, )), num_segments=options.batchSize/len(options.gpu_id) * SIZES[4] * SIZES[4]), 0)
x4_up_topdown = tf.reshape(x4_up_topdown, (options.batchSize/len(options.gpu_id), SIZES[4], SIZES[4], -1))
if '0' in options.branches:
x4_up = mergeFeatures([x4_up, x4_up_topdown])
pass
pass
if '4' in options.branches:
x4_up = mergeFeatures([x4_up, img_feature[3]])
pass
x3_up = slim.conv2d_transpose(x4_up, NUM_CHANNELS[3], [5, 5], stride=2, activation_fn=nn.relu, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5))
#print(x3_up)
x3_up = mergeFeatures([x3_up, x3_down])
# if '4' in options.branches:
# img_SIZES = tf.constant([32, 32], dtype='int32')
# resized_image = tf.image.resize_images(img_feature, img_SIZES)
# x3_up = mergeFeatures([x3_up, resized_image])
# pass
if '3' in options.branches:
x3 = slim.conv2d(x4, NUM_CHANNELS[3], (1, 1), stride=1, activation_fn=nn.relu, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5))
if '2' in options.branches:
x3_up_unproject = tf.reshape(tf.gather(tf.reshape(x3_up, (-1, NUM_CHANNELS[3])), indices_maps[3], validate_indices=False), (options.batchSize/len(options.gpu_id), options.numPoints, -1))
#x3 = tf.add(x3, tf.expand_dims(x3_up_unproject, 2))
x3 = mergeFeatures([x3, tf.expand_dims(x3_up_unproject, 2)])
pass
x3_up_topdown = tf.maximum(tf.unsorted_segment_max(tf.reshape(x3, (-1, NUM_CHANNELS[3])), tf.reshape(indices_maps[3], (-1, )), num_segments=options.batchSize/len(options.gpu_id) * SIZES[3] * SIZES[3]), 0)
x3_up_topdown = tf.reshape(x3_up_topdown, (options.batchSize/len(options.gpu_id), SIZES[3], SIZES[3], -1))
if '0' in options.branches:
x3_up = mergeFeatures([x3_up, x3_up_topdown])
pass
pass
if '4' in options.branches:
x3_up = mergeFeatures([x3_up, img_feature[2]])
pass
x2_up = slim.conv2d_transpose(x3_up, NUM_CHANNELS[2], [5, 5], stride=2, activation_fn=nn.relu, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5))
x2_up = mergeFeatures([x2_up, x2_down])
if '3' in options.branches:
x2 = slim.conv2d(x3, NUM_CHANNELS[2], (1, 1), stride=1, activation_fn=nn.relu, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5))
if '2' in options.branches:
x2_up_unproject = tf.reshape(tf.gather(tf.reshape(x2_up, (-1, NUM_CHANNELS[2])), indices_maps[2], validate_indices=False), (options.batchSize/len(options.gpu_id), options.numPoints, -1))
#x2 = tf.add(x2, tf.expand_dims(x2_up_unproject, 2))
x2 = mergeFeatures([x2, tf.expand_dims(x2_up_unproject, 2)])
pass
x2_up_topdown = tf.maximum(tf.unsorted_segment_max(tf.reshape(x2, (-1, NUM_CHANNELS[2])), tf.reshape(indices_maps[2], (-1, )), num_segments=options.batchSize/len(options.gpu_id) * SIZES[2] * SIZES[2]), 0)
x2_up_topdown = tf.reshape(x2_up_topdown, (options.batchSize/len(options.gpu_id), SIZES[2], SIZES[2], -1))
if '0' in options.branches:
x2_up = mergeFeatures([x2_up, x2_up_topdown])
pass
pass
if '4' in options.branches:
x2_up = mergeFeatures([x2_up, img_feature[1]])
pass
x1_up = slim.conv2d_transpose(x2_up, NUM_CHANNELS[1], [5, 5], stride=2, activation_fn=nn.relu, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5))
#print(x1_up.shape)
#print(x1_down.shape)
x1_up = mergeFeatures([x1_up, x1_down])
if '3' in options.branches:
x1 = slim.conv2d(x2, NUM_CHANNELS[1], (1, 1), stride=1, activation_fn=nn.relu, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5))
if '2' in options.branches:
x1_up_unproject = tf.reshape(tf.gather(tf.reshape(x1_up, (-1, NUM_CHANNELS[1])), indices_maps[1], validate_indices=False), (options.batchSize/len(options.gpu_id), options.numPoints, -1))
#print(x1_up_unproject.shape)
#x1 = tf.add(x1, tf.expand_dims(x1_up_unproject, 2))
x1 = mergeFeatures([x1, tf.expand_dims(x1_up_unproject, 2)])
pass
x1_up_topdown = tf.maximum(tf.unsorted_segment_max(tf.reshape(x1, (-1, NUM_CHANNELS[1])), tf.reshape(indices_maps[1], (-1, )), num_segments=options.batchSize/len(options.gpu_id) * SIZES[1] * SIZES[1]), 0)
x1_up_topdown = tf.reshape(x1_up_topdown, (options.batchSize/len(options.gpu_id), SIZES[1], SIZES[1], -1))
if '1' not in options.branches:
x1_up = x1_up_topdown
else:
#print(x1_up_topdown)
x1_up = mergeFeatures([x1_up, x1_up_topdown])
pass
pass
if '4' in options.branches:
x1_up = mergeFeatures([x1_up, img_feature[0]])
pass
#print(x1_up)
#print(NUM_ROOMS)
if options.outputLayers in ['two', 'nobn']:
if options.outputLayers == 'two':
pred_corner = slim.conv2d_transpose(x1_up, NUM_CHANNELS[1], [5, 5], stride=2, activation_fn=nn.relu, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5), scope='pred_corner')
pred_icon = slim.conv2d_transpose(x1_up, NUM_CHANNELS[1], [5, 5], stride=2, activation_fn=nn.relu, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5), scope='pred_icon')
pred_room = slim.conv2d_transpose(x1_up, NUM_CHANNELS[1], [5, 5], stride=2, activation_fn=nn.relu, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5), scope='pred_room')
else:
pred_corner = slim.conv2d_transpose(x1_up, NUM_CHANNELS[1], [5, 5], stride=2, activation_fn=nn.relu, normalizer_fn=None, weights_regularizer=slim.l2_regularizer(1e-5), scope='pred_corner')
pred_icon = slim.conv2d_transpose(x1_up, NUM_CHANNELS[1], [5, 5], stride=2, activation_fn=nn.relu, normalizer_fn=None, weights_regularizer=slim.l2_regularizer(1e-5), scope='pred_icon')
pred_room = slim.conv2d_transpose(x1_up, NUM_CHANNELS[1], [5, 5], stride=2, activation_fn=nn.relu, normalizer_fn=None, weights_regularizer=slim.l2_regularizer(1e-5), scope='pred_room')
pass
pred_corner = slim.conv2d(pred_corner, NUM_CORNERS, (1, 1), stride=1, activation_fn=None, normalizer_fn=None, weights_regularizer=slim.l2_regularizer(1e-5))
pred_icon = slim.conv2d(pred_icon, NUM_ICONS, (1, 1), stride=1, activation_fn=None, normalizer_fn=None, weights_regularizer=slim.l2_regularizer(1e-5))
pred_room = slim.conv2d(pred_room, NUM_ROOMS, (1, 1), stride=1, activation_fn=None, normalizer_fn=None, weights_regularizer=slim.l2_regularizer(1e-5))
else:
pred_corner = slim.conv2d_transpose(x1_up, NUM_CORNERS, [5, 5], stride=2, activation_fn=None, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5), scope='pred_corner')
pred_icon = slim.conv2d_transpose(x1_up, NUM_ICONS, [5, 5], stride=2, activation_fn=None, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5), scope='pred_icon')
pred_room = slim.conv2d_transpose(x1_up, NUM_ROOMS, [5, 5], stride=2, activation_fn=None, normalizer_fn=bn_func, weights_regularizer=slim.l2_regularizer(1e-5), scope='pred_room')
pass
pred_dict = {'corner': pred_corner, 'icon': pred_icon, 'room': pred_room}
debug_dict['x0_topdown'] = x0_topdown
# x1_topdown = tf.unsorted_segment_sum(tf.reshape(x0, (-1, NUM_CHANNELS[0])), tf.reshape(indices_maps[1], (-1, )), num_segments=options.batchSize/len(options.gpu_id) * SIZES[1] * SIZES[1]) / (options.sumScale * 4)
# x1_topdown = tf.reshape(x1_topdown, (options.batchSize/len(options.gpu_id), SIZES[1], SIZES[1], -1))
# debug_dict['x1_topdown'] = x1_topdown
# x2_topdown = tf.unsorted_segment_sum(tf.reshape(x0, (-1, NUM_CHANNELS[0])), tf.reshape(indices_maps[2], (-1, )), num_segments=options.batchSize/len(options.gpu_id) * SIZES[2] * SIZES[2]) / (options.sumScale * 16)
# x2_topdown = tf.reshape(x2_topdown, (options.batchSize/len(options.gpu_id), SIZES[2], SIZES[2], -1))
# debug_dict['x2_topdown'] = x2_topdown
# debug_dict['x1_up'] = x1_up
#debug_dict['resized_image'] = resized_image
pred_dicts.append(pred_dict)
debug_dicts.append(debug_dict)
pass
continue
pred_dict = pred_dicts[0]
for pred in pred_dicts[1:]:
for k,v in pred.items():
pred_dict[k] = tf.concat([pred_dict[k], v], axis=0)
debug_dict = debug_dicts[0]
for de in debug_dicts[1:]:
for k,v in de.items():
debug_dict[k] = tf.concat([debug_dict[k], v], axis=0)
return pred_dict, debug_dict
def build_loss(options, pred_dict, gt_dict, dataset_flag, debug_dict, flags=None):
with tf.device('/gpu:0'):
corner_valid_masks = tf.stack([tf.concat([tf.ones(NUM_WALL_CORNERS), tf.zeros(NUM_CORNERS - NUM_WALL_CORNERS)], axis=0),
tf.ones(NUM_CORNERS),
#tf.concat([tf.ones(NUM_WALL_CORNERS), tf.zeros(NUM_CORNERS - NUM_WALL_CORNERS)], axis=0),
tf.zeros(NUM_CORNERS),
tf.zeros(NUM_CORNERS),
tf.ones(NUM_CORNERS)], axis=0)
icon_valid_masks = tf.stack([tf.zeros(NUM_ICONS),
tf.ones(NUM_ICONS),
#tf.zeros(NUM_ICONS),
tf.ones(NUM_ICONS),
tf.ones(NUM_ICONS),
tf.ones(NUM_ICONS)], axis=0)
room_valid_masks = tf.stack([tf.zeros(NUM_ROOMS),
tf.ones(NUM_ROOMS),
#tf.zeros(NUM_ROOMS),
tf.zeros(NUM_ROOMS),
tf.ones(NUM_ROOMS),
tf.ones(NUM_ROOMS)], axis=0)
corner_valid_masks_bound = []
for lossType in xrange(3):
if lossType == 0:
numChannels = NUM_WALL_CORNERS
else:
numChannels = 4
pass
if str(lossType) in options.loss:
corner_valid_masks_bound.append(tf.ones(numChannels))
else:
corner_valid_masks_bound.append(tf.zeros(numChannels))
pass
continue
corner_valid_masks_bound = tf.concat(corner_valid_masks_bound, axis=0)
if '3' in options.loss:
icon_valid_masks_bound = tf.ones(NUM_ICONS)
else:
icon_valid_masks_bound = tf.zeros(NUM_ICONS)
pass
if '4' in options.loss:
room_valid_masks_bound = tf.ones(NUM_ROOMS)
else:
room_valid_masks_bound = tf.zeros(NUM_ROOMS)
pass
corner_valid_masks = tf.minimum(corner_valid_masks, tf.expand_dims(corner_valid_masks_bound, 0))
icon_valid_masks = tf.minimum(icon_valid_masks, tf.expand_dims(icon_valid_masks_bound, 0))
room_valid_masks = tf.minimum(room_valid_masks, tf.expand_dims(room_valid_masks_bound, 0))
corners = gt_dict['corner']
cornerSegmentation = tf.stack([tf.sparse_to_dense(tf.stack([corners[batchIndex, :, 1], corners[batchIndex, :, 0]], axis=1), (HEIGHT, WIDTH), corners[batchIndex, :, 2], validate_indices=False) for batchIndex in xrange(options.batchSize)], axis=0)
cornerHeatmaps = tf.one_hot(cornerSegmentation, depth=NUM_CORNERS + 1, axis=-1)[:, :, :, 1:]
# cornerHeatmaps = tf.one_hot(cornerSegmentation, depth=NUM_CORNERS, axis=-1)
# kernel = tf.tile(tf.expand_dims(tf.constant(disk(11)), -1), [1, 1, NUM_CORNERS])
# cornerHeatmaps = tf.nn.dilation2d(tf.expand_dims(cornerHeatmaps, 0), kernel, [1, 1, 1, 1], [1, 1, 1, 1], 'SAME')[0]
icon_gt = gt_dict['icon']
room_gt = gt_dict['room']
kernel_size = options.kernelSize
neighbor_kernel_array = disk(kernel_size)
neighbor_kernel = tf.constant(neighbor_kernel_array.reshape(-1), shape=neighbor_kernel_array.shape, dtype=tf.float32)
neighbor_kernel = tf.reshape(neighbor_kernel, [kernel_size, kernel_size, 1, 1])
cornerHeatmaps = tf.nn.depthwise_conv2d(cornerHeatmaps, tf.tile(neighbor_kernel, [1, 1, NUM_CORNERS, 1]), strides=[1, 1, 1, 1], padding='SAME')
corner_gt = tf.cast(cornerHeatmaps > 0.5, tf.float32)
gt_dict['corner_values'] = gt_dict['corner']
gt_dict['corner'] = corner_gt
if options.cornerLossType == 'softmax':
corner_loss = tf.reduce_mean(tf.losses.sparse_softmax_cross_entropy(logits = pred_dict['corner'], labels = corner_gt, weights = tf.maximum(tf.cast(corner_gt > 0, tf.float32) * 100, 1)), axis=[0, 1, 2])
elif options.cornerLossType == 'mse':
#pred_corner = tf.sigmoid(pred_dict['corner'])
#pred_corner = pred_corner * HEATMAP_SCALE
kernel_size = 11
#kernel_size = 5
neighbor_kernel_array = gaussian(kernel_size)
#neighbor_kernel_array = disk(kernel_size)
neighbor_kernel_array /= neighbor_kernel_array.max()
#print(neighbor_kernel_array)
#exit(1)
neighbor_kernel = tf.constant(neighbor_kernel_array.reshape(-1), shape=neighbor_kernel_array.shape, dtype=tf.float32)
neighbor_kernel = tf.reshape(neighbor_kernel, [kernel_size, kernel_size, 1, 1])
#heatmaps = 1 - tf.nn.max_pool(1 - heatmaps, ksize=[1, 3, 3, 1], strides=[1, 1, 1, 1], padding='SAME')
corner_gt = tf.nn.depthwise_conv2d(cornerHeatmaps, tf.tile(neighbor_kernel, [1, 1, NUM_CORNERS, 1]), strides=[1, 1, 1, 1], padding='SAME')
#corner_gt = tf.minimum(corner_gt * HEATMAP_SCALE, HEATMAP_SCALE)
#print(pred_dict['corner'].shape, corner_gt.shape)
#exit(1)
corner_loss = tf.reduce_mean(tf.squared_difference(pred_dict['corner'], corner_gt), axis=[0, 1, 2])
#pred_dict['corner'] /= HEATMAP_SCALE
else:
# kernel_size = 11
# neighbor_kernel_array = disk(kernel_size)
# neighbor_kernel = tf.constant(neighbor_kernel_array.reshape(-1), shape=neighbor_kernel_array.shape, dtype=tf.float32)
# neighbor_kernel = tf.reshape(neighbor_kernel, [kernel_size, kernel_size, 1, 1])
# heatmaps = tf.nn.depthwise_conv2d(heatmaps, tf.tile(neighbor_kernel, [1, 1, NUM_CORNERS, 1]), strides=[1, 1, 1, 1], padding='SAME')
# heatmaps = tf.cast(heatmaps > 0.5, np.float32)
#tune weight to 5
corner_loss = tf.reduce_mean(tf.losses.sigmoid_cross_entropy(logits = pred_dict['corner'], multi_class_labels = corner_gt, weights = tf.maximum(tf.cast(corner_gt > 0.5, tf.float32) * 5, 1), reduction=tf.losses.Reduction.NONE), axis=[0, 1, 2])
pass
#dataset_flag = flags[0][0]
corner_loss = tf.reduce_mean(corner_loss * corner_valid_masks[dataset_flag])
icon_loss = tf.reduce_mean(tf.losses.sparse_softmax_cross_entropy(logits = pred_dict['icon'], labels = icon_gt, weights = tf.maximum(tf.cast(icon_gt > 0, tf.float32) * options.iconPositiveWeight, 1), reduction=tf.losses.Reduction.NONE), axis=[0, 1, 2])
icon_loss = tf.reduce_mean(icon_loss * icon_valid_masks[dataset_flag])
room_loss = tf.reduce_mean(tf.losses.sparse_softmax_cross_entropy(logits = pred_dict['room'], labels = room_gt, reduction=tf.losses.Reduction.NONE), axis=[0, 1, 2])
room_loss = tf.reduce_mean(room_loss * room_valid_masks[dataset_flag])
#room_loss = tf.reduce_mean(tf.squared_difference(tf.squeeze(pred_room), tf.cast(segmentation_gt, tf.float32)))
if options.branches == '4':
corner_loss = tf.reduce_mean(tf.losses.sigmoid_cross_entropy(logits = pred_dict['corner'], multi_class_labels = corner_gt, weights = tf.maximum(tf.cast(corner_gt > 0.5, tf.float32) * 5, 1), reduction=tf.losses.Reduction.NONE), axis=[1, 2, 3])
corner_loss = tf.reduce_sum(corner_loss * tf.cast(flags[:, 1], tf.float32))
icon_loss = tf.reduce_mean(tf.losses.sparse_softmax_cross_entropy(logits = pred_dict['icon'], labels = icon_gt, weights = tf.maximum(tf.cast(icon_gt > 0, tf.float32) * 10, 1), reduction=tf.losses.Reduction.NONE), axis=[1, 2])
icon_loss = tf.reduce_mean(icon_loss * tf.cast(flags[:, 1], tf.float32))
room_loss = tf.reduce_mean(tf.losses.sparse_softmax_cross_entropy(logits = pred_dict['room'], labels = room_gt, reduction=tf.losses.Reduction.NONE), axis=[1, 2])
room_loss = tf.reduce_mean(room_loss * tf.cast(flags[:, 1], tf.float32))
pass
#corner_loss *= options.cornerLossWeight
l2_loss = tf.add_n(tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)) * 0
loss = corner_loss * options.cornerLossWeight + icon_loss * options.iconLossWeight + room_loss + l2_loss
loss_list = []
#losses.append(tf.cond(tf.equal(dataset_inp, 0), lambda: corner_loss, lambda: tf.constant(0.0)))
#losses.append(tf.cond(tf.equal(dataset_inp, 1), lambda: corner_loss, lambda: tf.constant(0.0)))
loss_list.append(corner_loss)
loss_list.append(icon_loss)
loss_list.append(room_loss)
#debug_dict['room_mask'] = room_valid_masks[dataset_flag]
pass
return loss, loss_list
def train(options):
if not os.path.exists(options.checkpoint_dir):
os.system("mkdir -p %s"%options.checkpoint_dir)
pass
if not os.path.exists(options.test_dir):
os.system("mkdir -p %s"%options.test_dir)
pass
if not os.path.exists(options.log_dir):
os.system("mkdir -p %s"%options.log_dir)
pass
filenames_train = []
if '0' in options.hybrid:
filenames_train.append('data/Syn_train.tfrecords')
if '1' in options.hybrid:
filenames_train.append('data/Tango_train.tfrecords')
pass
if '2' in options.hybrid:
filenames_train.append('data/ScanNet_train.tfrecords')
pass
if '3' in options.hybrid:
filenames_train.append('data/Matterport_train.tfrecords')
pass
if '4' in options.hybrid:
filenames_train.append('data/SUNCG_train.tfrecords')
pass
if options.slice:
import RecordReaderSlice
dataset_train = RecordReaderSlice.getDatasetTrain(filenames_train, options.augmentation, '4' in options.branches, options.batchSize)
else:
dataset_train = getDatasetTrain(filenames_train, options.augmentation, '4' in options.branches, options.batchSize)
filenames_val = ['data/Tango_val.tfrecords']
dataset_val = getDatasetVal(filenames_val, '', '4' in options.branches, options.batchSize)
#dataset_val = dataset_train
handle = tf.placeholder(tf.string, shape=[])
iterator = tf.data.Iterator.from_string_handle(handle, dataset_train.output_types, dataset_train.output_shapes)
input_dict, gt_dict = iterator.get_next()
iterator_train = dataset_train.make_one_shot_iterator()
iterator_val = dataset_val.make_initializable_iterator()
pred_dict, debug_dict = build_graph(options, input_dict)
dataset_flag = input_dict['flags'][0, 0]
if '4' in options.branches:
loss, loss_list = build_loss(options, pred_dict, gt_dict, dataset_flag, debug_dict, input_dict['flags'])
else:
loss, loss_list = build_loss(options, pred_dict, gt_dict, dataset_flag, debug_dict)
pass
#training_flag = tf.placeholder(tf.bool, shape=[], name='training_flag')
#with tf.variable_scope('statistics'):
with tf.device('/cpu:0'):
#batchno = tf.Variable(0, dtype=tf.int32)
batchno = tf.Variable(0, dtype=tf.int32, trainable=False, name='batchno')
batchnoinc = batchno.assign(batchno + 1)
#optimizer = tf.train.AdamOptimizer(3e-3).minimize(loss, global_step=batchno, colocate_gradients_with_ops=True)
pass
optimizer = tf.train.AdamOptimizer(3e-3).minimize(loss, global_step=batchno)
#tf.train.write_graph(tf.get_default_graph(), options.log_dir, 'train.pbtxt')
writers_train = []
writers_val = []
for dataset in '01234':
train_writer = tf.summary.FileWriter(options.log_dir + '/train_' + dataset)
val_writer = tf.summary.FileWriter(options.log_dir + '/val_' + dataset)
writers_train.append(train_writer)
writers_val.append(val_writer)
continue
tf.summary.scalar('loss', loss)
for index, l in enumerate(loss_list):
tf.summary.scalar('loss_' + str(index), l)
continue
summary_op = tf.summary.merge_all()
var_to_restore = [v for v in tf.global_variables()]
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
config.allow_soft_placement = True
#config.log_device_placement=True
saver=tf.train.Saver()
threshold = np.ones((HEIGHT, WIDTH, 1)) * 0.5#HEATMAP_SCALE / 2
profileTime = False
if profileTime:
run_metadata = tf.RunMetadata()
run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)
pass
validation_losses = []
with tf.Session(config=config) as sess:
handle_train = sess.run(iterator_train.string_handle())
handle_val = sess.run(iterator_val.string_handle())
sess.run(tf.global_variables_initializer())
tflearn.is_training(True)
#if tf.train.checkpoint_exists("%s/checkpoint.ckpt"%(options.checkpoint_dir)):
if options.restore == 1 and os.path.exists('%s/checkpoint.ckpt.index'%(options.checkpoint_dir)):
#restore the same model from checkpoint
print('restore')
loader = tf.train.Saver(var_to_restore)
if options.startIteration <= 0:
loader.restore(sess, '%s/checkpoint.ckpt'%(options.checkpoint_dir))
else:
loader.restore(sess,"%s/checkpoint_%d.ckpt"%(options.checkpoint_dir, options.startIteration))
pass
bno = sess.run(batchno)
print(bno)
elif options.restore == 2 and os.path.exists('%s/checkpoint.ckpt.index'%(options.checkpoint_dir)):
#restore the same model from checkpoint but reset batchno to 1
loader = tf.train.Saver(var_to_restore)
loader.restore(sess, '%s/checkpoint.ckpt'%(options.checkpoint_dir))
sess.run(batchno.assign(1))
elif options.restore == 3:
loader = tf.train.Saver(var_to_restore)
loader.restore(sess, '%s/checkpoint_%d.ckpt'%(options.checkpoint_dir, options.startIteration))
bno = sess.run(batchno)
print(bno)
elif options.restore == 4:
#fine-tune another model
#var_to_restore = [v for v in var_to_restore if 'res4b22_relu_non_plane' not in v.name]
loader = tf.train.Saver(var_to_restore)
loader.restore(sess, '%s/checkpoint.ckpt'%(options.checkpoint_dir.replace('hybrid1', 'hybrid4')))
sess.run(batchno.assign(1))
elif options.restore == 5:
var_to_restore = [v for v in var_to_restore if 'pred_' not in v.name]
loader = tf.train.Saver(var_to_restore)
loader.restore(sess, '%s/checkpoint.ckpt'%(options.checkpoint_dir))
pass
#if tf.train.checkpoint_exists("%s/%s.ckpt"%(dumpdir,keyname)):
#saver.restore(sess,"%s/%s.ckpt"%(dumpdir,keyname))
#pass
MOVING_AVERAGE_DECAY = 0.99
train_losses = [0., 0., 0.]
train_acc = [1e-4, 1e-4, 1e-4]
val_losses = [0., 0., 0.]
val_acc = [1e-4, 1e-4, 1e-4]
lastsave = time.time()
bno = sess.run(batchno)
#coord = tf.train.Coordinator()
#threads = tf.train.start_queue_runners(sess=sess, coord=coord)
while bno < options.numIterations * (6.0 / options.batchSize):
#while bno<64:
try:
if profileTime:
for iteration in xrange(5):
t0 = time.time()
# if options.slice:
# mydebug = tf.get_collection("mydebug")[0]
# _, total_loss, losses, summary_str, dataset, gt, pred, debug, mydebug_out = sess.run([optimizer, loss, loss_list, summary_op, dataset_flag, gt_dict, pred_dict, debug_dict, mydebug], feed_dict={handle: handle_train}, run_metadata=run_metadata, options=run_options)
# else:
_, total_loss, losses, summary_str, dataset, gt, pred, debug = sess.run([optimizer, loss, loss_list, summary_op, dataset_flag, gt_dict, pred_dict, debug_dict], feed_dict={handle: handle_train}, run_metadata=run_metadata, options=run_options)
print('time', time.time() - t0)
continue
tl = timeline.Timeline(run_metadata.step_stats)
ctf = tl.generate_chrome_trace_format()
with open('test/timeline.json', 'w') as f:
f.write(ctf)
pass
exit(1)
pass
for iteration in xrange(500):
t0 = time.time()
if iteration == 250 and options.visualize:
_, total_loss, losses, summary_str, dataset, gt, pred, debug = sess.run([optimizer, loss, loss_list, summary_op, dataset_flag, gt_dict, pred_dict, debug_dict], feed_dict={handle: handle_train})
visualizeBatch(options, 'train', pred, {'corner': gt['corner'], 'icon': gt['icon'], 'room': gt['room'], 'density': debug['x0_topdown'][:, :, :, -1]}, dataset)
# print(dataset)
# print(losses)
# print(gt['room'].dtype, gt['icon'].dtype)
# print(gt['room'][0].min(), gt['room'][0].max())
# print(pred['room'][0].min(), pred['room'][0].max())
# print(gt['icon'][0].min(), gt['icon'][0].max())
# print(pred['icon'][0].min(), pred['icon'][0].max())
# exit(1)
else:
_, total_loss, losses, summary_str, dataset = sess.run([optimizer, loss, loss_list, summary_op, dataset_flag], feed_dict={handle: handle_train})
pass
for lossIndex, value in enumerate(losses):
train_losses[lossIndex] = train_losses[lossIndex] * MOVING_AVERAGE_DECAY + value
train_acc[lossIndex] = train_acc[lossIndex] * MOVING_AVERAGE_DECAY + 1
continue
#print(bno + iteration, 't', train_losses[0] / train_acc[0], train_losses[1] / train_acc[1], train_losses[2] / train_acc[2], 'v', val_losses[0] / val_acc[0], val_losses[1] / val_acc[1], val_losses[2] / val_acc[2], time.time() - t0)
#print('dataset', dataset)
print('%d: t %02f %02f %02f, v %02f %02f %02f %02f' % (bno + iteration, train_losses[0] / train_acc[0], train_losses[1] / train_acc[1], train_losses[2] / train_acc[2], val_losses[0] / val_acc[0], val_losses[1] / val_acc[1], val_losses[2] / val_acc[2], time.time() - t0))
writers_train[dataset].add_summary(summary_str, bno + iteration)
continue
except tf.errors.OutOfRangeError:
print('Trained 1000 iterations')
pass
bno = sess.run(batchno)
np.random.seed(bno)
sess.run(iterator_val.initializer)
try:
#validation_loss = []
for iteration in xrange(10):
if iteration == 0 and options.visualize:
total_loss, losses, summary_str, dataset, gt, pred, debug = sess.run([loss, loss_list, summary_op, dataset_flag, gt_dict, pred_dict, debug_dict], feed_dict={handle: handle_val})
visualizeBatch(options, 'val', pred, {'corner': gt['corner'], 'icon': gt['icon'], 'room': gt['room'], 'density': debug['x0_topdown'][:, :, :, -1]}, dataset)
else:
total_loss, losses, summary_str, dataset = sess.run([loss, loss_list, summary_op, dataset_flag], feed_dict={handle: handle_val})
pass
for lossIndex, value in enumerate(losses):
val_losses[lossIndex] = val_losses[lossIndex] * MOVING_AVERAGE_DECAY + value
val_acc[lossIndex] = val_acc[lossIndex] * MOVING_AVERAGE_DECAY + 1
continue
print('validation', 't', train_losses[0] / train_acc[0], train_losses[1] / train_acc[1], train_losses[2] / train_acc[2], 'v', val_losses[0] / val_acc[0], val_losses[1] / val_acc[1], val_losses[2] / val_acc[2])
writers_val[dataset].add_summary(summary_str, bno + iteration)
#validation_loss.append(total_loss)
continue
except tf.errors.OutOfRangeError:
print('Finish validation')
pass
pass
# validation_losses.append(val_losses[0] / val_acc[0] + val_losses[1] / val_acc[1] + val_losses[2] / val_acc[2])
# if len(validation_losses) >= 3 and validation_losses[-1] > validation_losses[-2] and validation_losses[-2] > validation_losses[-3]:
# print('validation losses', validation_losses)
# exit(1)
# pass
print('save snapshot')
saver.save(sess, "%s/checkpoint.ckpt"%(options.checkpoint_dir))
if bno % 10000 == 0:
saver.save(sess, "%s/checkpoint_%d.ckpt"%(options.checkpoint_dir, bno))
pass
print(bno, 't', train_losses[0] / train_acc[0], train_losses[1] / train_acc[1], train_losses[2] / train_acc[2], 'v', val_losses[0] / val_acc[0], val_losses[1] / val_acc[1], val_losses[2] / val_acc[2])
continue
pass
return
def test(options):
if not os.path.exists(options.test_dir):
os.system("mkdir -p %s"%options.test_dir)
pass
if options.useCache == 1 and os.path.exists(options.test_dir + '/network_numbers.npy'):
numbers = np.load(options.test_dir + '/network_numbers.npy')[()]
print([(k, v[0] / v[1], v[0] / v[2]) for k, v in numbers.iteritems()])
#print(numbers)
return numbers
#print(options.checkpoint_dir)
tf.reset_default_graph()
filenames = []
if '0' in options.dataset:
filenames.append('data/Syn_val.tfrecords')
if '1' in options.dataset:
filenames.append('data/Tango_val.tfrecords')
pass
if '2' in options.dataset:
filenames.append('data/ScanNet_val.tfrecords')
pass