-
Notifications
You must be signed in to change notification settings - Fork 7
/
eval_multipro.py
1260 lines (1140 loc) · 72.7 KB
/
eval_multipro.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
# System libs
import os
import argparse
from distutils.version import LooseVersion
from multiprocessing import Queue, Process
# Numerical libs
import numpy as np
import math
import torch
import torch.nn as nn
from torch.nn import functional as F
from scipy.io import loadmat
# from sklearn.metrics import confusion_matrix
# Our libs
from config import cfg
from dataset import ValDataset, imresize, b_imresize, patch_loader
from models import ModelBuilder, SegmentationModule, FovSegmentationModule
from utils import AverageMeter, colorEncode, accuracy, intersectionAndUnion, parse_devices, setup_logger, confusion_matrix, hd95
from criterion import OhemCrossEntropy, DiceCoeff, DiceLoss, FocalLoss
from lib.nn import user_scattered_collate, async_copy_to
from lib.utils import as_numpy
from PIL import Image
from tqdm import tqdm
colors = loadmat('data/color150.mat')['colors']
def visualize_result(data, pred, dir_result):
(img, seg, info) = data
# segmentation
seg_color = colorEncode(seg, colors)
# prediction
pred_color = colorEncode(pred, colors)
# aggregate images and save
im_vis = np.concatenate((img, seg_color, pred_color),
axis=1).astype(np.uint8)
img_name = info.split('/')[-1]
Image.fromarray(im_vis).save(os.path.join(dir_result, os.path.splitext(img_name)[0] + '_seg.png'))
def visualize_result_fov(data, foveated_expection, dir_result):
(img, F_Xlr, info) = data
# aggregate images and save
im_vis = np.concatenate((img, foveated_expection),
axis=1).astype(np.uint8)
img_name = info.split('/')[-1]
Image.fromarray(F_Xlr.astype(np.uint8),mode='L').save(os.path.join(dir_result, os.path.splitext(img_name)[0] + '_F_Xlr.png'))
Image.fromarray(im_vis).save(os.path.join(dir_result, os.path.splitext(img_name)[0] + '_fov_exp.png'))
def evaluate(segmentation_module, loader, cfg, gpu_id, result_queue, foveation_module=None):
segmentation_module.eval()
if cfg.MODEL.foveation:
foveation_module.eval()
patch_bank = list((float(cfg.VAL.expand_prediection_rate_patch)*np.array(cfg.MODEL.patch_bank)).astype(int))
# initialize a confusion matrix
confusion = np.zeros((cfg.DATASET.num_class, cfg.DATASET.num_class))
for batch_data in loader:
# process data
if batch_data is None:
continue
batch_data = batch_data[0]
seg_label = as_numpy(batch_data['seg_label'][0])
img_resized_list = batch_data['img_data']
img_resized_list_unnorm = batch_data['img_data_unnorm']
# note for foveation resize not applied, i.e. both seg_label and img_data are at original size
if cfg.VAL.visualize and cfg.MODEL.foveation and cfg.VAL.foveated_expection:
foveated_expection = torch.zeros(batch_data['img_ori'].shape)
# if cfg.VAL.hard_max_fov:
foveated_expection_temp = torch.cat([foveated_expection.unsqueeze(0), foveated_expection.unsqueeze(0)])
foveated_expection_weight = torch.zeros(foveated_expection_temp.shape[0:-1]) # 2,w,h
# else:
# overlap_count = torch.zeros(batch_data['img_ori'].shape)
with torch.no_grad():
segSize = (seg_label.shape[0], seg_label.shape[1])
scores = torch.zeros(1, cfg.DATASET.num_class, segSize[0], segSize[1])
scores_tmp = torch.zeros(1, cfg.DATASET.num_class, segSize[0], segSize[1])
scores = async_copy_to(scores, gpu_id)
scores_tmp = async_copy_to(scores_tmp, gpu_id)
if cfg.VAL.max_score:
scores_tmp_2 = torch.cat([scores_tmp.unsqueeze(0), scores_tmp.unsqueeze(0)])
scores_tmp_2 = async_copy_to(scores_tmp_2, gpu_id)
if cfg.VAL.approx_pred_Fxlr_by_ensemble or cfg.VAL.F_Xlr_low_scale != 0:
fov_map_scale_temp = cfg.MODEL.fov_map_scale
if cfg.VAL.approx_pred_Fxlr_by_ensemble:
scores_ensemble = torch.zeros(1, cfg.DATASET.num_class, segSize[0], segSize[1])
scores_ensemble = async_copy_to(scores_ensemble, gpu_id)
approx_pred_Fxlr_iter = len(patch_bank)
# create fake feed_dict
feed_dict = batch_data.copy()
feed_dict['img_data'] = img_resized_list[0]
feed_dict['img_data_unnorm'] = img_resized_list_unnorm[0]
del feed_dict['img_ori']
del feed_dict['info']
feed_dict = async_copy_to(feed_dict, gpu_id)
# get F_Xlr at original high resolution fov_map_scale # b,d,w,h
X = feed_dict['img_data'] # NOTE only support test image = 1
fov_map_scale = cfg.MODEL.fov_map_scale
X_lr = b_imresize(X, (round(X.shape[2]/fov_map_scale), round(X.shape[3]/(fov_map_scale*cfg.MODEL.patch_ap))), interp='bilinear')
feed_dict['cor_info'] = (tuple([0]), tuple([0]))
if cfg.VAL.visualize:
patch_data, F_Xlr, Y_patch_cord, X_patches_cords, X_patches_unnorm = foveation_module(feed_dict, train_mode=False)
else:
patch_data, F_Xlr, Y_patch_cord = foveation_module(feed_dict, train_mode=False)
# patch_data, F_Xlr, Y_patch_cord = foveation_module(feed_dict, train_mode=False)
F_Xlr_ori = F_Xlr.clone()
print(F_Xlr.size())
# scale F_Xlr to size of score b,d,W,H
if cfg.VAL.approx_pred_Fxlr_by_ensemble:
F_Xlr_scale = b_imresize(F_Xlr, (segSize[0], segSize[1]), interp='nearest')
if cfg.VAL.F_Xlr_low_scale != 0:
# print('!!!!!!!!!!!!!!!!!!!!!!!!!!!Fist detect F_Xlr_low_scale')
F_Xlr_low_res = b_imresize(F_Xlr, (round(X.shape[2]/cfg.VAL.F_Xlr_low_scale), round(X.shape[3]/(cfg.VAL.F_Xlr_low_scale*cfg.MODEL.patch_ap))), interp='bilinear')
cfg.MODEL.fov_map_scale = cfg.VAL.F_Xlr_low_scale
approx_pred_Fxlr_iter = 1
# print('cfg.VAL.F_Xlr_low_scale:', cfg.VAL.F_Xlr_low_scale)
else:
approx_pred_Fxlr_iter = 1
for pred_iter in range(approx_pred_Fxlr_iter):
if cfg.VAL.approx_pred_Fxlr_by_ensemble:
cfg.MODEL.fov_map_scale = patch_bank[0]
cfg.MODEL.one_hot_patch = [0]*len(patch_bank)
cfg.MODEL.one_hot_patch[pred_iter] = 1
for idx in range(len(img_resized_list)):
feed_dict = batch_data.copy()
feed_dict['img_data'] = img_resized_list[idx]
feed_dict['img_data_unnorm'] = img_resized_list_unnorm[idx]
if cfg.VAL.F_Xlr_low_scale != 0:
# print('!!!!!!!!!!!!!!!!!!!!!!!!!!!ADD')
feed_dict['F_Xlr_low_res'] = F_Xlr_low_res
# print('F_Xlr_low_res_size:', feed_dict['F_Xlr_low_res'].size())
del feed_dict['img_ori']
del feed_dict['info']
feed_dict = async_copy_to(feed_dict, gpu_id)
# Foveation
if cfg.MODEL.foveation:
X, Y = feed_dict['img_data'], feed_dict['seg_label']
X_unnorm = feed_dict['img_data_unnorm']
with torch.no_grad():
patch_segSize = (patch_bank[0], patch_bank[0]*cfg.MODEL.patch_ap)
patch_scores = torch.zeros(1, cfg.DATASET.num_class, patch_segSize[0], patch_segSize[1])
patch_scores = async_copy_to(patch_scores, gpu_id)
fov_map_scale = cfg.MODEL.fov_map_scale
# NOTE: although here we use batch imresize yet in practical batch size for X = 1
X_lr = b_imresize(X, (round(X.shape[2]/fov_map_scale), round(X.shape[3]/(fov_map_scale*cfg.MODEL.patch_ap))), interp='bilinear')
# foveation (crop as you go)
if cfg.VAL.F_Xlr_only:
feed_dict['cor_info'] = (tuple([0]), tuple([0]))
patch_data, F_Xlr, Y_patch_cord = foveation_module(feed_dict, train_mode=False)
else:
if cfg.VAL.F_Xlr_acc_map_only:
Xlr_miou_map = torch.zeros(X_lr.shape[2], X_lr.shape[3])
Xlr_loss_map = torch.zeros(X_lr.shape[2], X_lr.shape[3])
print('Percentage of fov_location finished:')
pbar_X_lr = tqdm(total=X_lr.shape[2])
for xi in range(X_lr.shape[2]):
for yi in range(X_lr.shape[3]):
# feed_dict['cor_info'] = (xi, yi)
feed_dict['cor_info'] = (tuple([xi]), tuple([yi]))
if cfg.VAL.visualize:
patch_data, F_Xlr, Y_patch_cord, X_patches_cords, X_patches_unnorm = foveation_module(feed_dict, train_mode=False)
else:
patch_data, F_Xlr, Y_patch_cord = foveation_module(feed_dict, train_mode=False)
# TODO: foveation (pre_cropped available)
if cfg.VAL.F_Xlr_acc_map_only:
patch_scores, patch_loss = segmentation_module(patch_data, segSize=patch_segSize, F_Xlr_acc_map=cfg.VAL.F_Xlr_acc_map_only)
_, patch_pred = torch.max(patch_scores, dim=1)
# w,h
patch_pred = as_numpy(patch_pred.squeeze(0).cpu())
# calculate accuracy and SEND THEM TO MASTER
# acc, pix = accuracy(pred, seg_label)
if 'CITYSCAPES' in cfg.DATASET.root_dataset:
intersection, union, area_lab = intersectionAndUnion(patch_pred, patch_data['seg_label'].squeeze(0).cpu(), cfg.DATASET.num_class, ignore_index=20-1)
else:
if cfg.DATASET.ignore_index != -2:
intersection, union, area_lab = intersectionAndUnion(patch_pred, patch_data['seg_label'].squeeze(0).cpu(), cfg.DATASET.num_class, ignore_index=cfg.DATASET.ignore_index)
else:
intersection, union, area_lab = intersectionAndUnion(patch_pred, patch_data['seg_label'].squeeze(0).cpu(), cfg.DATASET.num_class)
patch_iou = intersection.sum() / union.sum()
Xlr_miou_map[xi,yi] = patch_iou
Xlr_loss_map[xi,yi] = patch_loss
continue
else:
patch_scores = segmentation_module(patch_data, segSize=patch_segSize)
cx_Y, cy_Y, patch_size_Y, p_y_w, p_y_h = Y_patch_cord
if cfg.MODEL.fov_padding:
# p_y = max(patch_bank[0], patch_bank[0]*cfg.MODEL.patch_ap)
scores_tmp_pad = torch.zeros(scores_tmp.shape)
scores_tmp_pad = F.pad(scores_tmp_pad, (p_y_w,p_y_w,p_y_h,p_y_h))
scores_tmp_pad = async_copy_to(scores_tmp_pad, gpu_id)
# print('scores_tmp_pad shape: ', scores_tmp_pad.shape)
patch_size_Y_x = patch_size_Y
patch_size_Y_y = patch_size_Y*cfg.MODEL.patch_ap
if not cfg.VAL.max_score:
if cfg.MODEL.fov_padding:
scores_tmp_pad = scores_tmp_pad*0
scores_tmp_pad[:, :, cx_Y:cx_Y+patch_size_Y_x, cy_Y:cy_Y+patch_size_Y_y] = patch_scores.clone()
scores_tmp = torch.add(scores_tmp, scores_tmp_pad[:, :, p_y_h:scores_tmp_pad.shape[2]-p_y_h, p_y_w:scores_tmp_pad.shape[3]-p_y_w])
else:
scores_tmp[:, :, cx_Y:cx_Y+patch_size_Y_x, cy_Y:cy_Y+patch_size_Y_y] = torch.add(scores_tmp[:, :, cx_Y:cx_Y+patch_size_Y_x, cy_Y:cy_Y+patch_size_Y_y], patch_scores)
else:
if cfg.MODEL.fov_padding:
scores_tmp_pad = scores_tmp_pad*0
scores_tmp_pad[:, :, cx_Y:cx_Y+patch_size_Y_x, cy_Y:cy_Y+patch_size_Y_y] = patch_scores
scores_tmp_2[1] = scores_tmp_pad[:, :, p_y_h:scores_tmp_pad.shape[2]-p_y_h, p_y_w:scores_tmp_pad.shape[3]-p_y_w]
else:
scores_tmp_2[1, :, :, cx_Y:cx_Y+patch_size_Y_x, cy_Y:cy_Y+patch_size_Y_y] = patch_scores
max_class_scores_tmp_2_0, _ = torch.max(scores_tmp_2[0], dim=1)
max_class_scores_tmp_2_1, _ = torch.max(scores_tmp_2[1], dim=1)
# 2,B,W,H, B=1
max_class_scores_tmp_2 = torch.cat([max_class_scores_tmp_2_0.unsqueeze(0), max_class_scores_tmp_2_1.unsqueeze(0)])
# get patch idx of max(max(score))
# patch_idx_by_score.shape = B,W,H; B=1
_, patch_idx_by_score = torch.max(max_class_scores_tmp_2, dim=0)
scores_tmp_2_patch_idx = patch_idx_by_score.unsqueeze(1).unsqueeze(0).expand(scores_tmp_2.shape)
scores_tmp_2[0] = scores_tmp_2.gather(0, scores_tmp_2_patch_idx)[0]
scores_tmp_2[1] = torch.zeros(scores_tmp_2[0].shape)
if cfg.VAL.visualize:
if cfg.VAL.central_crop:
cx_0, cy_0, patch_size_0, p_y_w, p_y_h = Y_patch_cord
if cfg.VAL.hard_max_fov:
weight_s, max_s = torch.max(F_Xlr[0,:,xi,yi], dim=0)
if cfg.MODEL.hard_fov or cfg.MODEL.categorical:
max_s = 0
cx, cy, patch_size, p_w, p_h = X_patches_cords[max_s]
X_patch = b_imresize(X_patches_unnorm[:,max_s,:,:,:], (patch_size, patch_size), interp='nearest')
X_patch = X_patch[0]
print('X_patch_shape: ', X_patch.shape)
# c,w,h
weighed_patch = X_patch.permute(1,2,0).cpu()
# w,h
patch_weight = weight_s.unsqueeze(-1).expand(*weighed_patch.shape[0:-1])
else: # soft fov - max_score=False mode not currently supported
cx_w, cy_w, patch_size_w = 0, 0, 0
for i in range(len(X_patches_cords)):
cx, cy, patch_size, p_w, p_h = X_patches_cords[i]
w = F_Xlr[0,i,xi,yi]
cx_w += w*cx
cy_w += w*cy
patch_size_w += w*patch_size
cx, cy, patch_size = int(cx_w), int(cy_w), int(patch_size_w)
# patch_size = int(torch.sum(F_Xlr[0,:,xi,yi] * torch.FloatTensor(cfg.MODEL.patch_bank)))
if cfg.MODEL.fov_padding:
fov_map_scale = cfg.MODEL.fov_map_scale
# p = patch_size
cx_p = xi*fov_map_scale + patch_size_Y//2 - patch_size//2 + p_h
cy_p = yi*(fov_map_scale*cfg.MODEL.patch_ap) + patch_size_Y//2 - patch_size//2 + p_w
X_unnorm_pad = F.pad(X_unnorm, (p_w,p_w,p_h,p_h))
crop_patch = X_unnorm_pad[:, :, cx_p:cx_p+patch_size, cy_p:cy_p+patch_size]
else:
crop_patch = X_unnorm[:, :, cx:cx+patch_size, cy:cy+patch_size]
X_patch = b_imresize(crop_patch, (patch_size_0,patch_size_0), interp='bilinear')
X_patch = b_imresize(X_patch, (patch_size, patch_size), interp='nearest')
X_patch = X_patch[0]
print('X_patch_shape: ', X_patch.shape)
# c,w,h
weighed_patch = X_patch.permute(1,2,0).cpu()
if cfg.VAL.foveated_expection:
if cfg.MODEL.fov_padding:
fov_map_scale = cfg.MODEL.fov_map_scale
# p = patch_size
cx_p = xi*fov_map_scale + patch_size_Y//2 - patch_size//2 + p_h
cy_p = yi*(fov_map_scale*cfg.MODEL.patch_ap) + patch_size_Y//2 - patch_size//2 + p_w
# C,W,H
foveated_expection_temp_pad = torch.zeros(foveated_expection_temp.shape[3],foveated_expection_temp.shape[1],foveated_expection_temp.shape[2])
foveated_expection_temp_pad = F.pad(foveated_expection_temp_pad, (p_w,p_w,p_h,p_h))
# print('foveated_expection_temp_pad:', foveated_expection_temp_pad.shape)
# print('cx_p, cy_p, patch_size:', cx_p, cy_p, patch_size)
# W,H,C
foveated_expection_temp_pad = foveated_expection_temp_pad.permute(1,2,0)
foveated_expection_temp_pad[cx_p:cx_p+patch_size, cy_p:cy_p+patch_size, :] = weighed_patch
foveated_expection_temp[1] = foveated_expection_temp_pad[p_h:-p_h, p_w:-p_w, :]
if cfg.VAL.central_crop:
# p_y = max(patch_bank[0], patch_bank[0]*cfg.MODEL.patch_ap)
foveated_expection_temp_pad_y = foveated_expection_temp[1].clone() # W,H,C
foveated_expection_temp_pad_y = foveated_expection_temp_pad_y.permute(2,0,1) # C,W,H
foveated_expection_temp_pad_y = F.pad(foveated_expection_temp_pad_y, (p_y_w,p_y_w,p_y_h,p_y_h))
foveated_expection_temp_temp = foveated_expection_temp_pad_y[:, cx_0:cx_0+patch_size_0, cy_0:cy_0+patch_size_0].clone()
foveated_expection_temp_pad_y = foveated_expection_temp_pad_y*0
foveated_expection_temp_pad_y[:, cx_0:cx_0+patch_size_0, cy_0:cy_0+patch_size_0] = foveated_expection_temp_temp
foveated_expection_temp_pad_y = foveated_expection_temp_pad_y.permute(1,2,0) # W,H,C
foveated_expection_temp[1] = foveated_expection_temp_pad_y[p_y_h:foveated_expection_temp_pad_y.shape[0]-p_y_h, p_y_w:foveated_expection_temp_pad_y.shape[1]-p_y_w, :]
print('max: ', torch.max(foveated_expection_temp_temp))
print('min: ', torch.min(foveated_expection_temp_temp))
# if torch.min(foveated_expection_temp_temp) == 0:
# print(foveated_expection_temp_temp)
# raise Exception('weighted patch may wrong')
if cfg.VAL.hard_max_fov:
# W,H
foveated_expection_weight_pad = torch.zeros(foveated_expection_temp_pad.shape[0:-1])
foveated_expection_weight_pad[cx_p:cx_p+patch_size, cy_p:cy_p+patch_size] = patch_weight
foveated_expection_weight[1] = foveated_expection_weight_pad[p_h:-p_h, p_w:-p_w]
else:
# W,H,C
foveated_expection_temp[1, cx:cx+patch_size, cy:cy+patch_size, :] = weighed_patch
if cfg.VAL.hard_max_fov:
# W,H
foveated_expection_weight[1, cx:cx+patch_size, cy:cy+patch_size] = patch_weight
if cfg.VAL.hard_max_fov:
foveated_expection_weight[0], max_w_idx = torch.max(foveated_expection_weight, dim=0)
if not cfg.VAL.max_score:
max_w_idx = max_w_idx.unsqueeze(0).unsqueeze(-1).expand(*foveated_expection_temp.shape)
# max_w_idx_w = max_w_idx.unsqueeze(0).expand(*foveated_expection_weight.shape)
foveated_expection = foveated_expection_temp.gather(0, max_w_idx)[0]
else:
max_s_idx = patch_idx_by_score.unsqueeze(-1).expand(*foveated_expection_temp.shape).cpu()
foveated_expection = foveated_expection_temp.gather(0, max_s_idx)[0]
# foveated_expection_weight[0] = foveated_expection_weight.gather(0, max_w_idx_w).squeeze(0)
foveated_expection_temp[0] = foveated_expection
foveated_expection_temp[1] = torch.zeros(foveated_expection_temp[0].shape)
if cfg.VAL.hard_max_fov:
foveated_expection_weight[1] = torch.zeros(foveated_expection_weight[0].shape)
pbar_X_lr.update(1)
# print('{}/{} foveate points, xi={}, yi={}\n'.format(xi*X_lr.shape[3]+yi, X_lr.shape[2]*X_lr.shape[3], xi, yi))
if cfg.VAL.max_score:
scores_tmp = scores_tmp_2[0]
# print('F_Xlr: ', F_Xlr.shape)
# print(F_Xlr)
# non foveation mode
else:
# forward pass
scores_tmp = segmentation_module(feed_dict, segSize=segSize)
scores = scores + scores_tmp / len(cfg.DATASET.imgSizes)
if cfg.VAL.approx_pred_Fxlr_by_ensemble:
scores_ensemble = scores_ensemble + scores * F_Xlr_scale[:,pred_iter,:,:]
if cfg.VAL.approx_pred_Fxlr_by_ensemble:
scores = scores_ensemble
cfg.MODEL.fov_map_scale = fov_map_scale_temp
if cfg.VAL.F_Xlr_low_scale != 0:
cfg.MODEL.fov_map_scale = fov_map_scale_temp
F_Xlr = F_Xlr_ori
if cfg.VAL.ensemble:
if not os.path.isdir(os.path.join(cfg.DIR, "{}result_{}".format(cfg.VAL.rename_eval_folder, cfg.VAL.checkpoint), 'scores')):
os.makedirs(os.path.join(cfg.DIR, "{}result_{}".format(cfg.VAL.rename_eval_folder, cfg.VAL.checkpoint), 'scores'))
np.save(os.path.join(cfg.DIR, "{}result_{}".format(cfg.VAL.rename_eval_folder, cfg.VAL.checkpoint), 'scores', batch_data['info'].split('/')[-1]), scores.cpu())
if cfg.VAL.F_Xlr_acc_map_only:
if not os.path.isdir(os.path.join(cfg.DIR, "{}result_{}".format(cfg.VAL.rename_eval_folder, cfg.VAL.checkpoint), 'Xlr_miou_map')):
os.makedirs(os.path.join(cfg.DIR, "{}result_{}".format(cfg.VAL.rename_eval_folder, cfg.VAL.checkpoint), 'Xlr_miou_map'))
np.save(os.path.join(cfg.DIR, "{}result_{}".format(cfg.VAL.rename_eval_folder, cfg.VAL.checkpoint), 'Xlr_miou_map', batch_data['info'].split('/')[-1]), Xlr_miou_map.cpu())
if not os.path.isdir(os.path.join(cfg.DIR, "{}result_{}".format(cfg.VAL.rename_eval_folder, cfg.VAL.checkpoint), 'Xlr_loss_map')):
os.makedirs(os.path.join(cfg.DIR, "{}result_{}".format(cfg.VAL.rename_eval_folder, cfg.VAL.checkpoint), 'Xlr_loss_map'))
np.save(os.path.join(cfg.DIR, "{}result_{}".format(cfg.VAL.rename_eval_folder, cfg.VAL.checkpoint), 'Xlr_loss_map', batch_data['info'].split('/')[-1]), Xlr_loss_map.cpu())
_, pred = torch.max(scores, dim=1)
# w,h
pred = as_numpy(pred.squeeze(0).cpu())
# calculate accuracy and SEND THEM TO MASTER
acc, pix = accuracy(pred, seg_label)
if 'CITYSCAPES' in cfg.DATASET.root_dataset:
intersection, union, area_lab = intersectionAndUnion(pred, seg_label, cfg.DATASET.num_class, ignore_index=20-1)
else:
if cfg.DATASET.ignore_index != -2:
intersection, union, area_lab = intersectionAndUnion(pred, seg_label, cfg.DATASET.num_class, ignore_index=cfg.DATASET.ignore_index)
else:
intersection, union, area_lab = intersectionAndUnion(pred, seg_label, cfg.DATASET.num_class)
# calculate Hausdorff distance
h_dists = []
if cfg.VAL.hd95:
if 'CITYSCAPES' in cfg.DATASET.root_dataset:
ig_class = 19
else:
ig_class = cfg.DATASET.ignore_index
for cur_class in range(cfg.DATASET.num_class):
if cur_class == ig_class:
h_dists.append(np.nan)
continue
pred_c = pred.copy()
seg_label_c = seg_label.copy()
mask_pred_b = pred_c != cur_class
mask_pred_f = pred_c == cur_class
pred_c[mask_pred_b] = 0
pred_c[mask_pred_f] = 1
mask_seg_label_b = seg_label_c != cur_class
mask_seg_label_f = seg_label_c == cur_class
seg_label_c[mask_seg_label_b] = 0
seg_label_c[mask_seg_label_f] = 1
if (pred_c == 1).sum() > 1 and (seg_label_c == 1).sum() > 1:
dist_ = hd95(pred_c, seg_label_c)
h_dists.append(dist_)
else:
h_dists.append(np.nan)
# flatten for confusion confusion_matrix
# pred_flatten = pred.flatten()
# seg_label_flatten = seg_label.flatten()
# calculate the confusion matrix and add to the accumulated matrix
if 'CITYSCAPES' in cfg.DATASET.root_dataset:
confusion += confusion_matrix(seg_label, pred, seg_label.shape, cfg.DATASET.num_class, ignore=20-1)
else:
if cfg.DATASET.ignore_index != -2:
confusion += confusion_matrix(seg_label, pred, seg_label.shape, cfg.DATASET.num_class, ignore=cfg.DATASET.ignore_index)
else:
confusion += confusion_matrix(seg_label, pred, seg_label.shape, cfg.DATASET.num_class)
if cfg.MODEL.foveation:
if cfg.MODEL.gumbel_softmax:
F_Xlr = F_Xlr.exp()
F_Xlr_cp = F_Xlr.clone()
F_Xlr_score = as_numpy(F_Xlr.clone().cpu())
patch_bank_F_Xlr = torch.tensor(patch_bank).to(F_Xlr.device)
F_Xlr = patch_bank_F_Xlr.unsqueeze(-1).unsqueeze(-1).float()*(F_Xlr.squeeze(0)).float()
F_Xlr = as_numpy(F_Xlr.cpu())
# F_Xlr = as_numpy(F_Xlr.squeeze(0).cpu())
# print('F_Xlr_np', F_Xlr.shape)
# t,b,d,w,h
F_Xlr = np.sum(F_Xlr,axis=0)
# print('F_Xlr_sum', F_Xlr.shape)
# print(F_Xlr)
F_Xlr = np.expand_dims(F_Xlr,axis=0)
# print('F_Xlr_expand_dims', F_Xlr.shape)
if cfg.VAL.all_F_Xlr_time:
F_Xlr_info = (F_Xlr, batch_data['info'].split('/')[-1].split('.')[0], F_Xlr_score)
result_queue.put_nowait((acc, pix, intersection, union, confusion, area_lab, F_Xlr_info, h_dists))
else:
result_queue.put_nowait((acc, pix, intersection, union, confusion, area_lab, F_Xlr, F_Xlr_score, h_dists))
else:
result_queue.put_nowait((acc, pix, intersection, union, confusion, area_lab))
# visualization
if cfg.VAL.visualize:
# seg_label = convert_label(label=seg_label, inverse=True)
visualize_result(
(batch_data['img_ori'], seg_label, batch_data['info']),
pred,
os.path.join(cfg.DIR, "{}result_{}".format(cfg.VAL.rename_eval_folder, cfg.VAL.checkpoint))
)
if cfg.MODEL.foveation and cfg.VAL.foveated_expection:
# if not cfg.VAL.hard_max_fov:
# foveated_expection = foveated_expection / overlap_count
foveated_expection = as_numpy(foveated_expection.cpu())
# b,d,w,h
# bright -> fine high resolution, dark -> coarse low resolution
# normalize F_Xlr
# np.savetxt(os.path.join(cfg.DIR, "result_{}".format(cfg.VAL.checkpoint), "un_scaled_F_Xlr.txt"), as_numpy(F_Xlr.cpu()))
F_Xlr = F_Xlr_cp
F_Xlr = (F_Xlr-torch.min(F_Xlr))/(torch.max(F_Xlr)-torch.min(F_Xlr))
F_Xlr = b_imresize((1-F_Xlr), (segSize[0], segSize[1]), interp='nearest')
# b,d,w,h -> d,w,h -> w,h,d
F_Xlr = as_numpy(F_Xlr.squeeze(0).permute(1,2,0).cpu())
for idx in range(F_Xlr.shape[2]):
F_Xlr[:,:,idx] = F_Xlr[:,:,idx]*(255//F_Xlr.shape[2]*idx)
F_Xlr = np.sum(F_Xlr,axis=2)
visualize_result_fov(
(batch_data['img_ori'], F_Xlr, batch_data['info']),
foveated_expection*255,
os.path.join(cfg.DIR, "{}result_{}".format(cfg.VAL.rename_eval_folder, cfg.VAL.checkpoint))
)
def evaluate_train(segmentation_module, loader, cfg, gpu_id, result_queue, foveation_module=None):
segmentation_module.eval()
if cfg.MODEL.foveation:
foveation_module.eval()
patch_bank = list((float(cfg.VAL.expand_prediection_rate_patch)*np.array(cfg.MODEL.patch_bank)).astype(int))
# initialize a confusion matrix
confusion = np.zeros((cfg.DATASET.num_class, cfg.DATASET.num_class))
for batch_data in loader:
# process data
if batch_data is None:
continue
batch_data = batch_data[0]
seg_label = as_numpy(batch_data['seg_label'][0])
img_resized_list = batch_data['img_data']
img_resized_list_unnorm = batch_data['img_data_unnorm']
# note for foveation resize not applied, i.e. both seg_label and img_data are at original size
if cfg.VAL.visualize and cfg.MODEL.foveation:
foveated_expection = torch.zeros(batch_data['img_ori'].shape)
# if cfg.VAL.hard_max_fov:
foveated_expection_temp = torch.cat([foveated_expection.unsqueeze(0), foveated_expection.unsqueeze(0)])
foveated_expection_weight = torch.zeros(foveated_expection_temp.shape[0:-1]) # 2,w,h
# else:
# overlap_count = torch.zeros(batch_data['img_ori'].shape)
with torch.no_grad():
segSize = (seg_label.shape[0], seg_label.shape[1])
scores = torch.zeros(1, cfg.DATASET.num_class, segSize[0], segSize[1])
scores_tmp = torch.zeros(1, cfg.DATASET.num_class, segSize[0], segSize[1])
# scores = async_copy_to(scores, gpu_id)
# scores_tmp = async_copy_to(scores_tmp, gpu_id)
if cfg.VAL.max_score:
scores_tmp_2 = torch.cat([scores_tmp.unsqueeze(0), scores_tmp.unsqueeze(0)])
# scores_tmp_2 = async_copy_to(scores_tmp_2, gpu_id)
for idx in range(len(img_resized_list)):
feed_dict = batch_data.copy()
feed_dict['img_data'] = img_resized_list[idx]
feed_dict['img_data_unnorm'] = img_resized_list_unnorm[idx]
del feed_dict['img_ori']
del feed_dict['info']
# feed_dict = async_copy_to(feed_dict, gpu_id)
# Foveation
if cfg.MODEL.foveation:
X, Y = feed_dict['img_data'], feed_dict['seg_label']
X_unnorm = feed_dict['img_data_unnorm']
with torch.no_grad():
patch_segSize = (patch_bank[0], patch_bank[0]*cfg.MODEL.patch_ap)
patch_scores = torch.zeros(1, cfg.DATASET.num_class, patch_segSize[0], patch_segSize[1])
# patch_scores = async_copy_to(patch_scores, gpu_id)
fov_map_scale = cfg.MODEL.fov_map_scale
# NOTE: although here we use batch imresize yet in practical batch size for X = 1
X_lr = b_imresize(X, (round(X.shape[2]/fov_map_scale), round(X.shape[3]/(fov_map_scale*cfg.MODEL.patch_ap))), interp='bilinear')
# foveation (crop as you go)
pbar_X_lr = tqdm(total=X_lr.shape[2])
for xi in range(X_lr.shape[2]):
for yi in range(X_lr.shape[3]):
# feed_dict['cor_info'] = (xi, yi)
feed_dict['cor_info'] = (tuple([xi]), tuple([yi]))
if cfg.VAL.visualize:
patch_data, F_Xlr, Y_patch_cord, X_patches_cords, X_patches_unnorm = foveation_module(feed_dict, train_mode=False)
else:
patch_data, F_Xlr, Y_patch_cord = foveation_module(feed_dict, train_mode=False)
# TODO: foveation (pre_cropped available)
patch_scores = segmentation_module(patch_data, segSize=patch_segSize)
cx_Y, cy_Y, patch_size_Y, p_y_w, p_y_h = Y_patch_cord
if cfg.MODEL.fov_padding:
# p_y = max(patch_bank[0], patch_bank[0]*cfg.MODEL.patch_ap)
scores_tmp_pad = torch.zeros(scores_tmp.shape)
scores_tmp_pad = F.pad(scores_tmp_pad, (p_y_w,p_y_w,p_y_h,p_y_h))
# scores_tmp_pad = async_copy_to(scores_tmp_pad, gpu_id)
# print('scores_tmp_pad shape: ', scores_tmp_pad.shape)
patch_size_Y_x = patch_size_Y
patch_size_Y_y = patch_size_Y*cfg.MODEL.patch_ap
if not cfg.VAL.max_score:
if cfg.MODEL.fov_padding:
scores_tmp_pad = scores_tmp_pad*0
scores_tmp_pad[:, :, cx_Y:cx_Y+patch_size_Y_x, cy_Y:cy_Y+patch_size_Y_y] = patch_scores.clone()
scores_tmp = torch.add(scores_tmp, scores_tmp_pad[:, :, p_y_h:scores_tmp_pad.shape[2]-p_y_h, p_y_w:scores_tmp_pad.shape[3]-p_y_w])
else:
scores_tmp[:, :, cx_Y:cx_Y+patch_size_Y_x, cy_Y:cy_Y+patch_size_Y_y] = torch.add(scores_tmp[:, :, cx_Y:cx_Y+patch_size_Y_x, cy_Y:cy_Y+patch_size_Y_y], patch_scores)
else:
if cfg.MODEL.fov_padding:
scores_tmp_pad = scores_tmp_pad*0
scores_tmp_pad[:, :, cx_Y:cx_Y+patch_size_Y_x, cy_Y:cy_Y+patch_size_Y_y] = patch_scores
scores_tmp_2[1] = scores_tmp_pad[:, :, p_y_h:scores_tmp_pad.shape[2]-p_y_h, p_y_w:scores_tmp_pad.shape[3]-p_y_w]
else:
scores_tmp_2[1, :, :, cx_Y:cx_Y+patch_size_Y_x, cy_Y:cy_Y+patch_size_Y_y] = patch_scores
max_class_scores_tmp_2_0, _ = torch.max(scores_tmp_2[0], dim=1)
max_class_scores_tmp_2_1, _ = torch.max(scores_tmp_2[1], dim=1)
# 2,B,W,H, B=1
max_class_scores_tmp_2 = torch.cat([max_class_scores_tmp_2_0.unsqueeze(0), max_class_scores_tmp_2_1.unsqueeze(0)])
# get patch idx of max(max(score))
# patch_idx_by_score.shape = B,W,H; B=1
_, patch_idx_by_score = torch.max(max_class_scores_tmp_2, dim=0)
scores_tmp_2_patch_idx = patch_idx_by_score.unsqueeze(1).unsqueeze(0).expand(scores_tmp_2.shape)
scores_tmp_2[0] = scores_tmp_2.gather(0, scores_tmp_2_patch_idx)[0]
scores_tmp_2[1] = torch.zeros(scores_tmp_2[0].shape)
if cfg.VAL.visualize:
if cfg.VAL.central_crop:
cx_0, cy_0, patch_size_0, p_y_w, p_y_h = Y_patch_cord
if cfg.VAL.hard_max_fov:
weight_s, max_s = torch.max(F_Xlr[0,:,xi,yi], dim=0)
cx, cy, patch_size, p_w, p_h = X_patches_cords[max_s]
X_patch = b_imresize(X_patches_unnorm[:,max_s,:,:,:], (patch_size, patch_size), interp='nearest')
X_patch = X_patch[0]
print('X_patch_shape: ', X_patch.shape)
# c,w,h
weighed_patch = X_patch.permute(1,2,0).cpu()
# w,h
patch_weight = weight_s.unsqueeze(-1).expand(*weighed_patch.shape[0:-1])
else: # soft fov - max_score=False mode not currently supported
cx_w, cy_w, patch_size_w = 0, 0, 0
for i in range(len(X_patches_cords)):
cx, cy, patch_size, p_w, p_h = X_patches_cords[i]
w = F_Xlr[0,i,xi,yi]
cx_w += w*cx
cy_w += w*cy
patch_size_w += w*patch_size
cx, cy, patch_size = int(cx_w), int(cy_w), int(patch_size_w)
# patch_size = int(torch.sum(F_Xlr[0,:,xi,yi] * torch.FloatTensor(cfg.MODEL.patch_bank)))
if cfg.MODEL.fov_padding:
fov_map_scale = cfg.MODEL.fov_map_scale
# p = patch_size
cx_p = xi*fov_map_scale + patch_size_Y//2 - patch_size//2 + p_h
cy_p = yi*(fov_map_scale*cfg.MODEL.patch_ap) + patch_size_Y//2 - patch_size//2 + p_w
X_unnorm_pad = F.pad(X_unnorm, (p_w,p_w,p_h,p_h))
crop_patch = X_unnorm_pad[:, :, cx_p:cx_p+patch_size, cy_p:cy_p+patch_size]
else:
crop_patch = X_unnorm[:, :, cx:cx+patch_size, cy:cy+patch_size]
X_patch = b_imresize(crop_patch, (patch_size_0,patch_size_0), interp='bilinear')
X_patch = b_imresize(X_patch, (patch_size, patch_size), interp='nearest')
X_patch = X_patch[0]
print('X_patch_shape: ', X_patch.shape)
# c,w,h
weighed_patch = X_patch.permute(1,2,0).cpu()
if cfg.MODEL.fov_padding:
fov_map_scale = cfg.MODEL.fov_map_scale
# p = patch_size
cx_p = xi*fov_map_scale + patch_size_Y//2 - patch_size//2 + p_h
cy_p = yi*(fov_map_scale*cfg.MODEL.patch_ap) + patch_size_Y//2 - patch_size//2 + p_w
# C,W,H
foveated_expection_temp_pad = torch.zeros(foveated_expection_temp.shape[3],foveated_expection_temp.shape[1],foveated_expection_temp.shape[2])
foveated_expection_temp_pad = F.pad(foveated_expection_temp_pad, (p_w,p_w,p_h,p_h))
# print('foveated_expection_temp_pad:', foveated_expection_temp_pad.shape)
# print('cx_p, cy_p, patch_size:', cx_p, cy_p, patch_size)
# W,H,C
foveated_expection_temp_pad = foveated_expection_temp_pad.permute(1,2,0)
foveated_expection_temp_pad[cx_p:cx_p+patch_size, cy_p:cy_p+patch_size, :] = weighed_patch
foveated_expection_temp[1] = foveated_expection_temp_pad[p_h:-p_h, p_w:-p_w, :]
if cfg.VAL.central_crop:
# p_y = max(patch_bank[0], patch_bank[0]*cfg.MODEL.patch_ap)
foveated_expection_temp_pad_y = foveated_expection_temp[1].clone() # W,H,C
foveated_expection_temp_pad_y = foveated_expection_temp_pad_y.permute(2,0,1) # C,W,H
foveated_expection_temp_pad_y = F.pad(foveated_expection_temp_pad_y, (p_y_w,p_y_w,p_y_h,p_y_h))
foveated_expection_temp_temp = foveated_expection_temp_pad_y[:, cx_0:cx_0+patch_size_0, cy_0:cy_0+patch_size_0].clone()
foveated_expection_temp_pad_y = foveated_expection_temp_pad_y*0
foveated_expection_temp_pad_y[:, cx_0:cx_0+patch_size_0, cy_0:cy_0+patch_size_0] = foveated_expection_temp_temp
foveated_expection_temp_pad_y = foveated_expection_temp_pad_y.permute(1,2,0) # W,H,C
foveated_expection_temp[1] = foveated_expection_temp_pad_y[p_y_h:foveated_expection_temp_pad_y.shape[0]-p_y_h, p_y_w:foveated_expection_temp_pad_y.shape[1]-p_y_w, :]
print('max: ', torch.max(foveated_expection_temp_temp))
print('min: ', torch.min(foveated_expection_temp_temp))
# if torch.min(foveated_expection_temp_temp) == 0:
# print(foveated_expection_temp_temp)
# raise Exception('weighted patch may wrong')
if cfg.VAL.hard_max_fov:
# W,H
foveated_expection_weight_pad = torch.zeros(foveated_expection_temp_pad.shape[0:-1])
foveated_expection_weight_pad[cx_p:cx_p+patch_size, cy_p:cy_p+patch_size] = patch_weight
foveated_expection_weight[1] = foveated_expection_weight_pad[p_h:-p_h, p_w:-p_w]
else:
# W,H,C
foveated_expection_temp[1, cx:cx+patch_size, cy:cy+patch_size, :] = weighed_patch
if cfg.VAL.hard_max_fov:
# W,H
foveated_expection_weight[1, cx:cx+patch_size, cy:cy+patch_size] = patch_weight
if cfg.VAL.hard_max_fov:
foveated_expection_weight[0], max_w_idx = torch.max(foveated_expection_weight, dim=0)
if not cfg.VAL.max_score:
max_w_idx = max_w_idx.unsqueeze(0).unsqueeze(-1).expand(*foveated_expection_temp.shape)
# max_w_idx_w = max_w_idx.unsqueeze(0).expand(*foveated_expection_weight.shape)
foveated_expection = foveated_expection_temp.gather(0, max_w_idx)[0]
else:
max_s_idx = patch_idx_by_score.unsqueeze(-1).expand(*foveated_expection_temp.shape).cpu()
foveated_expection = foveated_expection_temp.gather(0, max_s_idx)[0]
# foveated_expection_weight[0] = foveated_expection_weight.gather(0, max_w_idx_w).squeeze(0)
foveated_expection_temp[0] = foveated_expection
foveated_expection_temp[1] = torch.zeros(foveated_expection_temp[0].shape)
if cfg.VAL.hard_max_fov:
foveated_expection_weight[1] = torch.zeros(foveated_expection_weight[0].shape)
# else:
# for s in range(len(X_patches_cords)):
# cx, cy, patch_size, p = X_patches_cords[s]
# # X_patches_unnorm: b,d,c,w,h
# X_patch = b_imresize(X_patches_unnorm[:,s,:,:,:], (patch_size, patch_size), interp='nearest')
# # X_patch: b,c,w,h
# # NOTE: current version only appliable for batch size = 1
# X_patch = X_patch[0]
# # c,w,h
# # TODO: check is this right??? should it be F_Xlr[:,s,xi,yi] NOT 1-F_Xlr[:,s,xi,yi] ?
# weighed_patch = (1-F_Xlr[:,s,xi,yi]).unsqueeze(-1).unsqueeze(-1).expand(*X_patch.size())*X_patch
# # w,h,c
# weighed_patch = weighed_patch.permute(1,2,0).cpu()
# foveated_expection[cx:cx+patch_size, cy:cy+patch_size, :] = foveated_expection[cx:cx+patch_size, cy:cy+patch_size, :] + weighed_patch
# overlap_count[cx:cx+patch_size, cy:cy+patch_size, :] += torch.ones_like(weighed_patch)
# print('{}/{} foveate points, xi={}, yi={}'.format(xi*X_lr.shape[3]+yi, X_lr.shape[2]*X_lr.shape[3], xi, yi))
pbar_X_lr.update(1)
if cfg.VAL.max_score:
scores_tmp = scores_tmp_2[0]
# print('F_Xlr: ', F_Xlr.shape)
# print(F_Xlr)
# non foveation mode
else:
# forward pass
scores_tmp = segmentation_module(feed_dict, segSize=segSize)
scores = scores + scores_tmp / len(cfg.DATASET.imgSizes)
_, pred = torch.max(scores, dim=1)
# w,h
pred = as_numpy(pred.squeeze(0).cpu())
# calculate accuracy and SEND THEM TO MASTER
acc, pix = accuracy(pred, seg_label)
if 'CITYSCAPES' in cfg.DATASET.root_dataset:
intersection, union, area_lab = intersectionAndUnion(pred, seg_label, cfg.DATASET.num_class, ignore_index=20-1)
else:
if cfg.DATASET.ignore_index != -2:
intersection, union, area_lab = intersectionAndUnion(pred, seg_label, cfg.DATASET.num_class, ignore_index=cfg.DATASET.ignore_index)
else:
intersection, union, area_lab = intersectionAndUnion(pred, seg_label, cfg.DATASET.num_class)
# flatten for confusion confusion_matrix
pred_flatten = pred.flatten()
seg_label_flatten = seg_label.flatten()
# calculate the confusion matrix and add to the accumulated matrix
if 'CITYSCAPES' in cfg.DATASET.root_dataset:
confusion += confusion_matrix(seg_label, pred, seg_label.shape, cfg.DATASET.num_class, ignore=20-1)
else:
if cfg.DATASET.ignore_index != -2:
confusion += confusion_matrix(seg_label, pred, seg_label.shape, cfg.DATASET.num_class, ignore=cfg.DATASET.ignore_index)
else:
confusion += confusion_matrix(seg_label, pred, seg_label.shape, cfg.DATASET.num_class)
if cfg.MODEL.foveation:
# b,d,w,h
# print(F_Xlr.shape)
# F_Xlr = (F_Xlr-torch.min(F_Xlr))/(torch.max(F_Xlr)-torch.min(F_Xlr))
# print(F_Xlr.shape)
# for idx in range(F_Xlr.shape[1]):
# F_Xlr[:,idx,:,:] = F_Xlr[:,idx,:,:]*(255//F_Xlr.shape[1]*idx)
# print(F_Xlr.shape)
patch_bank_F_Xlr = torch.tensor(patch_bank).to(F_Xlr.device)
F_Xlr = patch_bank_F_Xlr.unsqueeze(-1).unsqueeze(-1).float()*(F_Xlr.squeeze(0)).float()
F_Xlr = as_numpy(F_Xlr.cpu())
# F_Xlr = as_numpy(F_Xlr.squeeze(0).cpu())
# print('F_Xlr_np', F_Xlr.shape)
# t,b,d,w,h
F_Xlr = np.sum(F_Xlr,axis=0)
# print('F_Xlr_sum', F_Xlr.shape)
# print(F_Xlr)
F_Xlr = np.expand_dims(F_Xlr,axis=0)
# print('F_Xlr_expand_dims', F_Xlr.shape)
if cfg.VAL.all_F_Xlr_time:
F_Xlr_info = (F_Xlr, batch_data['info'].split('/')[-1].split('.')[0])
result_queue.put_nowait((acc, pix, intersection, union, confusion, area_lab, F_Xlr_info))
else:
result_queue.put_nowait((acc, pix, intersection, union, confusion, area_lab, F_Xlr))
else:
result_queue.put_nowait((acc, pix, intersection, union, confusion, area_lab))
# visualization
if cfg.VAL.visualize:
# seg_label = convert_label(label=seg_label, inverse=True)
visualize_result(
(batch_data['img_ori'], seg_label, batch_data['info']),
pred,
os.path.join(cfg.DIR, "{}result_{}".format(cfg.VAL.rename_eval_folder, cfg.VAL.checkpoint))
)
if cfg.MODEL.foveation:
# if not cfg.VAL.hard_max_fov:
# foveated_expection = foveated_expection / overlap_count
foveated_expection = as_numpy(foveated_expection.cpu())
# b,d,w,h
# bright -> fine high resolution, dark -> coarse low resolution
# normalize F_Xlr
# np.savetxt(os.path.join(cfg.DIR, "result_{}".format(cfg.VAL.checkpoint), "un_scaled_F_Xlr.txt"), as_numpy(F_Xlr.cpu()))
F_Xlr = (F_Xlr-torch.min(F_Xlr))/(torch.max(F_Xlr)-torch.min(F_Xlr))
F_Xlr = b_imresize((1-F_Xlr), (segSize[0], segSize[1]), interp='nearest')
# b,d,w,h -> d,w,h -> w,h,d
F_Xlr = as_numpy(F_Xlr.squeeze(0).permute(1,2,0).cpu())
for idx in range(F_Xlr.shape[2]):
F_Xlr[:,:,idx] = F_Xlr[:,:,idx]*(255//F_Xlr.shape[2]*idx)
F_Xlr = np.sum(F_Xlr,axis=2)
visualize_result_fov(
(batch_data['img_ori'], F_Xlr, batch_data['info']),
foveated_expection*255,
os.path.join(cfg.DIR, "{}result_{}".format(cfg.VAL.rename_eval_folder, cfg.VAL.checkpoint))
)
def worker_train(cfg, gpu_id, start_idx, end_idx, result_queue):
# torch.cuda.set_device(gpu_id)
# Dataset and Loader
dataset_val = ValDataset(
cfg.DATASET.root_dataset,
cfg.DATASET.list_val,
cfg.DATASET,
cfg,
start_idx=start_idx, end_idx=end_idx)
loader_val = torch.utils.data.DataLoader(
dataset_val,
batch_size=cfg.VAL.batch_size,
shuffle=False,
collate_fn=user_scattered_collate,
num_workers=2)
# Network Builders
net_encoder = ModelBuilder.build_encoder(
arch=cfg.MODEL.arch_encoder.lower(),
fc_dim=cfg.MODEL.fc_dim,
weights=cfg.MODEL.weights_encoder)
net_decoder = ModelBuilder.build_decoder(
arch=cfg.MODEL.arch_decoder.lower(),
fc_dim=cfg.MODEL.fc_dim,
num_class=cfg.DATASET.num_class,
weights=cfg.MODEL.weights_decoder,
use_softmax=True)
if cfg.MODEL.foveation:
net_foveater = ModelBuilder.build_foveater(
in_channel=cfg.MODEL.in_dim,
out_channel=len(cfg.MODEL.patch_bank),
weights=cfg.MODEL.weights_foveater,
cfg=cfg)
# crit = nn.NLLLoss(ignore_index=-1)
# Gleason2019:
# NOTE: DON'T use ignore_index to omit class 3 which will lead final layer size missmatch, use weight=0 for class 3
# ignore_label = -1 # because we added 1, so the original gs2 class labelled as 3
# total_lab_weight [2.0343, 15.8754, inf, 5.2565, 4.0280, 561.1551, 194.2561], inf will be omit by pass 0 instead of inf in the Tensor
# TODO: weight now calculated based on 67 STAPLE fused gt subset, full
# class_weights = torch.cuda.FloatTensor([2.0343, 15.8754, 0, 5.2565, 4.0280, 561.1551, 194.2561])
# omit background and set upper cap as 10
# class_weights = torch.cuda.FloatTensor([1, 1, 0, 1, 1, 0, 0])
# crit = nn.CrossEntropyLoss(weight=class_weights, ignore_index=ignore_label)
if 'CITYSCAPES' in cfg.DATASET.root_dataset:
if cfg.TRAIN.loss_fun == 'NLLLoss':
crit = nn.NLLLoss(ignore_index=19)
else:
crit = nn.CrossEntropyLoss(ignore_index=20-1)
elif 'Digest' in cfg.DATASET.root_dataset:
crit = nn.CrossEntropyLoss(ignore_index=-2)
elif cfg.TRAIN.loss_fun == 'FocalLoss' and 'DeepGlob' in cfg.DATASET.root_dataset:
crit = FocalLoss(gamma=6, ignore_label=cfg.DATASET.ignore_index)
else:
if cfg.TRAIN.loss_fun == 'NLLLoss':
if cfg.DATASET.ignore_index != -2:
crit = nn.NLLLoss(ignore_index=cfg.DATASET.ignore_index)
else:
crit = nn.NLLLoss(ignore_index=-2)
else:
if cfg.DATASET.ignore_index != -2:
crit = nn.CrossEntropyLoss(ignore_index=cfg.DATASET.ignore_index)
else:
crit = nn.CrossEntropyLoss(ignore_index=-2)
segmentation_module = SegmentationModule(net_encoder, net_decoder, crit, cfg)
if cfg.MODEL.foveation:
foveation_module = FovSegmentationModule(net_foveater, cfg)
# segmentation_module.cuda()
# if cfg.MODEL.foveation:
# foveation_module.cuda()
# if not os.path.exists(os.path.join(cfg.DIR, 'network_summary.txt')):
# f = open(os.path.join(cfg.DIR, 'network_summary.txt'), 'w')
# if cfg.MODEL.foveation:
# print(foveation_module, file = f)
# print(segmentation_module, file = f)
if cfg.MODEL.foveation:
foveation_module = FovSegmentationModule(net_foveater, cfg)
# total_fov = sum([param.nelement() for param in foveation_module.parameters()])
# print('Number of FoveationModule params: %.2fM \n' % (total_fov / 1e6))
#
# total = sum([param.nelement() for param in segmentation_module.parameters()])
# f.write('Number of SegmentationModule params: %.2fM \n' % (total / 1e6))
# Main loop
if cfg.MODEL.foveation:
evaluate(segmentation_module, loader_val, cfg, gpu_id, result_queue, foveation_module)
else:
evaluate(segmentation_module, loader_val, cfg, gpu_id, result_queue)
# f.write('Max memory allocated: %.2fM' % (torch.cuda.max_memory_allocated() / 1e6))
# f.close()
def worker(cfg, gpu_id, start_idx, end_idx, result_queue):
torch.cuda.set_device(gpu_id)
# Dataset and Loader
dataset_val = ValDataset(
cfg.DATASET.root_dataset,
cfg.DATASET.list_val,
cfg.DATASET,
cfg,
start_idx=start_idx, end_idx=end_idx)
loader_val = torch.utils.data.DataLoader(
dataset_val,
batch_size=cfg.VAL.batch_size,
shuffle=False,
collate_fn=user_scattered_collate,
num_workers=2)
# Network Builders
net_encoder = ModelBuilder.build_encoder(
arch=cfg.MODEL.arch_encoder.lower(),
fc_dim=cfg.MODEL.fc_dim,
weights=cfg.MODEL.weights_encoder)
net_decoder = ModelBuilder.build_decoder(
arch=cfg.MODEL.arch_decoder.lower(),
fc_dim=cfg.MODEL.fc_dim,
num_class=cfg.DATASET.num_class,
weights=cfg.MODEL.weights_decoder,
use_softmax=True)
if cfg.MODEL.foveation:
net_foveater = ModelBuilder.build_foveater(
in_channel=cfg.MODEL.in_dim,
out_channel=len(cfg.MODEL.patch_bank),
weights=cfg.MODEL.weights_foveater,
cfg=cfg)
if 'CITYSCAPES' in cfg.DATASET.root_dataset:
if cfg.TRAIN.loss_fun == 'NLLLoss':
crit = nn.NLLLoss(ignore_index=19)
else:
crit = nn.CrossEntropyLoss(ignore_index=19)
elif 'Digest' in cfg.DATASET.root_dataset:
if cfg.TRAIN.loss_fun == 'NLLLoss':
crit = nn.NLLLoss(ignore_index=-2)
else:
crit = nn.CrossEntropyLoss(ignore_index=-2)
elif cfg.TRAIN.loss_fun == 'FocalLoss' and 'DeepGlob' in cfg.DATASET.root_dataset:
crit = FocalLoss(gamma=6, ignore_label=cfg.DATASET.ignore_index)
else:
if cfg.TRAIN.loss_fun == 'NLLLoss':
if cfg.DATASET.ignore_index != -2:
crit = nn.NLLLoss(ignore_index=cfg.DATASET.ignore_index)
else:
crit = nn.NLLLoss(ignore_index=-2)
else:
if cfg.DATASET.ignore_index != -2:
crit = nn.CrossEntropyLoss(ignore_index=cfg.DATASET.ignore_index)
else:
crit = nn.CrossEntropyLoss(ignore_index=-2)
segmentation_module = SegmentationModule(net_encoder, net_decoder, crit, cfg)
if cfg.MODEL.foveation:
foveation_module = FovSegmentationModule(net_foveater, cfg)
segmentation_module.cuda()
if cfg.MODEL.foveation:
foveation_module.cuda()
# if not os.path.exists(os.path.join(cfg.DIR, 'network_summary.txt')):
f = open(os.path.join(cfg.DIR, 'network_summary.txt'), 'w')
if cfg.MODEL.foveation:
print(foveation_module, file = f)
print(segmentation_module, file = f)
if cfg.MODEL.foveation:
foveation_module = FovSegmentationModule(net_foveater, cfg)
total_fov = sum([param.nelement() for param in foveation_module.parameters()])
print('Number of FoveationModule params: %.2fM \n' % (total_fov / 1e6))
total = sum([param.nelement() for param in segmentation_module.parameters()])
f.write('Number of SegmentationModule params: %.2fM \n' % (total / 1e6))
# Main loop
if cfg.MODEL.foveation:
evaluate(segmentation_module, loader_val, cfg, gpu_id, result_queue, foveation_module)
else:
evaluate(segmentation_module, loader_val, cfg, gpu_id, result_queue)
f.write('Max memory allocated: %.2fM' % (torch.cuda.max_memory_allocated() / 1e6))
f.close()
def eval_during_train_multipro(cfg, gpus):
# absolute paths of model weights
cfg.MODEL.weights_encoder = os.path.join(
cfg.DIR, 'encoder_' + cfg.VAL.checkpoint)
cfg.MODEL.weights_decoder = os.path.join(
cfg.DIR, 'decoder_' + cfg.VAL.checkpoint)
# load foveation weights
if cfg.MODEL.foveation:
weights=cfg.MODEL.weights_foveater = os.path.join(
cfg.DIR, 'foveater_' + cfg.VAL.checkpoint)
assert os.path.exists(cfg.MODEL.weights_foveater), "checkpoint does not exitst!"
assert os.path.exists(cfg.MODEL.weights_encoder) and \
os.path.exists(cfg.MODEL.weights_decoder), "checkpoint does not exitst!"
with open(cfg.DATASET.list_val, 'r') as f:
lines = f.readlines()
num_files = len(lines)
num_files_per_gpu = math.ceil(num_files / len(gpus))
pbar = tqdm(total=num_files)
acc_meter = AverageMeter()
intersection_meter = AverageMeter()