"""Validation-only threshold selection and full test evaluation at native resolution.""" import argparse,csv,json,time from pathlib import Path import numpy as np from PIL import Image from scipy.ndimage import label import torch from torch.nn import functional as F from torch.utils.data import DataLoader from segmentation import ResUNet,Frames from prepare_data import read_manifest,mask_array def clean_mask(prob,threshold,min_ratio): mask=prob>=threshold;components,n=label(mask) counts=np.bincount(components.ravel());keep=np.where(counts>=max(1,int(np.ceil(min_ratio*mask.size))))[0] keep=keep[keep!=0];return np.isin(components,keep) def geometry(mask): ys,xs=np.where(mask);h,w=mask.shape if not len(xs):return dict(present=False,coverage_pct=0.0,location='none',bbox=None,centroid=None,component_count=0) cx,cy=float(xs.mean()/w),float(ys.mean()/h) loc=['upper','middle','lower'][min(2,int(cy*3))]+'-'+['left','centre','right'][min(2,int(cx*3))] return dict(present=True,coverage_pct=round(100*len(xs)/mask.size,3),location=loc, bbox=[int(xs.min()),int(ys.min()),int(xs.max()+1),int(ys.max()+1)],centroid=[cx,cy],component_count=int(label(mask)[1])) def image_metrics(pred,truth): tp=int((pred&truth).sum());fp=int((pred&~truth).sum());fn=int((~pred&truth).sum());tn=int((~pred&~truth).sum()) positive=truth.any();present=pred.any();dice=2*tp/(2*tp+fp+fn) if positive else None iou=tp/(tp+fp+fn) if positive else None gt,pr=geometry(truth),geometry(pred) dist=float(np.linalg.norm(np.array(gt['centroid'])-pr['centroid'])) if positive and present else None return dict(positive=int(positive),predicted_positive=int(present),tp=tp,fp=fp,fn=fn,tn=tn,dice=dice,iou=iou, pixel_recall=tp/(tp+fn) if positive else None,area_mae_pp=abs(gt['coverage_pct']-pr['coverage_pct']), centroid_error_norm=dist,location_correct=int(gt['location']==pr['location']) if positive else None, localized=int(iou>=.1) if positive else None,truth_geometry=gt,predicted_geometry=pr) def summary(rows): pos=[r for r in rows if r['positive']];neg=[r for r in rows if not r['positive']] mean=lambda key:float(np.mean([r[key] for r in rows if r[key] is not None])) if any(r[key] is not None for r in rows) else None return dict(n=len(rows),positive_n=len(pos),negative_n=len(neg),positive_dice=mean('dice'),positive_iou=mean('iou'), positive_pixel_recall=mean('pixel_recall'),presence_sensitivity=float(np.mean([r['predicted_positive'] for r in pos])) if pos else None, specificity=float(np.mean([1-r['predicted_positive'] for r in neg])) if neg else None, negative_frame_fpr=float(np.mean([r['predicted_positive'] for r in neg])) if neg else None, localization_recall_iou_0_1=float(np.mean([r['localized'] for r in pos])) if pos else None, area_mae_pp=mean('area_mae_pp'),positive_area_mae_pp=float(np.mean([r['area_mae_pp'] for r in pos])) if pos else None, negative_predicted_area_pct=float(np.mean([r['predicted_geometry']['coverage_pct'] for r in neg])) if neg else None, centroid_error_norm=mean('centroid_error_norm'),location_accuracy=mean('location_correct')) def confidence_intervals(rows,repeats=1000): groups={} for r in rows:groups.setdefault(r['group'],[]).append(r) keys=sorted(groups);rng=np.random.default_rng(4601);values={k:[] for k in ['positive_dice','presence_sensitivity','specificity','localization_recall_iou_0_1','area_mae_pp']} for _ in range(repeats): sampled=[row for k in rng.choice(keys,size=len(keys),replace=True) for row in groups[k]] s=summary(sampled) for key in values: if s[key] is not None:values[key].append(s[key]) return {k:np.percentile(v,[2.5,97.5]).tolist() if v else None for k,v in values.items()} @torch.no_grad() def infer(model,rows,size,batch,device): loader=DataLoader(Frames(rows,size),batch_size=batch,num_workers=0) probs=[] for x,_ in loader: with torch.autocast(device_type=device,dtype=torch.float16,enabled=device=='cuda'):y=model(x.to(device)).sigmoid().float().cpu().numpy()[:,0] probs.extend(y) return probs def main(): ap=argparse.ArgumentParser();ap.add_argument('--manifest',default='artifacts/data/manifest.csv');ap.add_argument('--checkpoint',default='artifacts/segmentation/best.pt') ap.add_argument('--out',type=Path,default=Path('artifacts/evaluation'));ap.add_argument('--batch',type=int,default=16) args=ap.parse_args();args.out.mkdir(parents=True,exist_ok=True);torch.set_num_threads(4) rows=read_manifest(args.manifest);device='cuda' if torch.cuda.is_available() else 'cpu';ckpt=torch.load(args.checkpoint,map_location='cpu',weights_only=True) model=ResUNet().to(device);model.load_state_dict(ckpt['model']);model.eval();size=ckpt['size'] val=[r for r in rows if r['split']=='val'];probs=infer(model,val,size,args.batch,device);truths=[] for r in val: im=Image.open(r['mask']).convert('L').resize((size,size),Image.Resampling.NEAREST) if r['mask'] else Image.new('L',(size,size)) truths.append(np.asarray(im)>127) candidates=[] for threshold in [.3,.4,.5,.6,.7]: for ratio in [.0005,.001,.002,.005,.01]: m=[image_metrics(clean_mask(p,threshold,ratio),t) for p,t in zip(probs,truths)];s=summary(m) score=(s['presence_sensitivity']+s['specificity'])/2 candidates.append(dict(pixel_threshold=threshold,min_component_ratio=ratio,balanced_accuracy=score,**s)) selected=max(candidates,key=lambda c:(c['balanced_accuracy'],c['positive_dice'])) settings={'pixel_threshold':selected['pixel_threshold'],'min_component_ratio':selected['min_component_ratio'], 'selection':'Maximize validation balanced accuracy, break ties by positive Dice. No test data used.', 'validation':selected} (args.out/'thresholds.json').write_text(json.dumps(settings,indent=2));(args.out/'threshold_search.json').write_text(json.dumps(candidates,indent=2)) evaluation=[r for r in rows if r['split'] in ['test','external']];probabilities=infer(model,evaluation,size,args.batch,device) results=[] mask_dir=args.out/'predicted_masks';mask_dir.mkdir(exist_ok=True) for i,(row,prob) in enumerate(zip(evaluation,probabilities)): w,h=int(row['width']),int(row['height']) native=F.interpolate(torch.tensor(prob)[None,None],size=(h,w),mode='bilinear',align_corners=False)[0,0].numpy() pred=clean_mask(native,settings['pixel_threshold'],settings['min_component_ratio']);truth=mask_array(row['mask'],(w,h)) mask_path=mask_dir/(row['id']+'.png');Image.fromarray(pred.astype(np.uint8)*255).save(mask_path) metrics=image_metrics(pred,truth);results.append({**row,**metrics,'predicted_mask':mask_path.as_posix()}) if (i+1)%500==0:print('Native-resolution evaluation',i+1,'/',len(evaluation),flush=True) groups={} for r in results: key=r['dataset']+(f"_C{r['center']}" if r['dataset']=='PolypGen' else '') groups.setdefault(key,[]).append(r) report={key:{**summary(group),'cluster_bootstrap_95ci':confidence_intervals(group)} for key,group in groups.items()} report['definitions']={'geometry':'Native-resolution binary mask; image area percentage is not millimeters; disconnected components are not a validated polyp count.', 'presence_sensitivity':'Any retained predicted component on a positive frame, regardless of overlap.', 'localization_recall_iou_0_1':'Positive frame with total-mask IoU >= 0.1.', 'uncertainty':'1000 cluster-bootstrap resamples; sequences are clusters, still images are singleton clusters; not patient-level confidence intervals.'} (args.out/'segmentation_results.json').write_text(json.dumps(report,indent=2)) with (args.out/'per_image.jsonl').open('w') as f: for r in results:f.write(json.dumps(r)+'\n') print(json.dumps(report,indent=2),flush=True) if __name__=='__main__':main()