3636from detection .frcnn_la import fasterrcnn_resnet50_fpn_feature
3737from detection .retinanet_cal import retinanet_mobilenet , retinanet_resnet50_fpn_cal
3838
39+ A = 1
40+
3941
4042def train_one_epoch (task_model , task_optimizer , data_loader , device , cycle , epoch , print_freq ):
4143 task_model .train ()
@@ -53,6 +55,10 @@ def train_one_epoch(task_model, task_optimizer, data_loader, device, cycle, epoc
5355 for images , targets in metric_logger .log_every (data_loader , print_freq , header ):
5456 images = list (image .to (device ) for image in images )
5557 targets = [{k : v .to (device ) for k , v in t .items ()} for t in targets ]
58+ # global A
59+ # for image, target in zip(images, targets):
60+ # draw_PIL_image(image, target['boxes'], target['labels'], None, "unlabeled_{}".format(A))
61+ # A += 1
5662 task_loss_dict = task_model (images , targets )
5763 task_losses = sum (loss for loss in task_loss_dict .values ())
5864 # reduce losses over all GPUs for logging purposes
@@ -203,8 +209,8 @@ def get_uncertainty(task_model, unlabeled_loader, augs, num_cls):
203209 for output , aug_box , aug_image in zip (outputs , aug_boxes , aug_images ):
204210 consistency_img = 1.0
205211 mean_img = []
206- boxes , scores_cls , pm , labels = output ['boxes' ], output ['scores_cls' ], output ['prob_max' ], output [
207- 'labels' ]
212+ boxes , scores_cls , pm , labels , scores = output ['boxes' ], output ['scores_cls' ], output ['prob_max' ], \
213+ output [ 'labels' ], output [ 'scores ' ]
208214 cls_corr = [0 ] * (num_cls - 1 )
209215 for p , l in zip (pm , labels ):
210216 # if p.item() > 0.4:
@@ -217,7 +223,7 @@ def get_uncertainty(task_model, unlabeled_loader, augs, num_cls):
217223 continue
218224 j = 0
219225 no = []
220- for ab , ref_score_cls , ref_pm in zip (aug_box , ref_scores_cls , prob_max ):
226+ for ab , ref_score_cls , ref_pm , ref_score in zip (aug_box , ref_scores_cls , prob_max , ref_scores ):
221227 width = torch .min (ab [2 ], boxes [:, 2 ]) - torch .max (ab [0 ], boxes [:, 0 ])
222228 height = torch .min (ab [3 ], boxes [:, 3 ]) - torch .max (ab [1 ], boxes [:, 1 ])
223229 Aarea = (ab [2 ] - ab [0 ]) * (ab [3 ] - ab [1 ])
@@ -232,13 +238,13 @@ def get_uncertainty(task_model, unlabeled_loader, augs, num_cls):
232238 js = 0.5 * scipy .stats .entropy (p , m ) + 0.5 * scipy .stats .entropy (q , m )
233239 if js < 0 :
234240 js = 0
235- # if 0.6 > torch.max(iou) > 0.4 and 0.4 < 0.5 * (1 - js) * (
236- # ref_pm + pm[torch.argmax(iou)]) < 0.6 and (ab[2] - ab[0]) > 200 and \
237- # torch.max(ref_score_cls) < 0.6 and pm[torch.argmax(iou)] < 0.6 :
241+ # if 0.7 < torch.max(iou) and 0.4 > 0.5 * (1 - js) * (
242+ # ref_pm + pm[torch.argmax(iou)]) and (ab[2] - ab[0]) > 100 and scores[
243+ # torch.argmax(iou)] > 0.4 and ref_score > 0.4 :
238244 # # draw_PIL_image(image, boxes, ref_labels, i, no=[ab], color='greenyellow')
239245 # no = [j, torch.argmax(iou).item()]
240246 # draw_PIL_image_2(aug_image.cpu(), aug_box, boxes, ref_labels, labels, ref_scores, pm,
241- # 'bad ', no=no, color='red')
247+ # 'bad_2 ', no=no, color='red')
242248 # print(1 / 0)
243249 j += 1
244250 consistency_img = min (consistency_img , torch .abs (
@@ -379,7 +385,7 @@ def main(args):
379385 init_num = 500
380386 budget_num = 500
381387 if 'retina' in args .model :
382- init_num = 500
388+ init_num = 1000
383389 budget_num = 500
384390 else :
385391 init_num = 5000
@@ -441,14 +447,23 @@ def main(args):
441447 print ("Getting stability" )
442448 random .shuffle (unlabeled_set )
443449 if 'coco' in args .dataset :
444- subset = unlabeled_set [:10000 ]
450+ subset = unlabeled_set [:5000 ]
445451 else :
446452 subset = unlabeled_set
447453 if args .mutual :
448454 unlabeled_loader = DataLoader (dataset_aug , batch_size = 1 , sampler = SubsetSequentialSampler (subset ),
449455 num_workers = args .workers , pin_memory = True , collate_fn = utils .collate_fn )
450456 uncertainty , _cls_corrs = get_uncertainty (task_model , unlabeled_loader , augs , num_classes )
457+ # labeled_loader = DataLoader(dataset_aug, batch_size=1, sampler=SubsetSequentialSampler(labeled_set),
458+ # num_workers=args.workers, pin_memory=True, collate_fn=utils.collate_fn)
459+ # u, _ = get_uncertainty(task_model, labeled_loader, augs, num_classes)
460+ # with open("vis/cal_labeled_metric_{}_{}_{}.pkl".format(args.model, args.dataset, cycle),
461+ # "wb") as fp: # Pickling
462+ # pickle.dump(u, fp)
451463 arg = np .argsort (np .array (uncertainty ))
464+ # with open("vis/cal_unlabeled_metric_{}_{}_{}.pkl".format(args.model, args.dataset, cycle),
465+ # "wb") as fp: # Pickling
466+ # pickle.dump(torch.tensor(uncertainty)[arg][:budget_num].numpy(), fp)
452467 cls_corrs_set = arg [:int (args .mr * budget_num )]
453468 cls_corrs = [_cls_corrs [i ] for i in cls_corrs_set ]
454469 labeled_loader = DataLoader (dataset_aug , batch_size = 1 , sampler = SubsetSequentialSampler (labeled_set ),
@@ -457,8 +472,6 @@ def main(args):
457472 # Update the labeled dataset and the unlabeled dataset, respectively
458473 tobe_labeled_set = list (torch .tensor (subset )[arg ][tobe_labeled_set ].numpy ())
459474 labeled_set += tobe_labeled_set
460- with open ("vis/cal_{}_{}_{}.txt" .format (args .model , args .dataset , cycle ), "wb" ) as fp : # Pickling
461- pickle .dump (labeled_set , fp )
462475 unlabeled_set = list (set (indices ) - set (labeled_set ))
463476 else :
464477 unlabeled_loader = DataLoader (dataset_aug , batch_size = 1 , sampler = SubsetSequentialSampler (subset ),
@@ -467,6 +480,7 @@ def main(args):
467480 arg = np .argsort (np .array (uncertainty ))
468481 # Update the labeled dataset and the unlabeled dataset, respectively
469482 labeled_set += list (torch .tensor (subset )[arg ][:budget_num ].numpy ())
483+ labeled_set = list (set (labeled_set ))
470484 unlabeled_set = list (set (indices ) - set (labeled_set ))
471485
472486 # Create a new dataloader for the updated labeled dataset
@@ -494,26 +508,35 @@ def main(args):
494508 coco_evaluate (task_model , data_loader_test )
495509 elif 'voc' in args .dataset :
496510 voc_evaluate (task_model , data_loader_test , args .dataset , False , path = args .results_path )
497- if not args .skip and cycle == 0 :
498- if 'faster' in args .model :
499- utils .save_on_master ({
500- 'model' : task_model .state_dict (), 'args' : args },
501- os .path .join (args .first_checkpoint_path , '{}_frcnn_1st.pth' .format (args .dataset )))
502- elif 'retina' in args .model :
503- utils .save_on_master ({
504- 'model' : task_model .state_dict (), 'args' : args },
505- os .path .join (args .first_checkpoint_path , '{}_retinanet_1st.pth' .format (args .dataset )))
511+ # if not args.skip and cycle == 0:
512+ # if 'faster' in args.model:
513+ # utils.save_on_master({
514+ # 'model': task_model.state_dict(), 'args': args},
515+ # os.path.join(args.first_checkpoint_path, '{}_frcnn_1st.pth'.format(args.dataset)))
516+ # elif 'retina' in args.model:
517+ # utils.save_on_master({
518+ # 'model': task_model.state_dict(), 'args': args},
519+ # os.path.join(args.first_checkpoint_path, '{}_retinanet_1st.pth'.format(args.dataset)))
506520 random .shuffle (unlabeled_set )
507521 if 'coco' in args .dataset :
508- subset = unlabeled_set [:10000 ]
522+ subset = unlabeled_set [:5000 ]
509523 else :
510524 subset = unlabeled_set
511525 print ("Getting stability" )
512526 if args .mutual :
513527 unlabeled_loader = DataLoader (dataset_aug , batch_size = 1 , sampler = SubsetSequentialSampler (subset ),
514528 num_workers = args .workers , pin_memory = True , collate_fn = utils .collate_fn )
515529 uncertainty , _cls_corrs = get_uncertainty (task_model , unlabeled_loader , augs , num_classes )
530+ labeled_loader = DataLoader (dataset_aug , batch_size = 1 , sampler = SubsetSequentialSampler (labeled_set ),
531+ num_workers = args .workers , pin_memory = True , collate_fn = utils .collate_fn )
532+ # u, _ = get_uncertainty(task_model, labeled_loader, augs, num_classes)
533+ # with open("vis/cal_labeled_metric_{}_{}_{}.pkl".format(args.model, args.dataset, cycle),
534+ # "wb") as fp: # Pickling
535+ # pickle.dump(u, fp)
516536 arg = np .argsort (np .array (uncertainty ))
537+ # with open("vis/cal_unlabeled_metric_{}_{}_{}.pkl".format(args.model, args.dataset, cycle),
538+ # "wb") as fp: # Pickling
539+ # pickle.dump(torch.tensor(uncertainty)[arg][:budget_num].numpy(), fp)
517540 cls_corrs_set = arg [:int (args .mr * budget_num )]
518541 cls_corrs = [_cls_corrs [i ] for i in cls_corrs_set ]
519542 labeled_loader = DataLoader (dataset_aug , batch_size = 1 , sampler = SubsetSequentialSampler (labeled_set ),
@@ -522,8 +545,8 @@ def main(args):
522545 # Update the labeled dataset and the unlabeled dataset, respectively
523546 tobe_labeled_set = list (torch .tensor (subset )[arg ][tobe_labeled_set ].numpy ())
524547 labeled_set += tobe_labeled_set
525- with open ("vis/cal_{}_{}_{}.txt" .format (args .model , args .dataset , cycle ), "wb" ) as fp : # Pickling
526- pickle .dump (labeled_set , fp )
548+ # with open("vis/cal_{}_{}_{}.txt".format(args.model, args.dataset, cycle), "wb") as fp: # Pickling
549+ # pickle.dump(labeled_set, fp)
527550 unlabeled_set = list (set (indices ) - set (labeled_set ))
528551 else :
529552 unlabeled_loader = DataLoader (dataset_aug , batch_size = 1 , sampler = SubsetSequentialSampler (subset ),
@@ -532,6 +555,7 @@ def main(args):
532555 arg = np .argsort (np .array (uncertainty ))
533556 # Update the labeled dataset and the unlabeled dataset, respectively
534557 labeled_set += list (torch .tensor (subset )[arg ][:budget_num ].numpy ())
558+ labeled_set = list (set (labeled_set ))
535559 unlabeled_set = list (set (indices ) - set (labeled_set ))
536560 # Create a new dataloader for the updated labeled dataset
537561 train_sampler = SubsetRandomSampler (labeled_set )
0 commit comments