File size: 2,766 Bytes
9126e0d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Score only complete independent human labels; never fill missing labels."""
from pathlib import Path
import argparse,csv,json,collections
FIELDS=['representable','decomposition_correct','ambiguity']
def read(p):
    with Path(p).open(newline='') as f:rows=list(csv.DictReader(f))
    assert len({r['id'] for r in rows})==len(rows),'duplicate ids'
    return {r['id']:r for r in rows}
def main():
    a=argparse.ArgumentParser();a.add_argument('--a',required=True);a.add_argument('--b',required=True);a.add_argument('--key',required=True);a.add_argument('--adjudicated');a.add_argument('--output',required=True);p=a.parse_args()
    aa,bb=read(p.a),read(p.b);key={r['id']:r for r in json.loads(Path(p.key).read_text())}
    assert aa.keys()==bb.keys()==key.keys(),'unaligned forms'
    missing=[(i,f) for i in key for f in FIELDS if aa[i][f] not in ['0','1'] or bb[i][f] not in ['0','1']]
    if missing:
        report=dict(status='INCOMPLETE',items=len(key),missing_or_unresolved_fields=len(missing),reason='Human 0/1 labels required; no statistics estimated.')
    else:
        agreement={}
        for field in FIELDS:
            x=[int(aa[i][field]) for i in key];y=[int(bb[i][field]) for i in key];n=len(x);po=sum(a==b for a,b in zip(x,y))/n;px=sum(x)/n;py=sum(y)/n;pe=px*py+(1-px)*(1-py)
            agreement[field]=dict(raw_agreement=po,kappa=(po-pe)/(1-pe) if pe<1 else None,scope='unweighted stratified audit sample')
        disagreements=[i for i in key if any(aa[i][f]!=bb[i][f] for f in FIELDS)]
        report=dict(status='AWAITING_ADJUDICATION',agreement=agreement,disagreement_ids=disagreements)
        if p.adjudicated:
            gold=read(p.adjudicated);assert gold.keys()==key.keys()
            assert all(gold[i][f] in ['0','1'] for i in key for f in FIELDS),'unresolved adjudication'
            counts=collections.defaultdict(float)
            for i,k in key.items():
                pred=bool(k['accepted']);truth=gold[i]['representable']=='1';weight=k['weight'];counts[('T' if pred==truth else 'F')+('P' if pred else 'N')]+=weight
            tp,fp,tn,fn=[counts[k] for k in ['TP','FP','TN','FN']]
            ratio=lambda a,b:a/b if b else None
            report.update(status='COMPLETE',weighted_counts=dict(counts),precision=ratio(tp,tp+fp),recall=ratio(tp,tp+fn),false_acceptance_rate=ratio(fp,fp+tn),false_rejection_rate=ratio(fn,tp+fn),target='semantic representability under documented grammar',decomposition_precision_among_accepted=ratio(sum(key[i]['weight'] for i in key if key[i]['accepted'] and gold[i]['decomposition_correct']=='1'),sum(key[i]['weight'] for i in key if key[i]['accepted'])))
    Path(p.output).write_text(json.dumps(report,indent=2));print(json.dumps(report,indent=2))
if __name__=='__main__':main()