gpt4 book ai didi

nlp - 仅来自 PhraseMatcher 的 Spacy 实体

转载 作者:行者123 更新时间:2023-12-03 18:35:26 26 4
gpt4 key购买 nike

我将 Spacy 用于 NLP 项目。我有一个要标记为新实体类型的短语列表。我最初尝试训练 NER 模型,但由于术语列表有限,我认为仅使用 Matcher 应该更容易。我在 documentation 中看到您可以基于匹配器将实体添加到文档中。我的问题是:我如何为 实体执行此操作,并且没有 NER 管道将任何其他标记标记为该实体?理想情况下,只有通过我的匹配器找到的 token 应该被标记为实体,但我需要将它作为标签添加到 NER 模型中,然后最终将一些标记为实体。

关于如何最好地实现这一目标的任何建议?谢谢!

最佳答案

我想你可能想要实现类似于 this example 的东西——即使用 PhraseMatcher 并分配实体的 custom pipeline component。 spaCy 的内置实体识别器也只是一个管道组件 - 因此您可以将其从管道中删除并添加您的自定义组件:

nlp = spacy.load('en')               # load some model
nlp.remove_pipe('ner') # remove the entity recognizer
entity_matcher = EntityMatcher(nlp) # use your own entity matcher component
nlp.add_pipe(entity_matcher) # add it to the pipeline

您的实体匹配器组件可能如下所示:
from spacy.matcher import PhraseMatcher
from spacy.tokens import Span

class EntityMatcher(object):
name = 'entity_matcher'

def __init__(self, nlp, terms, label):
patterns = [nlp(term) for term in terms]
self.matcher = PhraseMatcher(nlp.vocab)
self.matcher.add(label, None, *patterns)

def __call__(self, doc):
matches = self.matcher(doc)
spans = []
for label, start, end in matches:
span = Span(doc, start, end, label=label)
spans.append(span)
doc.ents = spans
return doc

当您的组件初始化时,它会为您的术语创建匹配模式,并将它们添加到短语匹配器中。我的示例假设您有一个 terms 列表和一个要为这些术语分配的 label:
entity_matcher = EntityMatcher(nlp, your_list_of_terms, 'SOME_LABEL')
nlp.add_pipe(entity_matcher)

print(nlp.pipe_names) # see all components in the pipeline

当您对文本字符串调用 nlp 时,spaCy 将标记文本文本以创建 Doc 对象并按顺序调用 Doc 上的各个管道组件。您的自定义组件的 __call__ 方法然后在文档中查找匹配项,为每个匹配项创建 Span (允许您分配自定义标签),最后将它们添加到 doc.ents 属性并返回 Doc

您可以根据自己的喜好构建管道组件——例如,您可以扩展它以从文件加载到您的术语列表中,或者让它为不同的标签添加多个规则到 PhraseMatcher

关于nlp - 仅来自 PhraseMatcher 的 Spacy 实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49097804/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com