【发布时间】:2018-12-26 23:14:52
【问题描述】:
我正在尝试将自定义 PhraseMatcher() 组件集成到我的 nlp 管道中,这样我就可以加载自定义 Spacy 模型,而无需在每次加载时将自定义组件重新添加到通用模型中。
如何加载包含自定义管道组件的 Spacy 模型?
我创建组件,将其添加到我的管道并使用以下内容保存:
import requests
from spacy.lang.en import English
from spacy.matcher import PhraseMatcher
from spacy.tokens import Doc, Span, Token
class RESTCountriesComponent(object):
name = 'countries'
def __init__(self, nlp, label='GPE'):
self.countries = [u'MyCountry', u'MyOtherCountry']
self.label = nlp.vocab.strings[label]
patterns = [nlp(c) for c in self.countries]
self.matcher = PhraseMatcher(nlp.vocab)
self.matcher.add('COUNTRIES', None, *patterns)
def __call__(self, doc):
matches = self.matcher(doc)
spans = []
for _, start, end in matches:
entity = Span(doc, start, end, label=self.label)
spans.append(entity)
doc.ents = list(doc.ents) + spans
for span in spans:
span.merge()
return doc
nlp = English()
rest_countries = RESTCountriesComponent(nlp)
nlp.add_pipe(rest_countries)
nlp.to_disk('myNlp')
然后我尝试加载我的模型,
nlp = spacy.load('myNlp')
但是得到这个错误信息:
KeyError: u"[E002] Can't find factory for 'countries'。这通常 当 spaCy 使用组件名称调用
nlp.create_pipe时发生 这不是内置的 - 例如,在构建管道时 模型的 meta.json。如果您使用的是自定义组件,则可以编写 到Language.factories['countries']或将其从模型元数据中删除 并改为通过nlp.add_pipe添加。”
我不能只将我的自定义组件添加到我的编程环境中的通用管道中。我该怎么做?
【问题讨论】: