SpaCy menyimpan model ke disk dengan kesalahan Sentencizer kustom

Nov 27 2020

Saya tahu pertanyaan serupa telah diajukan:

Pemisahan kalimat khusus Spacy

Deteksi batas kalimat kustom di SpaCy

namun situasiku sedikit berbeda. Saya ingin mewarisi dari spacy Sentencizer () dengan:

from spacy.pipeline import Sentencizer

class MySentencizer(Sentencizer):
    def __init__(self):
        self.tok = create_mySentencizer() # returning the sentences

    def __call__(self, *args, **kwargs):
        doc = args[0]
        for tok in doc:
            # do set the boundaries with tok.is_sent_start 
        return doc

Bahkan pemisahan berfungsi dengan baik jika saya memanggil doc = nlp("Text and so on. Another sentence.")setelah memperbarui model:

  nlp = spacy.load("some_model")
  sentencizer = MySentencizer()
  nlp.add_pipe(sentencizer, before="parser")
  # update model 

ketika saya ingin menyimpan model terlatih dengan:

nlp.to_disk("path/to/my/model")

Saya mendapatkan kesalahan berikut:

AttributeError: 'MySentencizer' object has no attribute 'punct_chars'

Sebaliknya, jika saya menggunakan nlp.add_pipe (nlp.create_pipe ('sentencizer')) kesalahan tidak terjadi. Saya ingin tahu pada poin apa saya harus menyetel atribut punct_chars. Itu seharusnya diwarisi dari superclass?

Jika saya mengganti Sentencizer dari kelas dan melakukan objek sesuai dengan posting pertama, itu berfungsi, tetapi saya mungkin kehilangan beberapa informasi berharga di jalan misalnya punct_chars?

Terima kasih atas bantuannya.

Chris

Jawaban

1 SergeyBushmanov Nov 29 2020 at 20:44

Hal berikut harus dilakukan (catatan super(MySentencizer, self).__init__()):

import spacy
from spacy.pipeline import Sentencizer

class MySentencizer(Sentencizer):
    def __init__(self):
        super(MySentencizer, self).__init__() 

    def __call__(self, *args, **kwargs):
        doc = args[0]
        for tok in doc:
            tok.is_sent_start = True if tok.orth == "." else False
        return doc

nlp = spacy.load("en_core_web_md")
sentencizer = MySentencizer()
nlp.add_pipe(sentencizer, before="parser")

nlp.to_disk("model")