将Spacy培训数据格式转换为Spacy CLI格式(适用于空白NER)

2022-05-15 00:00:00 python spacy

问题描述

这是经典的培训格式。

TRAIN_DATA = [
    ("Who is Shaka Khan?", {"entities": [(7, 17, "PERSON")]}),
    ("I like London and Berlin.", {"entities": [(7, 13, "LOC"), (18, 24, "LOC")]}),
]

我以前是用代码训练的,但据我所知,用CLI训练方法训练更好。但是,我的格式是这样的。

我找到了这种类型转换的代码片段,但它们都在执行spacy.load('en')而不是空白-这让我想,它们是在训练现有模型而不是空白吗?

这块看起来很简单:

import spacy
from spacy.gold import docs_to_json
import srsly

nlp = spacy.load('en', disable=["ner"]) # as you see it's loading 'en' which I don't have
TRAIN_DATA = #data from above

docs = []
for text, annot in TRAIN_DATA:
    doc = nlp(text)
    doc.ents = [doc.char_span(start_idx, end_idx, label=label) for start_idx, end_idx, label in annot["entities"]]
    docs.append(doc)

srsly.write_json("ent_train_data.json", [docs_to_json(docs)])

运行此代码时会抛出:找不到模型‘en’。它似乎不是快捷方式链接、Python包或数据目录的有效路径。

我很困惑如何与空格上的spacy train一起使用。是否只使用spacy.blank('en')?但是disable=["ner"]标志又如何呢?

编辑:

如果我尝试spacy.blank('en')而不是spacy.blank('en'),则收到Can‘t ImportLanguage Goal From Spacy.lang:no模块名为’Spacy.lang.en‘

编辑2: 我已尝试加载en_core_web_sm

nlp = spacy.load('en_core_web_sm')

docs = []
for text, annot in TRAIN_DATA:
    doc = nlp(text)
    doc.ents = [doc.char_span(start_idx, end_idx, label=label) for start_idx, end_idx, label in annot["entities"]]
    docs.append(doc)

srsly.write_json("ent_train_data.json", [docs_to_json(docs)])

TypeError:‘NoneType’类型的对象没有len()

艾尔顿-print(text[start:end])

进球!FK Qarabag 1,Partizani Tirana 0。Filip Ozobic-FK Qarabag-从禁区中心到球门中心的头球射门。辅助-艾尔顿-print(text)

无-doc.ents =...

TypeError:‘NoneType’类型的对象没有len()

编辑3:From Ines' comment

nlp = spacy.load('en_core_web_sm')

docs = []
for text, annot in TRAIN_DATA:

    doc = nlp(text)

    tags = biluo_tags_from_offsets(doc, annot['entities'])
    docs.append(doc)

srsly.write_json(train_name + "_spacy_format.json", [docs_to_json(docs)])

这将创建json,但我在生成的json中看不到任何已标记的实体。


解决方案

编辑3已关闭,但缺少将实体添加到文档的步骤。这应该是可行的:

import spacy
import srsly
from spacy.gold import docs_to_json, biluo_tags_from_offsets, spans_from_biluo_tags

TRAIN_DATA = [
    ("Who is Shaka Khan?", {"entities": [(7, 17, "PERSON")]}),
    ("I like London and Berlin.", {"entities": [(7, 13, "LOC"), (18, 24, "LOC")]}),
]

nlp = spacy.load('en_core_web_sm')
docs = []
for text, annot in TRAIN_DATA:
    doc = nlp(text)
    tags = biluo_tags_from_offsets(doc, annot['entities'])
    entities = spans_from_biluo_tags(doc, tags)
    doc.ents = entities
    docs.append(doc)

srsly.write_json("spacy_format.json", [docs_to_json(docs)])

最好添加一个内置函数来执行此转换,因为通常需要从示例脚本(仅用于简单演示)转换到系列CLI。

编辑:

您也可以跳过对内置BILUO转换器的间接使用,而使用上面所拥有的:

    doc.ents = [doc.char_span(start_idx, end_idx, label=label) for start_idx, end_idx, label in annot["entities"]]

相关文章