Hsyshasuzh's picture
download
raw
3.95 kB
"""Validation-only precision-constrained thresholds, with explicit abstention."""
import math
from evaluation.calibrate_thresholds import _validate_selection_records
from evaluation.metrics import _match_class, evaluate_detection
def select_precision_policy(predictions, targets, *, target_precision=.99, min_predictions=30,
selection_ids=None, forbidden_ids=None):
if selection_ids is None:
if forbidden_ids is not None:raise ValueError('explicit selection IDs required')
_validate_selection_records(predictions, targets)
else:
allowed=set(selection_ids)
if forbidden_ids is None or not allowed or allowed & set(forbidden_ids) or any(not sid.startswith('dior_') for sid in allowed):
raise ValueError('disjoint explicit selection and forbidden IDs required')
for rows in (predictions,targets):
ids=[r['sample_id'] for r in rows]
if len(set(ids))!=len(ids) or set(ids)!=allowed or any(r.get('split')!='val' or r.get('provenance')!='selection_validation' for r in rows):
raise ValueError('exact reserved selection rows and validation provenance required')
if not math.isfinite(target_precision) or not 0 < target_precision <= 1:
raise ValueError('precision target must be in (0,1]')
if type(min_predictions) is not int or min_predictions < 1:
raise ValueError('positive minimum prediction count required')
ignored={r['sample_id']:r.get('ignored_annotations',[]) for r in targets}
support={};thresholds={};abstained=[]
for category in sorted({a['category_id'] for r in targets for a in r['annotations']}):
truth={r['sample_id']:[a for a in r['annotations'] if a['category_id']==category] for r in targets}
count=sum(len(v) for v in truth.values())
candidates=[(r['sample_id'],a) for r in predictions for a in r['annotations'] if a['category_id']==category]
scores,_,_=_match_class(candidates,truth,ignored,.5)
tp=0;kept=0;eligible=[]
# A threshold includes every prediction tied at that confidence.
for index,(score,matched) in enumerate(scores):
tp+=int(matched);kept+=1
if index+1 < len(scores) and scores[index+1][0]==score:continue
precision=tp/kept
if kept>=min_predictions and precision+1e-12>=target_precision:
eligible.append((tp,-kept,score,kept))
if eligible:
tp,_,threshold,kept=max(eligible)
thresholds[str(category)]=threshold
support[str(category)]={'status':'SUPPORTED_EMPIRICALLY','targets':count,'predictions':kept,
'tp':tp,'fp':kept-tp,'precision':tp/kept,'recall':tp/count if count else 0}
else:
abstained.append(category)
support[str(category)]={'status':'INSUFFICIENT_EVIDENCE_OR_NO_FEASIBLE_THRESHOLD','targets':count,
'predictions':0,'tp':0,'fp':0,'precision':None,'recall':0}
return {'target_precision':target_precision,'min_predictions':min_predictions,'thresholds':thresholds,
'abstained_class_ids':abstained,'support':support,'provenance':'selection_validation',
'sample_ids':sorted(r['sample_id'] for r in targets),
'limitation':'Empirical operating point, not a 99% guarantee. Minimum count is a support screen, not a confidence bound. Abstained classes remain false negatives in recall.'}
def apply_policy(predictions,policy):
return [{**r,'annotations':[a for a in r['annotations'] if a['category_id'] not in policy['abstained_class_ids']
and a['confidence'] >= policy['thresholds'][str(a['category_id'])]]} for r in predictions]
def score_policy(predictions,targets,policy):
metrics=evaluate_detection(apply_policy(predictions,policy),targets)
for row in [metrics,*metrics['per_class'].values()]:
row.pop('ap50',None);row.pop('map50_95',None)
return metrics

Xet Storage Details

Size:
3.95 kB
·
Xet hash:
cc6651ca4f962cf116b6d23dee485a9c9c46a04d05cae08c4840a367bb2788d2

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.