| import csv |
| import json |
| import re |
|
|
| def normalize(s): |
| return re.sub(r"\s+"," ",(s or "").strip().lower()) |
|
|
| def token_set(s): |
| s = normalize(s) |
| s = re.sub(r"[^a-z0-9\s]"," ",s) |
| return set([t for t in s.split(" ") if t]) |
|
|
| def jaccard(a,b): |
| ta, tb = token_set(a), token_set(b) |
| if not ta or not tb: |
| return 0.0 |
| return len(ta & tb)/len(ta | tb) |
|
|
| def load_refs(path): |
| refs={} |
| with open(path,encoding="utf-8") as f: |
| r=csv.DictReader(f) |
| for row in r: |
| refs[row["id"]] = row["gold_necessary_action"] |
| return refs |
|
|
| def score(pred_path,test_csv): |
| refs=load_refs(test_csv) |
| n=0 |
| correct=0 |
| sim_total=0 |
|
|
| with open(pred_path,encoding="utf-8") as f: |
| for line in f: |
| if not line.strip(): |
| continue |
| obj=json.loads(line) |
| ex_id=obj.get("id") |
| pred=obj.get("prediction","") |
| if ex_id not in refs: |
| continue |
| n+=1 |
| gold=refs[ex_id] |
| if normalize(pred)==normalize(gold): |
| correct+=1 |
| sim_total+=jaccard(pred,gold) |
|
|
| if n==0: |
| return {"final_score":0} |
|
|
| acc=correct/n |
| sim=sim_total/n |
| final=0.6*acc+0.4*sim |
|
|
| return { |
| "final_score":final, |
| "exact_accuracy":acc, |
| "similarity":sim, |
| "n":n |
| } |
|
|
| if __name__=="__main__": |
| import argparse |
| p=argparse.ArgumentParser() |
| p.add_argument("--predictions") |
| p.add_argument("--test_csv") |
| args=p.parse_args() |
| print(score(args.predictions,args.test_csv)) |
|
|