【问题标题】:How to predict entities for multiple sentences using spaCy?如何使用 spaCy 预测多个句子的实体?
【发布时间】:2022-10-05 08:54:39
【问题描述】:

我已经使用 spaCy 训练了一个 ner 模型。我知道如何使用它来识别单个句子(文档对象)的实体并可视化结果:

doc = disease_blank('Example sentence')    
spacy.displacy.render(doc, style="ent", jupyter=True)

或者

for ent in doc.ents:
    print(ent.text, ent.label_)

现在我想预测多个这样的句子的实体。我的想法是按实体过滤句子。目前我刚刚找到了以下方法:

sentences = ['sentence 1', 'sentence2', 'sentence3']
for element in sentences:
    doc = nlp(element)
    for ent in doc.ents:
        if ent.label_ == "LOC":
        print(doc)
 # returns all sentences which have the entitie "LOC"

我的问题是是否有更好、更有效的方法来做到这一点?

【问题讨论】:

    标签: model spacy named-entity-recognition


    【解决方案1】:

    您有 2 个选项来加快当前的实施:

    • 使用 spaCy 开发人员 here 提供的提示。在不知道您的自定义 NER 模型管道具有哪些特定组件的情况下,您的代码重构如下:
    import spacy
    import multiprocessing
    
    cpu_cores = multiprocessing.cpu_count()-2 if multiprocessing.cpu_count()-2 > 1 else 1
    nlp = spacy.load("./path/to/your/own/model")
    
    sentences = ['sentence 1', 'sentence2', 'sentence3']
    for doc in nlp.pipe(sentences, n_process=cpu_cores):  # disable=["tok2vec", "tagger", "parser", "attribute_ruler", "lemmatizer"] ... if your model has them. Check with `nlp.pipe_names`
        # returns all sentences which have the entitie "LOC"
        print([(doc) for ent in doc.ents if ent.label_ == "LOC"])
    
    • 结合以前的知识,使用 spaCy 自定义组件(如仔细解释 here)。使用此选项,您重构/改进的代码将如下所示:
    import spacy
    import multiprocessing
    from spacy.language import Language
    
    cpu_cores = multiprocessing.cpu_count()-2 if multiprocessing.cpu_count()-2 > 1 else 1
    
    @Language.component("loc_label_filter")
    def custom_component_function(doc):
        old_ents = doc.ents
        new_ents = [item for item in old_ents if item.label_ == "LOC"]
        doc.ents = new_ents
        return doc
    
    
    nlp = spacy.load("./path/to/your/own/model")
    nlp.add_pipe("loc_label_filter", after="ner")
    
    sentences = ['sentence 1', 'sentence2', 'sentence3']
    
    for doc in nlp.pipe(sentences, n_process=cpu_cores):
        print([(doc) for ent in doc.ents])
    

    重要的:

    1. 请注意,如果您的sentences 变量包含数百或数千个样本,这些结果将会很明显;如果句子是“小的”(即,它只包含一百个或更少的句子),您(和时间基准)可能不会注意到很大的差异。
    2. 还请注意nlp.pipe 中的batch_size 参数也可以微调,但根据我自己的经验,只有在前面的提示下,您仍然看不到明显差异时才想这样做。

    【讨论】:

      猜你喜欢
      • 2021-02-23
      • 1970-01-01
      • 2020-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多