SpaCy 中的自定义句子边界检测

Kev*_*erg 3 python nlp spacy

我正在尝试在 spaCy 中编写一个自定义句子分割器,它将整个文档作为一个句子返回。

我编写了一个自定义管道组件,它使用这里的代码来实现

但是我无法让它工作,因为不是更改句子边界以将整个文档作为单个句子,而是会引发两个不同的错误。

如果我创建一个空白语言实例并且只将我的自定义组件添加到管道中,我会收到此错误:

ValueError: Sentence boundary detection requires the dependency parse, which requires a statistical model to be installed and loaded.
Run Code Online (Sandbox Code Playgroud)

如果我将解析器组件添加到管道中

nlp = spacy.blank('es')
parser = nlp.create_pipe('parser')
nlp.add_pipe(parser, last=True)
def custom_sbd(doc):
    print("EXECUTING SBD!!!!!!!!!!!!!!!!!!!!")
    doc[0].sent_start = True
    for i in range(1, len(doc)):
        doc[i].sent_start = False
    return doc
nlp.begin_training()
nlp.add_pipe(custom_sbd, first=True)
Run Code Online (Sandbox Code Playgroud)

我犯了同样的错误。

如果我更改顺序使其先解析然后更改句子边界,则错误更改为

Refusing to write to token.sent_start if its document is parsed, because this may cause inconsistent state.
Run Code Online (Sandbox Code Playgroud)

因此,如果它在不存在的情况下抛出一个需要依赖解析的错误,或者在自定义句子边界检测之后执行,并且在首先执行依赖解析时出现不同的错误,那么合适的方法是什么?

谢谢!

Kev*_*erg 5

从spaCy伊内斯回答我的问题在这里

感谢您提出这一点 - 抱歉,这有点令人困惑。我很确定你描述的第一个问题已经在 master 上解决了。spaCy 绝对应该尊重自定义句子边界,即使在没有依赖解析器的管道中也是如此。

如果您想在没有解析器的情况下使用您的自定义 SBD 组件,一个非常简单的解决方案是在您的自定义组件中设置 doc.is_parsed = True。所以当 Doc.sents 检查依赖解析时,它会查看 is_parsed 并且不会抱怨。

如果要将组件与解析器一起使用,请确保将其添加在解析器之前。解析器应该始终尊重先前处理步骤中已经设置的句子边界。