File size: 9,360 Bytes
5e56f2f |
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 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 |
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('<e>.*</e>',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('<e>.*</e>',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('<e>.*</e>',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()
|