python计算召回率_序列标注的准确率和召回率计算
最近在用BiLSTM+CRF做命名實(shí)體識(shí)別問(wèn)題。關(guān)于模型效果評(píng)估,很多提到用conlleval.pl來(lái)實(shí)現(xiàn),conlleval.pl是perl語(yǔ)言寫(xiě)的,原諒我沒(méi)看懂。最后還是決定自己寫(xiě)個(gè)程序算一算準(zhǔn)確率和召回率。
公式
準(zhǔn)確率 = 預(yù)測(cè)正確的實(shí)體個(gè)數(shù) / 預(yù)測(cè)的實(shí)體總個(gè)數(shù)
召回率 = 預(yù)測(cè)正確的實(shí)體個(gè)數(shù) / 標(biāo)注的實(shí)體總個(gè)數(shù)
F1 = 2 *準(zhǔn)確率 * 召回率 / (準(zhǔn)確率 + 召回率)
實(shí)現(xiàn)
1、獲取實(shí)體:包括預(yù)測(cè)的全部實(shí)體和標(biāo)注的全部實(shí)體
對(duì)于一個(gè)標(biāo)簽序列,例如:'B-PER', 'I-PER', 'O', 'B-PER', 'I-PER', 'O', 'O', 'B-LOC', 'I-LOC'
實(shí)體對(duì)應(yīng)的標(biāo)簽塊是指:從B開(kāi)頭標(biāo)簽開(kāi)始的,同一類型(PER/LOC/ORG)的,非O的連續(xù)標(biāo)簽序列
因此可以采用形如{(position, type): [label1, label2, ...]}這種格式的字典來(lái)存儲(chǔ)實(shí)體,其中position為實(shí)體起始標(biāo)簽對(duì)應(yīng)的序列下標(biāo)索引,type為實(shí)體對(duì)應(yīng)的類型,[label1, label2, ...]為實(shí)體對(duì)應(yīng)的標(biāo)簽序列
從標(biāo)簽序列中抽取實(shí)體的代碼如下:
def split_entity(label_sequence):
entity_mark = dict()
entity_pointer = None
for index, label in enumerate(label_sequence):
if label.startswith('B'):
category = label.split('-')[1]
entity_pointer = (index, category)
entity_mark.setdefault(entity_pointer, [label])
elif label.startswith('I'):
if entity_pointer is None: continue
if entity_pointer[1] != label.split('-')[1]: continue
entity_mark[entity_pointer].append(label)
else:
entity_pointer = None
return entity_mark
2、獲取預(yù)測(cè)正確的實(shí)體,進(jìn)而計(jì)算準(zhǔn)確率和召回率
得到標(biāo)注的全部實(shí)體和預(yù)測(cè)的全部實(shí)體后,這兩個(gè)字典中鍵和值均相等的元素,即為預(yù)測(cè)正確的實(shí)體。
統(tǒng)計(jì)標(biāo)注的實(shí)體總個(gè)數(shù)、預(yù)測(cè)的實(shí)體總個(gè)數(shù)、預(yù)測(cè)正確的實(shí)體總個(gè)數(shù),進(jìn)而可以計(jì)算出準(zhǔn)確率、召回率以及F1值。
代碼如下:
def evaluate(real_label, predict_label):
real_entity_mark = split_entity(real_label)
predict_entity_mark = split_entity(predict_label)
true_entity_mark = dict()
key_set = real_entity_mark.keys() & predict_entity_mark.keys()
for key in key_set:
real_entity = real_entity_mark.get(key)
predict_entity = predict_entity_mark.get(key)
if tuple(real_entity) == tuple(predict_entity):
true_entity_mark.setdefault(key, real_entity)
real_entity_num = len(real_entity_mark)
predict_entity_num = len(predict_entity_mark)
true_entity_num = len(true_entity_mark)
precision = true_entity_num / predict_entity_num
recall = true_entity_num / real_entity_num
f1 = 2 * precision * recall / (precision + recall)
return precision, recall, f1
補(bǔ)充
1、以上只簡(jiǎn)單計(jì)算了準(zhǔn)確率和召回率,沒(méi)有涉及到混淆和偏移等問(wèn)題。如有錯(cuò)誤和疏漏之處,請(qǐng)不吝指正。
2、代碼寫(xiě)完后,在github上發(fā)現(xiàn)了conlleval的python版本o(╯□╰)o,附鏈接如下:
總結(jié)
以上是生活随笔為你收集整理的python计算召回率_序列标注的准确率和召回率计算的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: delphi tabsheet多标签自适
- 下一篇: websocket python爬虫_p