import os import json import re import sklearn import collections from sklearn.metrics import f1_score,accuracy_score def get_f1(samples): gold,pred = [],[] for sample in samples: if sample['gold'] in sample['pred']: gold.append(sample['gold']) pred.append(sample['gold']) else: gold.append(sample['gold']) pred.append(sample['pred']) micro_f1 = f1_score(gold,pred,average='micro') macro_f1 = f1_score(gold,pred,average='macro') print(f"Micro-F1: {micro_f1:.4f}") print(f"Macro-F1: {macro_f1:.4f}") return micro_f1, macro_f1 def get_cls_acc(samples): gold,pred = [],[] for sample in samples: if sample['gold'] in sample['pred']: gold.append(sample['gold']) pred.append(sample['gold']) else: gold.append(sample['gold']) pred.append(sample['pred']) pool = {} for g,p in zip(gold,pred): if g not in pool.keys(): pool[g] = {'g':[],'p':[]} pool[g]['g'].append(g) pool[g]['p'].append(p) result = {} counter = {} for k,v in pool.items(): g,p = v['g'],v['p'] acc = accuracy_score(g,p) result[k] = acc counter[k] = len(g) result = sorted([(k,v,counter[k]) for k,v in result.items()],key=lambda x:x[2],reverse=True) #_result = [r for r in result if r[1] > 0] _result = [r for r in result][:20] import pandas as pd prob = [r[1] for r in result] number = [r[2] for r in result] crime = [r[0] for r in result] data = {'crime':crime,'prob':prob,'number':number} df = pd.DataFrame(data) df.to_excel('./output/eval/lawbench.xlsx',index=False) for r in result: k,v = r[0],r[1] print('{x} : {y}'.format(x=k,y=v)) print(accuracy_score(gold,pred)) def get_bias_with_acc(samples): def load_result(path): samples = [] samples_with_tag = [] with open(path,'r') as f: for l in f.readlines(): line = json.loads(l) y = line['y'] y_ = line['pred'] if line['pred'] else '' y = [s[3:-4] for s in y.split(';')] for c in y: samples.append({'gold':c,'pred':y_[3:-4]}) if re.search('.*',y_): samples_with_tag.append({'gold':c,'pred':y_}) return samples def get_acc_in_cls(samples): gold,pred = [],[] for sample in samples: if sample['gold'] in sample['pred']: gold.append(sample['gold']) pred.append(sample['gold']) else: gold.append(sample['gold']) pred.append(sample['pred']) pool = {} for g,p in zip(gold,pred): if g not in pool.keys(): pool[g] = {'g':[],'p':[]} pool[g]['g'].append(g) pool[g]['p'].append(p) result = {} counter = {} for k,v in pool.items(): g,p = v['g'],v['p'] acc = accuracy_score(g,p) result[k] = acc counter[k] = len(g) import numpy result = sorted([(k,v,numpy.log(counter[k]/len(gold))) for k,v in result.items()],key=lambda x:x[2],reverse=True) return result zeroshot = load_result('') oneshot = load_result('') cot = load_result('') our = load_result('') zeroshot = get_acc_in_cls(zeroshot) oneshot = get_acc_in_cls(oneshot) cot = get_acc_in_cls(cot) our = get_acc_in_cls(our) crimes = {c[0]:c[-1] for c in zeroshot} crimes_pool = [] log = [] acc_zero = [] acc_one = [] acc_cot = [] acc_our = [] for c,crime in crimes.items(): crimes_pool.append(c) log.append(crime) for i,s in enumerate(zeroshot): if c in s[0]: acc_zero.append(s[1]) break if i == len(zeroshot) and c not in s[0]: raise ValueError for i,s in enumerate(oneshot): if c in s[0]: acc_one.append(s[1]) break if i == len(oneshot) and c not in s[0]: raise ValueError if len(acc_one) < len(acc_zero): acc_one.append(0) for i,s in enumerate(cot): if c in s[0]: acc_cot.append(s[1]) break if i == len(cot) and c not in s[0]: raise ValueError for i,s in enumerate(our): if c in s[0]: acc_our.append(s[1]) break if i == len(our) and c not in s[0]: raise ValueError import pandas as pd idx = [i for i in range(len(crimes_pool))] data = {'crime':crimes_pool,'prob':log,'zs':acc_zero,'os':acc_one,'ct':acc_cot,'our':acc_our,'id':idx} df = pd.DataFrame(data) df.to_excel('',index=False) def get_effect_with_f1(): def load_result(path): samples = [] samples_with_tag = [] with open(path,'r') as f: for l in f.readlines(): line = json.loads(l) y = line['y'] y_ = line['pred'] if line['pred'] else '' y = [s[3:-4] for s in y.split(';')] for c in y: #crimes_counter[c] += 1 samples.append({'gold':c,'pred':y_[3:-4]}) if re.search('.*',y_): samples_with_tag.append({'gold':c,'pred':y_}) return samples, samples_with_tag dzeroshot,dzeroshottag = load_result('') dzeromi,dzeroma = get_f1(dzeroshot) d_zeromi,d_zeroma = get_f1(dzeroshottag) doneshot,doneshottag = load_result('') donemi,donema = get_f1(doneshot) d_onemi,d_onema = get_f1(doneshottag) dcotshot,dcotshottag = load_result('') dcotmi,dcotma = get_f1(dcotshot) d_cotmi,d_cotma = get_f1(dcotshottag) dourshot,dourshottag = load_result('') dourmi,dourma = get_f1(dourshot) d_ourmi,d_ourma = get_f1(dourshottag) zeroshot,zeroshottag = load_result('') zeromi,zeroma = get_f1(zeroshot) _zeromi,_zeroma = get_f1(zeroshottag) oneshot,oneshottag = load_result('') onemi,onema = get_f1(oneshot) _onemi,_onema = get_f1(oneshottag) cotshot,cotshottag = load_result('') cotmi,cotma = get_f1(cotshot) _cotmi,_cotma = get_f1(cotshottag) ourshot,ourshottag = load_result('') ourmi,ourma = get_f1(ourshot) _ourmi,_ourma = get_f1(ourshottag) # mi acc_zero_effect = (dzeromi - zeromi) / (dzeromi - zeromi) acc_one_effect = (donemi - zeromi) / (dzeromi - zeromi) acc_cot_effect = (dcotmi - zeromi) / (dzeromi - zeromi) acc_our_effect = (dourmi - zeromi) / (dzeromi - zeromi) # ma acc_zero_effect = (dzeroma - zeroma) / (dzeroma - zeroma) acc_one_effect = (donema - zeroma) / (dzeroma - zeroma) acc_cot_effect = (dcotma - zeroma) / (dzeroma - zeroma) acc_our_effect = (dourma - zeroma) / (dzeroma - zeroma) print(acc_zero_effect) print(acc_one_effect) print(acc_cot_effect) print(acc_our_effect) def crime_topk_acc(samples,crimes=None,name='deepseek'): gold,pred = [],[] for sample in samples: if sample['gold'] in sample['pred']: gold.append(sample['gold']) pred.append(sample['gold']) else: gold.append(sample['gold']) pred.append(sample['pred']) pool = {} for g,p in zip(gold,pred): if g not in pool.keys(): pool[g] = {'g':[],'p':[]} pool[g]['g'].append(g) pool[g]['p'].append(p) if crimes is None: crimes = {k:i for i,k in enumerate(pool.keys())} #counter = {} result = {} for k,v in pool.items(): counter = collections.Counter() g,p = v['g'],v['p'] for pi in p: counter[pi] += 1 for c in crimes: if c not in counter.keys(): counter[c] = 0 result[k] = [counter[c] for c in crimes] import pandas as pd df = pd.DataFrame(result) df.to_excel('./output/eval/warm_acc_{x}.xlsx'.format(x=name),index=False) return result,crimes def main(): path = '' def load_data(path): crimes_counter = collections.Counter() samples = [] samples_with_tag = [] with open(path,'r') as f: for l in f.readlines(): line = json.loads(l) y = line['y'] y_ = line['pred'] if line['pred'] else '' y = [s[3:-4] for s in y.split(';')] for c in y: crimes_counter[c] += 1 samples.append({'gold':c,'pred':y_[3:-4]}) if re.search('.*',y_): samples_with_tag.append({'gold':c,'pred':y_}) return samples,samples_with_tag samples,samples_with_tag = load_data(path) print('/'.join(path.split('/')[-2:])) get_f1(samples) print('-'*30) get_f1(samples_with_tag) print('-'*30) get_cls_acc(samples) print('-'*30) get_bias_with_acc(samples) if __name__ =='__main__': main()