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

标签 python entity metrics spacy named-entity-recognition

在 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

平均/总计 0.809 0.787 0.796 6178

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

谢谢!

最佳答案

好问题。

首先,我们应该澄清一下,spaCy 使用的是 BILUO 注释方案,而不是您所指的 BIO 注释方案。 来自空间documentation这些字母表示以下内容:

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

然后,一些定义:

definitions

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)

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

希望对您有所帮助:)

关于python - spaCy 的 NER 有没有办法计算每个实体类型的指标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52856057/

相关文章:

python - 分形的 3D 动画

metrics - 具有相关值(value)的有趣软件指标

python - Cython 对导入做了什么?

python - 如何让 scrapy 跟随由 javascript 生成的 url?

python - 日期和时间对应于Python中的时间零

php - Symfony2 Doctrine 从类别中获取随机产品

java - JPA illegalStateException - CascadeType 问题

domain-driven-design - 领域驱动设计中跨界上下文的实体

oop - 度量和面向对象编程

java - 分析 Java 应用程序的 CPU 缓存性能的工具?