File size: 982 Bytes
ef987bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import csv

rows = list(csv.DictReader(open('test.csv', encoding='utf-8-sig')))
def f1_at(threshold):
    tp = fp = fn = 0
    for row in rows:
        pred_clear = float(row['score']) >= threshold
        actual_clear = row['label'].strip().lower() == 'clear'
        tp += bool(pred_clear and actual_clear)
        fp += bool(pred_clear and not actual_clear)
        fn += bool((not pred_clear) and actual_clear)
    precision = tp / (tp + fp) if tp + fp else 0
    recall = tp / (tp + fn) if tp + fn else 0
    return 2 * precision * recall / (precision + recall) if precision + recall else 0
thresholds = sorted({float(r['score']) for r in rows})
best_threshold, best_f1 = max(((t, f1_at(t)) for t in thresholds), key=lambda x: x[1])
open('threshold_report.txt', 'w', encoding='utf-8').write(
    f'Optimal threshold: {best_threshold:.3f}\nF1 score: {best_f1:.3f}\n'
)

import json
open('threshold_metrics.json','w').write(json.dumps({'threshold':best_threshold,'f1':best_f1}))