Spacy 3.0:无法为 Lemmatizer 添加自定义查找

Sapcy 3.0 : can't add costum lookups for Lemmatizer

我使用下面的代码将自定义 Lookups 添加到自定义 Lanuage class:

def create_lookups():
    lookups = Lookups()
    lookups.add_table("lemma_lookup", LOOKUP)
    lookups.add_table("lemma_rules", json_to_dict('lemma_rules.json'))
    lookups.add_table("lemma_index", json_to_dict('lemma_index.json'))
    lookups.add_table("lemma_exc", json_to_dict('lemma_exc.json'))
    return lookups


def json_to_dict(filename):
    location = os.path.realpath(
        os.path.join(os.getcwd(), os.path.dirname(__file__)))
    with open(os.path.join(location, filename)) as f_in:
        return json.load(f_in)


@CustomeLanguage.factory(
    "lemmatizer",
    assigns=["token.lemma"],
    default_config={"model": None, "mode": "lookup", "overwrite": False},
    default_score_weights={"lemma_acc": 1.0},
)
def make_lemmatizer(
        nlp: Language, model: Optional[Model], name: str, mode: str, overwrite: bool
):
    lemmatizer = Lemmatizer(nlp.vocab, model, name, mode=mode, overwrite=overwrite)
    lemmatizer.lookups = create_lookups()
    return lemmatizer


但是当我实例化 CustomLanguage 时,nlp.vocab.lookups 中没有查找 table。有什么问题,我该如何解决?

词汇表中不再有词形还原器查找。它们存储在 nlp.get_pipe("lemmatizer").lookups 下的词形还原器组件中。

如果你的词形还原器工厂像这样创建词形还原器,任何加载模型的人都需要有这些 JSON 可用的文件,否则模型将不会加载。 (查找表保存在模型中,但您的 make_lemmatizer 方法在编写时并未考虑到这一点。)

相反,创建一个自定义词形还原器 class 在其 initialize 方法中加载这些表,然后您的代码将如下所示添加词形还原器并加载其表一次。

nlp = spacy.blank("lg")
nlp.add_pipe("lemmatizer").initialize()
nlp.to_disk("/path/to/model")

一旦你 运行 initialize() 一次用于词形还原器,表格将与模型目录一起保存,你不需要在重新加载时再次 运行 它型号。

它可能看起来像这样,如果您愿意,它还允许您将 Lookups 对象传递给 initialize

class CustomLemmatizer(Lemmatizer):
    def initialize(
        self,
        get_examples: Optional[Callable[[], Iterable[Example]]] = None,
        *,
        nlp: Optional[Language] = None,
        lookups: Optional[Lookups] = None,
    ):
        if lookups is None:
            self.lookups = create_lookups()
        else:
            self.lookups = lookups