【问题标题】:How to convert spaCy NER dataset format to Flair format?如何将 spaCy NER 数据集格式转换为 Flair 格式?
【发布时间】:2021-03-13 20:12:55
【问题描述】:

我已经使用 dataturks 标记了一个数据集来训练 spaCy NER 并且一切正常,但是,我刚刚意识到 Flair 具有不同的格式,我只是想知道是否有办法将我的“ spaCy的NER" json数据集格式转为Flair格式:

乔治 N B-PER
华盛顿 N I-PER
去了V O
到P O
华盛顿 N B-LOC

然而 spaCy 的格式如下:

[("乔治华盛顿去了华盛顿",
{'entities': [(0, 6,'PER'),(7, 17,'PER'),(26, 36,'LOC')]})]

【问题讨论】:

    标签: python nlp spacy named-entity-recognition flair


    【解决方案1】:

    Flair使用BILUO方案,句子之间有空行,所以你需要使用bliuo_tags_from_offsets

    import spacy
    from spacy.gold import biluo_tags_from_offsets
    nlp = spacy.load("en_core_web_md")
    
    ents = [("George Washington went to Washington",{'entities': [(0, 6,'PER'),(7, 17,'PER'),(26, 36,'LOC')]}),
             ("Uber blew through $1 million a week", {'entities':[(0, 4, 'ORG')]}),
           ]
    
    with open("flair_ner.txt","w") as f:
        for sent,tags in ents:
            doc = nlp(sent)
            biluo = biluo_tags_from_offsets(doc,tags['entities'])
            for word,tag in zip(doc, biluo):
                f.write(f"{word} {tag}\n")
            f.write("\n")
    

    输出:

    George U-PER
    Washington U-PER
    went O
    to O
    Washington U-LOC
    
    Uber U-ORG
    blew O
    through O
    $ O
    1 O
    million O
    a O
    week O
    

    注意,只训练NER 这似乎就足够了。如果您希望添加 pos 标记,则需要创建从 Universal Pos Tags 到 Flair 简化方案的映射。例如:

    tag_mapping = {'PROPN':'N','VERB':'V','ADP':'P','NOUN':'N'} # create your own
    with open("flair_ner.txt","w") as f:
        for pair in ents:
            sent,tags = pair
            doc = nlp(sent)
            biluo = biluo_tags_from_offsets(doc,tags['entities'])
            try:
                for word,tag in zip(doc, biluo):
                    f.write(f"{word} {tag_mapping[word.pos_]} {tag}\n")
    #                 f.write(f"{word} {tag_mapping.get(word.pos_,'None')} {tag}\n")
            except KeyError:
                print(f"''{word.pos_}' tag is not defined in tag_mapping")
            f.write("\n")
    

    输出:

    ''SYM' tag is not defined in tag_mapping'
    

    【讨论】:

    • 非常感谢您的回复,但是,我遇到了一个重叠的问题:ValueError: [E103] Trying to set conflicting doc.ents: '(1155, 1199, 'Email Address')'和'(1143, 1240, '链接')'。令牌只能是一个实体的一部分,因此请确保您设置的实体不重叠。
    • 谢谢,我自己解决后会做的!
    • 我不能这样做,因为我必须重新定义我所有标记的数据集,这就是为什么我正在寻找一种直接的方法来将此数据集转换为 Flair 格式..顺便说一句我还在卡住重叠的问题,我会开一个新问题。
    猜你喜欢
    • 1970-01-01
    • 2022-01-02
    • 2021-07-30
    • 2018-05-06
    • 1970-01-01
    • 2020-04-03
    • 2021-10-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多