Spacy-NER模型中的计算

2024-03-28 13:06:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试评估使用spacy lib创建的训练有素的NER模型。 通常对于此类问题,可以使用f1分数(精确性和召回率之间的比率)。在文档中,我找不到一个经过训练的NER模型的精度函数。

我不确定它是否正确,但我试图用以下方法(示例)并使用f1_scorefrom sklearn来完成:

from sklearn.metrics import f1_score
import spacy
from spacy.gold import GoldParse


nlp = spacy.load("en") #load NER model
test_text = "my name is John" # text to test accuracy
doc_to_test = nlp(test_text) # transform the text to spacy doc format

# we create a golden doc where we know the tagged entity for the text to be tested
doc_gold_text= nlp.make_doc(test_text)
entity_offsets_of_gold_text = [(11, 15,"PERSON")]
gold = GoldParse(doc_gold_text, entities=entity_offsets_of_gold_text)

# bring the data in a format acceptable for sklearn f1 function
y_true = ["PERSON" if "PERSON" in x else 'O' for x in gold.ner]
y_predicted = [x.ent_type_ if x.ent_type_ !='' else 'O' for x in doc_to_test]
f1_score(y_true, y_predicted, average='macro')`[1]
> 1.0

任何想法或见解都是有用的。


Tags: thetotextintestimportfordoc
1条回答
网友
1楼 · 发布于 2024-03-28 13:06:52

对于在以下链接中有相同问题的人:

spaCy/scorer.py

您可以找到不同的度量标准,包括:fscore、recall和precision。 使用scorer的示例:

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

def evaluate(ner_model, examples):
    scorer = Scorer()
    for input_, annot in examples:
        doc_gold_text = ner_model.make_doc(input_)
        gold = GoldParse(doc_gold_text, entities=annot)
        pred_value = ner_model(input_)
        scorer.score(pred_value, gold)
    return scorer.scores

# example run

examples = [
    ('Who is Shaka Khan?',
     [(7, 17, 'PERSON')]),
    ('I like London and Berlin.',
     [(7, 13, 'LOC'), (18, 24, 'LOC')])
]

ner_model = spacy.load(ner_model_path) # for spaCy's pretrained use 'en_core_web_sm'
results = evaluate(ner_model, examples)

其中input_是文本(例如,“我的名字是约翰”),而annot是注释(例如。[(11,16,“人”)]

scorer.scores返回多个分数。示例取自spaCy example in github(链接不再工作)

相关问题 更多 >