【问题标题】:New named entity class in SpacySpacy 中的新命名实体类
【发布时间】:2016-11-07 12:34:10
【问题描述】:

我需要训练 Spacy NER 以便能够识别 2 个用于命名实体识别的新类,我所拥有的只是包含应该在新类中的项目列表的文件。

例如:Rolling Stones、Muse、Arctic Monkeys - 艺术家 知道如何做到这一点吗?

【问题讨论】:

    标签: python nlp named-entity-recognition spacy


    【解决方案1】:

    这似乎是Matcher 或PhraseMatcher 的完美用例(如果您关心性能的话)。

    import spacy
    
    nlp = spacy.load('en')
    
    def merge_phrases(matcher, doc, i, matches):
        '''
        Merge a phrase. We have to be careful here because we'll change the token indices.
        To avoid problems, merge all the phrases once we're called on the last match.
        '''
        if i != len(matches)-1:
            return None
        spans = [(ent_id, label, doc[start : end]) for ent_id, label, start, end in matches]
        for ent_id, label, span in spans:
            span.merge('NNP' if label else span.root.tag_, span.text, nlp.vocab.strings[label])
    
    
    matcher = spacy.matcher.Matcher(nlp.vocab)
    matcher.add(entity_key='1', label='ARTIST', attrs={}, specs=[[{spacy.attrs.ORTH: 'Rolling'}, {spacy.attrs.ORTH: 'Stones'}]], on_match=merge_phrases)
    matcher.add(entity_key='2', label='ARTIST', attrs={}, specs=[[{spacy.attrs.ORTH: 'Muse'}]], on_match=merge_phrases)
    matcher.add(entity_key='3', label='ARTIST', attrs={}, specs=[[{spacy.attrs.ORTH: 'Arctic'}, {spacy.attrs.ORTH: 'Monkeys'}]], on_match=merge_phrases)
    doc = nlp(u'The Rolling Stones are an English rock band formed in London in 1962. The first settled line-up consisted of Brian Jones, Ian Stewart, Mick Jagger, Keith Richards, Bill Wyman and Charlie Watts')
    matcher(doc)
    for ent in doc.ents:
      print(ent)
    

    有关详细信息,请参阅文档。根据我的经验,匹配器中有 400k 个实体,匹配每个文档几乎需要一秒钟。 PhraseMatcher 要快得多,但使用起来有点棘手。请注意,这是“严格”匹配器,它不会匹配它以前从未见过的任何实体。

    【讨论】:

    • 但看起来我需要手动添加新实体的所有元素?
    • 对,就像我说的。如果你想匹配它以前没有见过的实体——你需要先训练它,这更复杂,仍然需要你有很多数据。
    • 如果您认为该问题有帮助,请务必接受该问题,或者用您自己的解决方案回答并接受它,这样该问题将被关闭。
    • @MaxUppenkamp 我相信欢迎您提供自己的答案和/或修复现有答案。
    • 我现在正在尝试使用 Spacy Matcher,有没有办法找到标签之间的元素,例如两个匹配之间的动词?
    猜你喜欢
    • 1970-01-01
    • 2021-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 2020-04-06
    相关资源
    最近更新 更多