近期在学习NER(命名实体识别)的做法。在评价模型的指标上,因为其任务的特殊行性,没有发现off-the-shelf的函数。于是就自己实现了一个Exact-match Evaluation。
使用字典来保存实体提及,查询更快。对一个标签序列只需遍历一遍即可找到所有的实体。时间复杂度为O(N)
def find_entity(seq, start2end):
i, n = 0, len(seq)
res = {}
while i < n:
if seq[i] in start2end: #若当前为起始标签则进入循环找到这个实体提及的终止位置
start = i
while i + 1 < n and seq[i+1] == start2end[seq[start]]:
i += 1
end = i
res[start] = (end, seq[start]) #以起点位置当索引,不会产生冲突
elif seq[i] == label2id['O']: #若当前为O 则不寻找终止 只保存类型
res[i] = label2id['O']
i += 1
return res
seq为标签序列,start2end为标签对,如B-Loc表示为0, I-LOC表示为5, 则标签对为{0:5}
返回的res为标签序列中以开始位置为索引的所有实体提及
def find_match(predict, target):
match = 0
target_entity = find_entity(target)
predict_entity = find_entity(predict)
for i, j in target_entity.items():
if i in predict_entity:
if j == predict_entity[i]:
match += 1
return match
predict为模型预测序列,target为gold-truth。
因为exact-match要求开始终止位置和类型都一样,所有直接比较元组是否相等即可。
返回的match即为预测正确实体提及,可以直接用来计算P,R,F1