有没有办法用spaCy的NER来计算每个实体类型的指标?

ln *_* pi 8 python metrics entity spacy ner

有没有办法在spaCy的NER模型中提取每个实体类型的指标(精确度,召回率,f1得分)?

看起来像这样的东西:

         precision    recall  f1-score   support

  B-LOC      0.810     0.784     0.797      1084
  I-LOC      0.690     0.637     0.662       325
 B-MISC      0.731     0.569     0.640       339
 I-MISC      0.699     0.589     0.639       557
  B-ORG      0.807     0.832     0.820      1400
  I-ORG      0.852     0.786     0.818      1104
  B-PER      0.850     0.884     0.867       735
  I-PER      0.893     0.943     0.917       634
Run Code Online (Sandbox Code Playgroud)

平均/总计0.809 0.787 0.796 6178

取自:http://www.davidsbatista.net/blog/2018/05/09/Named_Entity_Evaluation/

谢谢!

gda*_*ras 6

好问题。

首先,我们应该澄清一下,spaCy 使用的是 BILUO 注释方案,而不是您所指的 BIO 注释方案。从 spacy文档中,这些字母表示以下内容:

  • B:多令牌实体的第一个令牌。
  • I:多令牌实体的内部令牌。
  • L:多令牌实体的最终令牌。
  • U:单令牌实体。
  • O:非实体令牌。

然后,一些定义:

定义

Spacy 有一个内置的类来评估 NER。它被称为得分手。Scorer 使用精确匹配来评估 NER。精度分数作为 ents_p 返回,召回作为 ents_r 和 F1 分数作为 ents_f。

唯一的问题是它返回文档中所有标签的分数。但是,我们只能使用我们想要的 TAG 调用该函数并获得所需的结果。

总之,代码应该是这样的:

import spacy
from spacy.gold import GoldParse
from spacy.scorer import Scorer

def evaluate(nlp, examples, ent='PERSON'):
    scorer = Scorer()
    for input_, annot in examples:
        text_entities = []
        for entity in annot.get('entities'):
            if ent in entity:
                text_entities.append(entity)
        doc_gold_text = nlp.make_doc(input_)
        gold = GoldParse(doc_gold_text, entities=text_entities)
        pred_value = nlp(input_)
        scorer.score(pred_value, gold)
    return scorer.scores


examples = [
    ("Trump says he's answered Mueller's Russia inquiry questions \u2013 live",{"entities":[[0,5,"PERSON"],[25,32,"PERSON"],[35,41,"GPE"]]}),
    ("Alexander Zverev reaches ATP Finals semis then reminds Lendl who is boss",{"entities":[[0,16,"PERSON"],[55,60,"PERSON"]]}),
    ("Britain's worst landlord to take nine years to pay off string of fines",{"entities":[[0,7,"GPE"]]}),
    ("Tom Watson: people's vote more likely given weakness of May's position",{"entities":[[0,10,"PERSON"],[56,59,"PERSON"]]}),
]

nlp = spacy.load('en_core_web_sm')
results = evaluate(nlp, examples)
print(results)
Run Code Online (Sandbox Code Playgroud)

使用适当的 ent 参数调用评估函数以获取每个标签的结果。

希望能帮助到你 :)


R.K*_*.K. 6

从 spacy v3 开始,

#测试模型

import spacy
from spacy.training.example import Example

nlp = spacy.load("./model_saved")
examples = []
data = [("Taj mahal is in Agra.", {"entities": [(0, 9, 'name'),
(16, 20, 'place')]})]
for text, annots in data:
    doc = nlp.make_doc(text)
    examples.append(Example.from_dict(doc, annots))
print(nlp.evaluate(examples)) # This will provide overall and per entity metrics
Run Code Online (Sandbox Code Playgroud)


ElB*_*ulP 5

我一直在致力于此,现在通过Pull Request将其与 spacy 集成。

现在您只需要调用Scorer().scores,它将返回带有附加键的常用字典,ents_per_type该键将包含每个实体的精度、召回率和 F1-Score 指标。

希望能帮助到你!