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
| ''' code taken from github repo detr , 'code present in engine.py' ''' matcher = HungarianMatcher(cost_giou=2,cost_class=1,cost_bbox=5) weight_dict = {'loss_ce': 1, 'loss_bbox': 5 , 'loss_giou': 2} losses = ['labels', 'boxes', 'cardinality']
def collate_fn(batch): return tuple(zip(*batch))
def get_fold(fold): train_indexes = train_ds.get_indices([x for i,f in enumerate(fold_indexes) if i!=fold for x in f]) valid_indexes = valid_ds.get_indices(fold_indexes[fold]) train_data_loader = DataLoader( torch.utils.data.Subset(train_ds,train_indexes), batch_size=BATCH_SIZE, shuffle=True, num_workers=2, collate_fn=collate_fn )
valid_data_loader = DataLoader( torch.utils.data.Subset(valid_ds,valid_indexes), batch_size=BATCH_SIZE, shuffle=False, num_workers=2, collate_fn=collate_fn ) return train_data_loader,valid_data_loader
train_loader,valid_loader = get_fold(0) valid_iter = iter(valid_loader) batch = next(valid_iter) images,targets,image_id = batch torch.cat([v['boxes'] for v in targets])
import util.box_ops as box_ops
def challenge_metric(outputs,targets): logits = outputs['pred_logits'] boxes = outputs['pred_boxes'] return sum(avg_precision(logit[:,0]-logit[:,1],box,target['boxes']) for logit,box,target in zip(logits,boxes,targets))/len(logits)
return {target['image_id']:avg_precision(logit[:,0]-logit[:,1],box,target['boxes']) for logit,box,target in zip(logits,boxes,targets)}
@torch.no_grad() def avg_precision(logit,pboxes,tboxes,reduce=True): idx = logit.gt(0) if sum(idx)==0 and len(tboxes)==0: return 1 if reduce else [1]*6 if sum(idx)>0 and len(tboxes)==0: return 0 if reduce else [0]*6 pboxes = pboxes[idx] logit = logit[idx] idx = logit.argsort(descending=True) pboxes=box_ops.box_cxcywh_to_xyxy(pboxes.detach()[idx]) tboxes=box_ops.box_cxcywh_to_xyxy(tboxes) iou = box_ops.box_iou(pboxes,tboxes)[0].cpu().numpy() prec = [precision(iou,th) for th in [0.5,0.55,0.6,0.65,0.7,0.75]] if reduce: return sum(prec)/6 return prec
def precision(iou,th):
tp = 0 iou = iou.copy() num_pred,num_gt = iou.shape for i in range(num_pred): _iou = iou[i] n_hits = (_iou>th).sum() if n_hits>0: tp += 1 j = np.argmax(_iou) iou[:,j] = 0 return tp/(num_pred+num_gt-tp) def gen_box(n,scale=1): par = torch.randn((n,4)).mul(scale).sigmoid() max_hw = 2*torch.min(par[:,:2],1-par[:,:2]) par[:,2:] = par[:,2:].min(max_hw) return par
pboxes = gen_box(50) logit = torch.randn(50) tboxes = gen_box(3) avg_precision(logit,pboxes,tboxes)
|