mirror of
https://github.com/explosion/spaCy.git
synced 2024-12-24 00:46:28 +03:00
Merge branch 'develop' of https://github.com/explosion/spaCy into develop
This commit is contained in:
commit
3f6f087113
|
@ -40,7 +40,7 @@ install_requires =
|
|||
murmurhash>=0.28.0,<1.1.0
|
||||
cymem>=2.0.2,<2.1.0
|
||||
preshed>=3.0.2,<3.1.0
|
||||
thinc>=8.0.0a11,<8.0.0a20
|
||||
thinc>=8.0.0a12,<8.0.0a20
|
||||
blis>=0.4.0,<0.5.0
|
||||
wasabi>=0.7.0,<1.1.0
|
||||
srsly>=2.1.0,<3.0.0
|
||||
|
|
|
@ -48,7 +48,7 @@ def convert_cli(
|
|||
morphology: bool = Opt(False, "--morphology", "-m", help="Enable appending morphology to tags"),
|
||||
merge_subtokens: bool = Opt(False, "--merge-subtokens", "-T", help="Merge CoNLL-U subtokens"),
|
||||
converter: str = Opt("auto", "--converter", "-c", help=f"Converter: {tuple(CONVERTERS.keys())}"),
|
||||
ner_map: Optional[Path] = Opt(None, "--ner-map", "-N", help="NER tag mapping (as JSON-encoded dict of entity types)", exists=True),
|
||||
ner_map: Optional[Path] = Opt(None, "--ner-map", "-nm", help="NER tag mapping (as JSON-encoded dict of entity types)", exists=True),
|
||||
lang: Optional[str] = Opt(None, "--lang", "-l", help="Language (if tokenizer required)"),
|
||||
# fmt: on
|
||||
):
|
||||
|
|
|
@ -118,7 +118,9 @@ def debug_data(
|
|||
|
||||
# Create all gold data here to avoid iterating over the train_dataset constantly
|
||||
gold_train_data = _compile_gold(train_dataset, pipeline, nlp, make_proj=True)
|
||||
gold_train_unpreprocessed_data = _compile_gold(train_dataset, pipeline, nlp, make_proj=False)
|
||||
gold_train_unpreprocessed_data = _compile_gold(
|
||||
train_dataset, pipeline, nlp, make_proj=False
|
||||
)
|
||||
gold_dev_data = _compile_gold(dev_dataset, pipeline, nlp, make_proj=True)
|
||||
|
||||
train_texts = gold_train_data["texts"]
|
||||
|
|
|
@ -229,7 +229,9 @@ def add_vectors(
|
|||
else:
|
||||
if vectors_loc:
|
||||
with msg.loading(f"Reading vectors from {vectors_loc}"):
|
||||
vectors_data, vector_keys = read_vectors(msg, vectors_loc, truncate_vectors)
|
||||
vectors_data, vector_keys = read_vectors(
|
||||
msg, vectors_loc, truncate_vectors
|
||||
)
|
||||
msg.good(f"Loaded vectors from {vectors_loc}")
|
||||
else:
|
||||
vectors_data, vector_keys = (None, None)
|
||||
|
|
|
@ -406,5 +406,5 @@ def verify_cli_args(
|
|||
if not config["nlp"]["vectors"]:
|
||||
msg.fail(
|
||||
"Must specify nlp.vectors if pretraining.objective.type is vectors",
|
||||
exits=True
|
||||
exits=True,
|
||||
)
|
||||
|
|
|
@ -202,11 +202,11 @@ def train(
|
|||
nlp.resume_training()
|
||||
else:
|
||||
msg.info(f"Initializing the nlp pipeline: {nlp.pipe_names}")
|
||||
train_examples = list(corpus.train_dataset(
|
||||
nlp,
|
||||
shuffle=False,
|
||||
gold_preproc=training["gold_preproc"]
|
||||
))
|
||||
train_examples = list(
|
||||
corpus.train_dataset(
|
||||
nlp, shuffle=False, gold_preproc=training["gold_preproc"]
|
||||
)
|
||||
)
|
||||
nlp.begin_training(lambda: train_examples)
|
||||
|
||||
# Update tag map with provided mapping
|
||||
|
@ -293,12 +293,14 @@ def train(
|
|||
|
||||
def create_train_batches(nlp, corpus, cfg):
|
||||
max_epochs = cfg.get("max_epochs", 0)
|
||||
train_examples = list(corpus.train_dataset(
|
||||
nlp,
|
||||
shuffle=True,
|
||||
gold_preproc=cfg["gold_preproc"],
|
||||
max_length=cfg["max_length"]
|
||||
))
|
||||
train_examples = list(
|
||||
corpus.train_dataset(
|
||||
nlp,
|
||||
shuffle=True,
|
||||
gold_preproc=cfg["gold_preproc"],
|
||||
max_length=cfg["max_length"],
|
||||
)
|
||||
)
|
||||
|
||||
epoch = 0
|
||||
while True:
|
||||
|
@ -520,7 +522,10 @@ def setup_printer(training, nlp):
|
|||
)
|
||||
)
|
||||
data = (
|
||||
[info["epoch"], info["step"]] + losses + scores + ["{0:.2f}".format(float(info["score"]))]
|
||||
[info["epoch"], info["step"]]
|
||||
+ losses
|
||||
+ scores
|
||||
+ ["{0:.2f}".format(float(info["score"]))]
|
||||
)
|
||||
msg.row(data, widths=table_widths, aligns=table_aligns)
|
||||
|
||||
|
|
|
@ -59,6 +59,6 @@ def read_iob(raw_sents, vocab, n_sents):
|
|||
doc[i].is_sent_start = sent_start
|
||||
biluo = iob_to_biluo(iob)
|
||||
entities = tags_to_entities(biluo)
|
||||
doc.ents = [Span(doc, start=s, end=e+1, label=L) for (L, s, e) in entities]
|
||||
doc.ents = [Span(doc, start=s, end=e + 1, label=L) for (L, s, e) in entities]
|
||||
docs.append(doc)
|
||||
return docs
|
||||
|
|
|
@ -8,7 +8,7 @@ class Corpus:
|
|||
"""An annotated corpus, reading train and dev datasets from
|
||||
the DocBin (.spacy) format.
|
||||
|
||||
DOCS: https://spacy.io/api/goldcorpus
|
||||
DOCS: https://spacy.io/api/corpus
|
||||
"""
|
||||
|
||||
def __init__(self, train_loc, dev_loc, limit=0):
|
||||
|
@ -49,16 +49,13 @@ class Corpus:
|
|||
Doc(
|
||||
nlp.vocab,
|
||||
words=[word.text for word in reference],
|
||||
spaces=[bool(word.whitespace_) for word in reference]
|
||||
spaces=[bool(word.whitespace_) for word in reference],
|
||||
),
|
||||
reference
|
||||
reference,
|
||||
)
|
||||
else:
|
||||
return Example(
|
||||
nlp.make_doc(reference.text),
|
||||
reference
|
||||
)
|
||||
|
||||
return Example(nlp.make_doc(reference.text), reference)
|
||||
|
||||
def make_examples(self, nlp, reference_docs, max_length=0):
|
||||
for reference in reference_docs:
|
||||
if len(reference) == 0:
|
||||
|
@ -71,7 +68,6 @@ class Corpus:
|
|||
continue
|
||||
elif max_length == 0 or len(ref_sent) < max_length:
|
||||
yield self._make_example(nlp, ref_sent.as_doc(), False)
|
||||
|
||||
|
||||
def make_examples_gold_preproc(self, nlp, reference_docs):
|
||||
for reference in reference_docs:
|
||||
|
@ -111,8 +107,9 @@ class Corpus:
|
|||
i += 1
|
||||
return n
|
||||
|
||||
def train_dataset(self, nlp, *, shuffle=True, gold_preproc=False,
|
||||
max_length=0, **kwargs):
|
||||
def train_dataset(
|
||||
self, nlp, *, shuffle=True, gold_preproc=False, max_length=0, **kwargs
|
||||
):
|
||||
ref_docs = self.read_docbin(nlp.vocab, self.walk_corpus(self.train_loc))
|
||||
if gold_preproc:
|
||||
examples = self.make_examples_gold_preproc(nlp, ref_docs)
|
||||
|
|
|
@ -92,7 +92,7 @@ def biluo_tags_from_offsets(doc, entities, missing="O"):
|
|||
# Handle entity cases
|
||||
for start_char, end_char, label in entities:
|
||||
if not label:
|
||||
for s in starts: # account for many-to-one
|
||||
for s in starts: # account for many-to-one
|
||||
if s >= start_char and s < end_char:
|
||||
biluo[starts[s]] = "O"
|
||||
else:
|
||||
|
|
|
@ -17,11 +17,7 @@ def build_tb_parser_model(
|
|||
nO=None,
|
||||
):
|
||||
t2v_width = tok2vec.get_dim("nO") if tok2vec.has_dim("nO") else None
|
||||
tok2vec = chain(
|
||||
tok2vec,
|
||||
list2array(),
|
||||
Linear(hidden_width, t2v_width),
|
||||
)
|
||||
tok2vec = chain(tok2vec, list2array(), Linear(hidden_width, t2v_width),)
|
||||
tok2vec.set_dim("nO", hidden_width)
|
||||
|
||||
lower = PrecomputableAffine(
|
||||
|
|
|
@ -179,22 +179,9 @@ def test_doc_api_right_edge(en_tokenizer):
|
|||
doc = get_doc(tokens.vocab, words=[t.text for t in tokens], heads=heads)
|
||||
assert doc[6].text == "for"
|
||||
subtree = [w.text for w in doc[6].subtree]
|
||||
assert subtree == [
|
||||
"for",
|
||||
"the",
|
||||
"sake",
|
||||
"of",
|
||||
"such",
|
||||
"as",
|
||||
"live",
|
||||
"under",
|
||||
"the",
|
||||
"government",
|
||||
"of",
|
||||
"the",
|
||||
"Romans",
|
||||
",",
|
||||
]
|
||||
# fmt: off
|
||||
assert subtree == ["for", "the", "sake", "of", "such", "as", "live", "under", "the", "government", "of", "the", "Romans", ","]
|
||||
# fmt: on
|
||||
assert doc[6].right_edge.text == ","
|
||||
|
||||
|
||||
|
@ -307,9 +294,14 @@ def test_doc_api_from_docs(en_tokenizer, de_tokenizer):
|
|||
en_texts = ["Merging the docs is fun.", "They don't think alike."]
|
||||
de_text = "Wie war die Frage?"
|
||||
en_docs = [en_tokenizer(text) for text in en_texts]
|
||||
docs_idx = en_texts[0].index('docs')
|
||||
docs_idx = en_texts[0].index("docs")
|
||||
de_doc = de_tokenizer(de_text)
|
||||
en_docs[0].user_data[("._.", "is_ambiguous", docs_idx, None)] = (True, None, None, None)
|
||||
en_docs[0].user_data[("._.", "is_ambiguous", docs_idx, None)] = (
|
||||
True,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
|
||||
assert Doc.from_docs([]) is None
|
||||
|
||||
|
@ -323,15 +315,16 @@ def test_doc_api_from_docs(en_tokenizer, de_tokenizer):
|
|||
assert len(en_docs) == len(list(m_doc.sents))
|
||||
assert len(str(m_doc)) > len(en_texts[0]) + len(en_texts[1])
|
||||
assert str(m_doc) == " ".join(en_texts)
|
||||
p_token = m_doc[len(en_docs[0])-1]
|
||||
p_token = m_doc[len(en_docs[0]) - 1]
|
||||
assert p_token.text == "." and bool(p_token.whitespace_)
|
||||
en_docs_tokens = [t for doc in en_docs for t in doc]
|
||||
assert len(m_doc) == len(en_docs_tokens)
|
||||
think_idx = len(en_texts[0]) + 1 + en_texts[1].index('think')
|
||||
think_idx = len(en_texts[0]) + 1 + en_texts[1].index("think")
|
||||
assert m_doc[9].idx == think_idx
|
||||
with pytest.raises(AttributeError):
|
||||
not_available = m_doc[2]._.is_ambiguous # not callable, because it was not set via set_extension
|
||||
assert len(m_doc.user_data) == len(en_docs[0].user_data) # but it's there
|
||||
# not callable, because it was not set via set_extension
|
||||
m_doc[2]._.is_ambiguous
|
||||
assert len(m_doc.user_data) == len(en_docs[0].user_data) # but it's there
|
||||
|
||||
m_doc = Doc.from_docs(en_docs, ensure_whitespace=False)
|
||||
assert len(en_docs) == len(list(m_doc.sents))
|
||||
|
@ -341,19 +334,21 @@ def test_doc_api_from_docs(en_tokenizer, de_tokenizer):
|
|||
assert p_token.text == "." and not bool(p_token.whitespace_)
|
||||
en_docs_tokens = [t for doc in en_docs for t in doc]
|
||||
assert len(m_doc) == len(en_docs_tokens)
|
||||
think_idx = len(en_texts[0]) + 0 + en_texts[1].index('think')
|
||||
think_idx = len(en_texts[0]) + 0 + en_texts[1].index("think")
|
||||
assert m_doc[9].idx == think_idx
|
||||
|
||||
m_doc = Doc.from_docs(en_docs, attrs=['lemma', 'length', 'pos'])
|
||||
with pytest.raises(ValueError): # important attributes from sentenziser or parser are missing
|
||||
m_doc = Doc.from_docs(en_docs, attrs=["lemma", "length", "pos"])
|
||||
with pytest.raises(ValueError):
|
||||
# important attributes from sentenziser or parser are missing
|
||||
assert list(m_doc.sents)
|
||||
assert len(str(m_doc)) > len(en_texts[0]) + len(en_texts[1])
|
||||
assert str(m_doc) == " ".join(en_texts) # space delimiter considered, although spacy attribute was missing
|
||||
# space delimiter considered, although spacy attribute was missing
|
||||
assert str(m_doc) == " ".join(en_texts)
|
||||
p_token = m_doc[len(en_docs[0]) - 1]
|
||||
assert p_token.text == "." and bool(p_token.whitespace_)
|
||||
en_docs_tokens = [t for doc in en_docs for t in doc]
|
||||
assert len(m_doc) == len(en_docs_tokens)
|
||||
think_idx = len(en_texts[0]) + 1 + en_texts[1].index('think')
|
||||
think_idx = len(en_texts[0]) + 1 + en_texts[1].index("think")
|
||||
assert m_doc[9].idx == think_idx
|
||||
|
||||
|
||||
|
|
|
@ -118,6 +118,7 @@ def test_oracle_moves_missing_B(en_vocab):
|
|||
moves.add_action(move_types.index("U"), label)
|
||||
moves.get_oracle_sequence(example)
|
||||
|
||||
|
||||
# We can't easily represent this on a Doc object. Not sure what the best solution
|
||||
# would be, but I don't think it's an important use case?
|
||||
@pytest.mark.xfail(reason="No longer supported")
|
||||
|
|
|
@ -91,6 +91,7 @@ def test_parser_merge_pp(en_tokenizer):
|
|||
assert doc[2].text == "another phrase"
|
||||
assert doc[3].text == "occurs"
|
||||
|
||||
|
||||
# We removed the step_through API a while ago. we should bring it back though
|
||||
@pytest.mark.xfail(reason="Unsupported")
|
||||
def test_parser_arc_eager_finalize_state(en_tokenizer, en_parser):
|
||||
|
|
|
@ -8,10 +8,11 @@ from ...tokens import DocBin
|
|||
|
||||
def test_issue4402():
|
||||
nlp = English()
|
||||
attrs = ["ORTH", "SENT_START", "ENT_IOB", "ENT_TYPE"]
|
||||
with make_tempdir() as tmpdir:
|
||||
output_file = tmpdir / "test4402.spacy"
|
||||
docs = json2docs([json_data])
|
||||
data = DocBin(docs=docs, attrs =["ORTH", "SENT_START", "ENT_IOB", "ENT_TYPE"]).to_bytes()
|
||||
data = DocBin(docs=docs, attrs=attrs).to_bytes()
|
||||
with output_file.open("wb") as file_:
|
||||
file_.write(data)
|
||||
corpus = Corpus(train_loc=str(output_file), dev_loc=str(output_file))
|
||||
|
@ -25,74 +26,73 @@ def test_issue4402():
|
|||
assert len(split_train_data) == 4
|
||||
|
||||
|
||||
json_data =\
|
||||
{
|
||||
"id": 0,
|
||||
"paragraphs": [
|
||||
{
|
||||
"raw": "How should I cook bacon in an oven?\nI've heard of people cooking bacon in an oven.",
|
||||
"sentences": [
|
||||
{
|
||||
"tokens": [
|
||||
{"id": 0, "orth": "How", "ner": "O"},
|
||||
{"id": 1, "orth": "should", "ner": "O"},
|
||||
{"id": 2, "orth": "I", "ner": "O"},
|
||||
{"id": 3, "orth": "cook", "ner": "O"},
|
||||
{"id": 4, "orth": "bacon", "ner": "O"},
|
||||
{"id": 5, "orth": "in", "ner": "O"},
|
||||
{"id": 6, "orth": "an", "ner": "O"},
|
||||
{"id": 7, "orth": "oven", "ner": "O"},
|
||||
{"id": 8, "orth": "?", "ner": "O"},
|
||||
],
|
||||
"brackets": [],
|
||||
},
|
||||
{
|
||||
"tokens": [
|
||||
{"id": 9, "orth": "\n", "ner": "O"},
|
||||
{"id": 10, "orth": "I", "ner": "O"},
|
||||
{"id": 11, "orth": "'ve", "ner": "O"},
|
||||
{"id": 12, "orth": "heard", "ner": "O"},
|
||||
{"id": 13, "orth": "of", "ner": "O"},
|
||||
{"id": 14, "orth": "people", "ner": "O"},
|
||||
{"id": 15, "orth": "cooking", "ner": "O"},
|
||||
{"id": 16, "orth": "bacon", "ner": "O"},
|
||||
{"id": 17, "orth": "in", "ner": "O"},
|
||||
{"id": 18, "orth": "an", "ner": "O"},
|
||||
{"id": 19, "orth": "oven", "ner": "O"},
|
||||
{"id": 20, "orth": ".", "ner": "O"},
|
||||
],
|
||||
"brackets": [],
|
||||
},
|
||||
],
|
||||
"cats": [
|
||||
{"label": "baking", "value": 1.0},
|
||||
{"label": "not_baking", "value": 0.0},
|
||||
],
|
||||
},
|
||||
{
|
||||
"raw": "What is the difference between white and brown eggs?\n",
|
||||
"sentences": [
|
||||
{
|
||||
"tokens": [
|
||||
{"id": 0, "orth": "What", "ner": "O"},
|
||||
{"id": 1, "orth": "is", "ner": "O"},
|
||||
{"id": 2, "orth": "the", "ner": "O"},
|
||||
{"id": 3, "orth": "difference", "ner": "O"},
|
||||
{"id": 4, "orth": "between", "ner": "O"},
|
||||
{"id": 5, "orth": "white", "ner": "O"},
|
||||
{"id": 6, "orth": "and", "ner": "O"},
|
||||
{"id": 7, "orth": "brown", "ner": "O"},
|
||||
{"id": 8, "orth": "eggs", "ner": "O"},
|
||||
{"id": 9, "orth": "?", "ner": "O"},
|
||||
],
|
||||
"brackets": [],
|
||||
},
|
||||
{"tokens": [{"id": 10, "orth": "\n", "ner": "O"}], "brackets": []},
|
||||
],
|
||||
"cats": [
|
||||
{"label": "baking", "value": 0.0},
|
||||
{"label": "not_baking", "value": 1.0},
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
json_data = {
|
||||
"id": 0,
|
||||
"paragraphs": [
|
||||
{
|
||||
"raw": "How should I cook bacon in an oven?\nI've heard of people cooking bacon in an oven.",
|
||||
"sentences": [
|
||||
{
|
||||
"tokens": [
|
||||
{"id": 0, "orth": "How", "ner": "O"},
|
||||
{"id": 1, "orth": "should", "ner": "O"},
|
||||
{"id": 2, "orth": "I", "ner": "O"},
|
||||
{"id": 3, "orth": "cook", "ner": "O"},
|
||||
{"id": 4, "orth": "bacon", "ner": "O"},
|
||||
{"id": 5, "orth": "in", "ner": "O"},
|
||||
{"id": 6, "orth": "an", "ner": "O"},
|
||||
{"id": 7, "orth": "oven", "ner": "O"},
|
||||
{"id": 8, "orth": "?", "ner": "O"},
|
||||
],
|
||||
"brackets": [],
|
||||
},
|
||||
{
|
||||
"tokens": [
|
||||
{"id": 9, "orth": "\n", "ner": "O"},
|
||||
{"id": 10, "orth": "I", "ner": "O"},
|
||||
{"id": 11, "orth": "'ve", "ner": "O"},
|
||||
{"id": 12, "orth": "heard", "ner": "O"},
|
||||
{"id": 13, "orth": "of", "ner": "O"},
|
||||
{"id": 14, "orth": "people", "ner": "O"},
|
||||
{"id": 15, "orth": "cooking", "ner": "O"},
|
||||
{"id": 16, "orth": "bacon", "ner": "O"},
|
||||
{"id": 17, "orth": "in", "ner": "O"},
|
||||
{"id": 18, "orth": "an", "ner": "O"},
|
||||
{"id": 19, "orth": "oven", "ner": "O"},
|
||||
{"id": 20, "orth": ".", "ner": "O"},
|
||||
],
|
||||
"brackets": [],
|
||||
},
|
||||
],
|
||||
"cats": [
|
||||
{"label": "baking", "value": 1.0},
|
||||
{"label": "not_baking", "value": 0.0},
|
||||
],
|
||||
},
|
||||
{
|
||||
"raw": "What is the difference between white and brown eggs?\n",
|
||||
"sentences": [
|
||||
{
|
||||
"tokens": [
|
||||
{"id": 0, "orth": "What", "ner": "O"},
|
||||
{"id": 1, "orth": "is", "ner": "O"},
|
||||
{"id": 2, "orth": "the", "ner": "O"},
|
||||
{"id": 3, "orth": "difference", "ner": "O"},
|
||||
{"id": 4, "orth": "between", "ner": "O"},
|
||||
{"id": 5, "orth": "white", "ner": "O"},
|
||||
{"id": 6, "orth": "and", "ner": "O"},
|
||||
{"id": 7, "orth": "brown", "ner": "O"},
|
||||
{"id": 8, "orth": "eggs", "ner": "O"},
|
||||
{"id": 9, "orth": "?", "ner": "O"},
|
||||
],
|
||||
"brackets": [],
|
||||
},
|
||||
{"tokens": [{"id": 10, "orth": "\n", "ner": "O"}], "brackets": []},
|
||||
],
|
||||
"cats": [
|
||||
{"label": "baking", "value": 0.0},
|
||||
{"label": "not_baking", "value": 1.0},
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
|
|
|
@ -28,7 +28,9 @@ def test_cli_converters_conllu2json():
|
|||
assert [t["tag"] for t in tokens] == ["NOUN", "PROPN", "PROPN", "VERB"]
|
||||
assert [t["head"] for t in tokens] == [1, 2, -1, 0]
|
||||
assert [t["dep"] for t in tokens] == ["appos", "nsubj", "name", "ROOT"]
|
||||
ent_offsets = [(e[0], e[1], e[2]) for e in converted[0]["paragraphs"][0]["entities"]]
|
||||
ent_offsets = [
|
||||
(e[0], e[1], e[2]) for e in converted[0]["paragraphs"][0]["entities"]
|
||||
]
|
||||
biluo_tags = biluo_tags_from_offsets(converted_docs[0], ent_offsets, missing="O")
|
||||
assert biluo_tags == ["O", "B-PER", "L-PER", "O"]
|
||||
|
||||
|
@ -54,7 +56,9 @@ def test_cli_converters_conllu2json():
|
|||
)
|
||||
def test_cli_converters_conllu2json_name_ner_map(lines):
|
||||
input_data = "\n".join(lines)
|
||||
converted_docs = conllu2docs(input_data, n_sents=1, ner_map={"PER": "PERSON", "BAD": ""})
|
||||
converted_docs = conllu2docs(
|
||||
input_data, n_sents=1, ner_map={"PER": "PERSON", "BAD": ""}
|
||||
)
|
||||
assert len(converted_docs) == 1
|
||||
converted = [docs_to_json(converted_docs)]
|
||||
assert converted[0]["id"] == 0
|
||||
|
@ -68,7 +72,9 @@ def test_cli_converters_conllu2json_name_ner_map(lines):
|
|||
assert [t["tag"] for t in tokens] == ["NOUN", "PROPN", "PROPN", "VERB", "PUNCT"]
|
||||
assert [t["head"] for t in tokens] == [1, 2, -1, 0, -1]
|
||||
assert [t["dep"] for t in tokens] == ["appos", "nsubj", "name", "ROOT", "punct"]
|
||||
ent_offsets = [(e[0], e[1], e[2]) for e in converted[0]["paragraphs"][0]["entities"]]
|
||||
ent_offsets = [
|
||||
(e[0], e[1], e[2]) for e in converted[0]["paragraphs"][0]["entities"]
|
||||
]
|
||||
biluo_tags = biluo_tags_from_offsets(converted_docs[0], ent_offsets, missing="O")
|
||||
assert biluo_tags == ["O", "B-PERSON", "L-PERSON", "O", "O"]
|
||||
|
||||
|
@ -115,7 +121,9 @@ def test_cli_converters_conllu2json_subtokens():
|
|||
assert [t["lemma"] for t in tokens] == ["dommer", "Finn Eilertsen", "avstå", "$."]
|
||||
assert [t["head"] for t in tokens] == [1, 1, 0, -1]
|
||||
assert [t["dep"] for t in tokens] == ["appos", "nsubj", "ROOT", "punct"]
|
||||
ent_offsets = [(e[0], e[1], e[2]) for e in converted[0]["paragraphs"][0]["entities"]]
|
||||
ent_offsets = [
|
||||
(e[0], e[1], e[2]) for e in converted[0]["paragraphs"][0]["entities"]
|
||||
]
|
||||
biluo_tags = biluo_tags_from_offsets(converted_docs[0], ent_offsets, missing="O")
|
||||
assert biluo_tags == ["O", "U-PER", "O", "O"]
|
||||
|
||||
|
@ -138,11 +146,11 @@ def test_cli_converters_iob2json(en_vocab):
|
|||
sent = converted["paragraphs"][0]["sentences"][i]
|
||||
assert len(sent["tokens"]) == 8
|
||||
tokens = sent["tokens"]
|
||||
# fmt: off
|
||||
assert [t["orth"] for t in tokens] == ["I", "like", "London", "and", "New", "York", "City", "."]
|
||||
expected = ["I", "like", "London", "and", "New", "York", "City", "."]
|
||||
assert [t["orth"] for t in tokens] == expected
|
||||
assert len(converted_docs[0].ents) == 8
|
||||
for ent in converted_docs[0].ents:
|
||||
assert(ent.text in ["New York City", "London"])
|
||||
assert ent.text in ["New York City", "London"]
|
||||
|
||||
|
||||
def test_cli_converters_conll_ner2json():
|
||||
|
@ -210,7 +218,7 @@ def test_cli_converters_conll_ner2json():
|
|||
# fmt: on
|
||||
assert len(converted_docs[0].ents) == 10
|
||||
for ent in converted_docs[0].ents:
|
||||
assert (ent.text in ["New York City", "London"])
|
||||
assert ent.text in ["New York City", "London"]
|
||||
|
||||
|
||||
def test_pretrain_make_docs():
|
||||
|
|
|
@ -161,65 +161,54 @@ def test_example_from_dict_no_ner(en_vocab):
|
|||
ner_tags = example.get_aligned_ner()
|
||||
assert ner_tags == [None, None, None, None]
|
||||
|
||||
|
||||
def test_example_from_dict_some_ner(en_vocab):
|
||||
words = ["a", "b", "c", "d"]
|
||||
spaces = [True, True, False, True]
|
||||
predicted = Doc(en_vocab, words=words, spaces=spaces)
|
||||
example = Example.from_dict(
|
||||
predicted,
|
||||
{
|
||||
"words": words,
|
||||
"entities": ["U-LOC", None, None, None]
|
||||
}
|
||||
predicted, {"words": words, "entities": ["U-LOC", None, None, None]}
|
||||
)
|
||||
ner_tags = example.get_aligned_ner()
|
||||
assert ner_tags == ["U-LOC", None, None, None]
|
||||
|
||||
|
||||
def test_json2docs_no_ner(en_vocab):
|
||||
data = [{
|
||||
"id":1,
|
||||
"paragraphs":[
|
||||
{
|
||||
"sentences":[
|
||||
{
|
||||
"tokens":[
|
||||
{
|
||||
"dep":"nn",
|
||||
"head":1,
|
||||
"tag":"NNP",
|
||||
"orth":"Ms."
|
||||
},
|
||||
{
|
||||
"dep":"nsubj",
|
||||
"head":1,
|
||||
"tag":"NNP",
|
||||
"orth":"Haag"
|
||||
},
|
||||
{
|
||||
"dep":"ROOT",
|
||||
"head":0,
|
||||
"tag":"VBZ",
|
||||
"orth":"plays"
|
||||
},
|
||||
{
|
||||
"dep":"dobj",
|
||||
"head":-1,
|
||||
"tag":"NNP",
|
||||
"orth":"Elianti"
|
||||
},
|
||||
{
|
||||
"dep":"punct",
|
||||
"head":-2,
|
||||
"tag":".",
|
||||
"orth":"."
|
||||
}
|
||||
data = [
|
||||
{
|
||||
"id": 1,
|
||||
"paragraphs": [
|
||||
{
|
||||
"sentences": [
|
||||
{
|
||||
"tokens": [
|
||||
{"dep": "nn", "head": 1, "tag": "NNP", "orth": "Ms."},
|
||||
{
|
||||
"dep": "nsubj",
|
||||
"head": 1,
|
||||
"tag": "NNP",
|
||||
"orth": "Haag",
|
||||
},
|
||||
{
|
||||
"dep": "ROOT",
|
||||
"head": 0,
|
||||
"tag": "VBZ",
|
||||
"orth": "plays",
|
||||
},
|
||||
{
|
||||
"dep": "dobj",
|
||||
"head": -1,
|
||||
"tag": "NNP",
|
||||
"orth": "Elianti",
|
||||
},
|
||||
{"dep": "punct", "head": -2, "tag": ".", "orth": "."},
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}]
|
||||
}
|
||||
],
|
||||
}
|
||||
]
|
||||
docs = json2docs(data)
|
||||
assert len(docs) == 1
|
||||
for doc in docs:
|
||||
|
|
|
@ -8,8 +8,9 @@ from ..tokens import Doc
|
|||
from ..attrs import SPACY, ORTH, intify_attr
|
||||
from ..errors import Errors
|
||||
|
||||
|
||||
# fmt: off
|
||||
ALL_ATTRS = ("ORTH", "TAG", "HEAD", "DEP", "ENT_IOB", "ENT_TYPE", "ENT_KB_ID", "LEMMA", "MORPH", "POS")
|
||||
# fmt: on
|
||||
|
||||
|
||||
class DocBin(object):
|
||||
|
@ -86,9 +87,7 @@ class DocBin(object):
|
|||
assert array.shape[0] == spaces.shape[0] # this should never happen
|
||||
spaces = spaces.reshape((spaces.shape[0], 1))
|
||||
self.spaces.append(numpy.asarray(spaces, dtype=bool))
|
||||
self.flags.append({
|
||||
"has_unknown_spaces": doc.has_unknown_spaces
|
||||
})
|
||||
self.flags.append({"has_unknown_spaces": doc.has_unknown_spaces})
|
||||
for token in doc:
|
||||
self.strings.add(token.text)
|
||||
self.strings.add(token.tag_)
|
||||
|
|
7
website/docs/api/architectures.md
Normal file
7
website/docs/api/architectures.md
Normal file
|
@ -0,0 +1,7 @@
|
|||
---
|
||||
title: Model Architectures
|
||||
teaser: Pre-defined model architectures included with the core library
|
||||
source: spacy/ml/models
|
||||
---
|
||||
|
||||
TODO: write
|
|
@ -13,6 +13,7 @@ menu:
|
|||
- ['Init Model', 'init-model']
|
||||
- ['Evaluate', 'evaluate']
|
||||
- ['Package', 'package']
|
||||
- ['Project', 'project']
|
||||
---
|
||||
|
||||
For a list of available commands, type `spacy --help`.
|
||||
|
@ -95,26 +96,29 @@ $ python -m spacy validate
|
|||
|
||||
## Convert {#convert}
|
||||
|
||||
Convert files into spaCy's [JSON format](/api/annotation#json-input) for use
|
||||
with the `train` command and other experiment management functions. The
|
||||
converter can be specified on the command line, or chosen based on the file
|
||||
extension of the input file.
|
||||
Convert files into spaCy's
|
||||
[binary training data format](/usage/training#data-format), a serialized
|
||||
[`DocBin`](/api/docbin), for use with the `train` command and other experiment
|
||||
management functions. The converter can be specified on the command line, or
|
||||
chosen based on the file extension of the input file.
|
||||
|
||||
```bash
|
||||
$ python -m spacy convert [input_file] [output_dir] [--file-type] [--converter]
|
||||
[--n-sents] [--morphology] [--lang]
|
||||
$ python -m spacy convert [input_file] [output_dir] [--converter]
|
||||
[--file-type] [--n-sents] [--seg-sents] [--model] [--morphology]
|
||||
[--merge-subtokens] [--ner-map] [--lang]
|
||||
```
|
||||
|
||||
| Argument | Type | Description |
|
||||
| ------------------------------------------------ | ---------- | ------------------------------------------------------------------------------------------------------------------------ |
|
||||
| `input_file` | positional | Input file. |
|
||||
| `output_dir` | positional | Output directory for converted file. Defaults to `"-"`, meaning data will be written to `stdout`. |
|
||||
| `--file-type`, `-t` <Tag variant="new">2.1</Tag> | option | Type of file to create. Either `spacy` (default) for binary [`DocBin`](/api/docbin) data or `json` for v2.x JSON format. |
|
||||
| `--converter`, `-c` <Tag variant="new">2</Tag> | option | Name of converter to use (see below). |
|
||||
| `--file-type`, `-t` <Tag variant="new">2.1</Tag> | option | Type of file to create. Either `spacy` (default) for binary [`DocBin`](/api/docbin) data or `json` for v2.x JSON format. |
|
||||
| `--n-sents`, `-n` | option | Number of sentences per document. |
|
||||
| `--seg-sents`, `-s` <Tag variant="new">2.2</Tag> | flag | Segment sentences (for `-c ner`) |
|
||||
| `--model`, `-b` <Tag variant="new">2.2</Tag> | option | Model for parser-based sentence segmentation (for `-s`) |
|
||||
| `--morphology`, `-m` | option | Enable appending morphology to tags. |
|
||||
| `--ner-map`, `-nm` | option | NER tag mapping (as JSON-encoded dict of entity types). |
|
||||
| `--lang`, `-l` <Tag variant="new">2.1</Tag> | option | Language code (if tokenizer required). |
|
||||
| `--help`, `-h` | flag | Show help message and available arguments. |
|
||||
| **CREATES** | binary | Binary [`DocBin`](/api/docbin) training data that can be used with [`spacy train`](/api/cli#train). |
|
||||
|
@ -136,20 +140,21 @@ stats, and find problems like invalid entity annotations, cyclic dependencies,
|
|||
low data labels and more.
|
||||
|
||||
```bash
|
||||
$ python -m spacy debug-data [lang] [train_path] [dev_path] [--base-model] [--pipeline] [--ignore-warnings] [--verbose] [--no-format]
|
||||
$ python -m spacy debug-data [lang] [train_path] [dev_path] [--base-model]
|
||||
[--pipeline] [--tag-map-path] [--ignore-warnings] [--verbose] [--no-format]
|
||||
```
|
||||
|
||||
| Argument | Type | Description |
|
||||
| ------------------------------------------------------ | ---------- | -------------------------------------------------------------------------------------------------- |
|
||||
| `lang` | positional | Model language. |
|
||||
| `train_path` | positional | Location of JSON-formatted training data. Can be a file or a directory of files. |
|
||||
| `dev_path` | positional | Location of JSON-formatted development data for evaluation. Can be a file or a directory of files. |
|
||||
| `--tag-map-path`, `-tm` <Tag variant="new">2.2.4</Tag> | option | Location of JSON-formatted tag map. |
|
||||
| `--base-model`, `-b` | option | Optional name of base model to update. Can be any loadable spaCy model. |
|
||||
| `--pipeline`, `-p` | option | Comma-separated names of pipeline components to train. Defaults to `'tagger,parser,ner'`. |
|
||||
| `--ignore-warnings`, `-IW` | flag | Ignore warnings, only show stats and errors. |
|
||||
| `--verbose`, `-V` | flag | Print additional information and explanations. |
|
||||
| `--no-format`, `-NF` | flag | Don't pretty-print the results. Use this if you want to write to a file. |
|
||||
| Argument | Type | Description |
|
||||
| ------------------------------------------------------ | ---------- | ------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `lang` | positional | Model language. |
|
||||
| `train_path` | positional | Location of [binary training data](/usage/training#data-format). Can be a file or a directory of files. |
|
||||
| `dev_path` | positional | Location of [binary development data](/usage/training#data-format) for evaluation. Can be a file or a directory of files. |
|
||||
| `--tag-map-path`, `-tm` <Tag variant="new">2.2.4</Tag> | option | Location of JSON-formatted tag map. |
|
||||
| `--base-model`, `-b` | option | Optional name of base model to update. Can be any loadable spaCy model. |
|
||||
| `--pipeline`, `-p` | option | Comma-separated names of pipeline components to train. Defaults to `'tagger,parser,ner'`. |
|
||||
| `--ignore-warnings`, `-IW` | flag | Ignore warnings, only show stats and errors. |
|
||||
| `--verbose`, `-V` | flag | Print additional information and explanations. |
|
||||
| `--no-format`, `-NF` | flag | Don't pretty-print the results. Use this if you want to write to a file. |
|
||||
|
||||
<Accordion title="Example output">
|
||||
|
||||
|
@ -292,6 +297,8 @@ will not be available.
|
|||
|
||||
## Train {#train}
|
||||
|
||||
<!-- TODO: document new training -->
|
||||
|
||||
Train a model. Expects data in spaCy's
|
||||
[JSON format](/api/annotation#json-input). On each epoch, a model will be saved
|
||||
out to the directory. Accuracy scores and model details will be added to a
|
||||
|
@ -345,47 +352,10 @@ $ python -m spacy train [lang] [output_path] [train_path] [dev_path]
|
|||
| `--help`, `-h` | flag | Show help message and available arguments. |
|
||||
| **CREATES** | model, pickle | A spaCy model on each epoch. |
|
||||
|
||||
### Environment variables for hyperparameters {#train-hyperparams new="2"}
|
||||
|
||||
spaCy lets you set hyperparameters for training via environment variables. For
|
||||
example:
|
||||
|
||||
```bash
|
||||
$ token_vector_width=256 learn_rate=0.0001 spacy train [...]
|
||||
```
|
||||
|
||||
> #### Usage with alias
|
||||
>
|
||||
> Environment variables keep the command simple and allow you to to
|
||||
> [create an alias](https://askubuntu.com/questions/17536/how-do-i-create-a-permanent-bash-alias/17537#17537)
|
||||
> for your custom `train` command while still being able to easily tweak the
|
||||
> hyperparameters.
|
||||
>
|
||||
> ```bash
|
||||
> alias train-parser="python -m spacy train en /output /data /train /dev -n 1000"
|
||||
> token_vector_width=256 train-parser
|
||||
> ```
|
||||
|
||||
| Name | Description | Default |
|
||||
| -------------------- | --------------------------------------------------- | ------- |
|
||||
| `dropout_from` | Initial dropout rate. | `0.2` |
|
||||
| `dropout_to` | Final dropout rate. | `0.2` |
|
||||
| `dropout_decay` | Rate of dropout change. | `0.0` |
|
||||
| `batch_from` | Initial batch size. | `1` |
|
||||
| `batch_to` | Final batch size. | `64` |
|
||||
| `batch_compound` | Rate of batch size acceleration. | `1.001` |
|
||||
| `token_vector_width` | Width of embedding tables and convolutional layers. | `128` |
|
||||
| `embed_size` | Number of rows in embedding tables. | `7500` |
|
||||
| `hidden_width` | Size of the parser's and NER's hidden layers. | `128` |
|
||||
| `learn_rate` | Learning rate. | `0.001` |
|
||||
| `optimizer_B1` | Momentum for the Adam solver. | `0.9` |
|
||||
| `optimizer_B2` | Adagrad-momentum for the Adam solver. | `0.999` |
|
||||
| `optimizer_eps` | Epsilon value for the Adam solver. | `1e-08` |
|
||||
| `L2_penalty` | L2 regularization penalty. | `1e-06` |
|
||||
| `grad_norm_clip` | Gradient L2 norm constraint. | `1.0` |
|
||||
|
||||
## Pretrain {#pretrain new="2.1" tag="experimental"}
|
||||
|
||||
<!-- TODO: document new pretrain command and link to new pretraining docs -->
|
||||
|
||||
Pre-train the "token to vector" (`tok2vec`) layer of pipeline components, using
|
||||
an approximate language-modeling objective. Specifically, we load pretrained
|
||||
vectors, and train a component like a CNN, BiLSTM, etc to predict vectors which
|
||||
|
@ -491,6 +461,8 @@ $ python -m spacy init-model [lang] [output_dir] [--jsonl-loc] [--vectors-loc]
|
|||
|
||||
## Evaluate {#evaluate new="2"}
|
||||
|
||||
<!-- TODO: document new evaluate command -->
|
||||
|
||||
Evaluate a model's accuracy and speed on JSON-formatted annotated data. Will
|
||||
print the results and optionally export
|
||||
[displaCy visualizations](/usage/visualizers) of a sample set of parses to
|
||||
|
@ -516,12 +488,20 @@ $ python -m spacy evaluate [model] [data_path] [--displacy-path] [--displacy-lim
|
|||
|
||||
## Package {#package}
|
||||
|
||||
Generate a [model Python package](/usage/training#models-generating) from an
|
||||
existing model data directory. All data files are copied over. If the path to a
|
||||
`meta.json` is supplied, or a `meta.json` is found in the input directory, this
|
||||
file is used. Otherwise, the data can be entered directly from the command line.
|
||||
After packaging, you can run `python setup.py sdist` from the newly created
|
||||
directory to turn your model into an installable archive file.
|
||||
Generate an installable
|
||||
[model Python package](/usage/training#models-generating) from an existing model
|
||||
data directory. All data files are copied over. If the path to a `meta.json` is
|
||||
supplied, or a `meta.json` is found in the input directory, this file is used.
|
||||
Otherwise, the data can be entered directly from the command line. spaCy will
|
||||
then create a `.tar.gz` archive file that you can distribute and install with
|
||||
`pip install`.
|
||||
|
||||
<Infobox title="New in v3.0" variant="warning">
|
||||
|
||||
The `spacy package` command now also builds the `.tar.gz` archive automatically,
|
||||
so you don't have to run `python setup.py sdist` separately anymore.
|
||||
|
||||
</Infobox>
|
||||
|
||||
```bash
|
||||
$ python -m spacy package [input_dir] [output_dir] [--meta-path] [--create-meta] [--force]
|
||||
|
@ -531,7 +511,6 @@ $ python -m spacy package [input_dir] [output_dir] [--meta-path] [--create-meta]
|
|||
### Example
|
||||
python -m spacy package /input /output
|
||||
cd /output/en_model-0.0.0
|
||||
python setup.py sdist
|
||||
pip install dist/en_model-0.0.0.tar.gz
|
||||
```
|
||||
|
||||
|
@ -541,6 +520,23 @@ pip install dist/en_model-0.0.0.tar.gz
|
|||
| `output_dir` | positional | Directory to create package folder in. |
|
||||
| `--meta-path`, `-m` <Tag variant="new">2</Tag> | option | Path to `meta.json` file (optional). |
|
||||
| `--create-meta`, `-c` <Tag variant="new">2</Tag> | flag | Create a `meta.json` file on the command line, even if one already exists in the directory. If an existing file is found, its entries will be shown as the defaults in the command line prompt. |
|
||||
| `--version`, `-v` <Tag variant="new">3</Tag> | option | Package version to override in meta. Useful when training new versions, as it doesn't require editing the meta template. |
|
||||
| `--force`, `-f` | flag | Force overwriting of existing folder in output directory. |
|
||||
| `--help`, `-h` | flag | Show help message and available arguments. |
|
||||
| **CREATES** | directory | A Python package containing the spaCy model. |
|
||||
|
||||
## Project {#project}
|
||||
|
||||
<!-- TODO: document project command and subcommands. We should probably wait and only finalize this once we've finalized the design -->
|
||||
|
||||
### project clone {#project-clone}
|
||||
|
||||
### project assets {#project-assets}
|
||||
|
||||
### project run-all {#project-run-all}
|
||||
|
||||
### project run {#project-run}
|
||||
|
||||
### project init {#project-init}
|
||||
|
||||
### project update-dvc {#project-update-dvc}
|
||||
|
|
37
website/docs/api/corpus.md
Normal file
37
website/docs/api/corpus.md
Normal file
|
@ -0,0 +1,37 @@
|
|||
---
|
||||
title: Corpus
|
||||
teaser: An annotated corpus
|
||||
tag: class
|
||||
source: spacy/gold/corpus.py
|
||||
new: 3
|
||||
---
|
||||
|
||||
This class manages annotated corpora and can read training and development
|
||||
datasets in the [DocBin](/api/docbin) (`.spacy`) format.
|
||||
|
||||
## Corpus.\_\_init\_\_ {#init tag="method"}
|
||||
|
||||
Create a `Corpus`. The input data can be a file or a directory of files.
|
||||
|
||||
| Name | Type | Description |
|
||||
| ----------- | ------------ | ---------------------------------------------------------------- |
|
||||
| `train` | str / `Path` | Training data (`.spacy` file or directory of `.spacy` files). |
|
||||
| `dev` | str / `Path` | Development data (`.spacy` file or directory of `.spacy` files). |
|
||||
| `limit` | int | Maximum number of examples returned. |
|
||||
| **RETURNS** | `Corpus` | The newly constructed object. |
|
||||
|
||||
<!-- TODO: document remaining methods / decide which to document -->
|
||||
|
||||
## Corpus.walk_corpus {#walk_corpus tag="staticmethod"}
|
||||
|
||||
## Corpus.make_examples {#make_examples tag="method"}
|
||||
|
||||
## Corpus.make_examples_gold_preproc {#make_examples_gold_preproc tag="method"}
|
||||
|
||||
## Corpus.read_docbin {#read_docbin tag="method"}
|
||||
|
||||
## Corpus.count_train {#count_train tag="method"}
|
||||
|
||||
## Corpus.train_dataset {#train_dataset tag="method"}
|
||||
|
||||
## Corpus.dev_dataset {#dev_dataset tag="method"}
|
|
@ -123,7 +123,7 @@ details, see the documentation on
|
|||
|
||||
| Name | Type | Description |
|
||||
| --------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `name` | str | Name of the attribute to set by the extension. For example, `'my_attr'` will be available as `doc._.my_attr`. |
|
||||
| `name` | str | Name of the attribute to set by the extension. For example, `"my_attr"` will be available as `doc._.my_attr`. |
|
||||
| `default` | - | Optional default value of the attribute if no getter or method is defined. |
|
||||
| `method` | callable | Set a custom method on the object, for example `doc._.compare(other_doc)`. |
|
||||
| `getter` | callable | Getter function that takes the object and returns an attribute value. Is called when the user accesses the `._` attribute. |
|
||||
|
@ -140,8 +140,8 @@ Look up a previously registered extension by name. Returns a 4-tuple
|
|||
>
|
||||
> ```python
|
||||
> from spacy.tokens import Doc
|
||||
> Doc.set_extension('has_city', default=False)
|
||||
> extension = Doc.get_extension('has_city')
|
||||
> Doc.set_extension("has_city", default=False)
|
||||
> extension = Doc.get_extension("has_city")
|
||||
> assert extension == (False, None, None, None)
|
||||
> ```
|
||||
|
||||
|
@ -158,8 +158,8 @@ Check whether an extension has been registered on the `Doc` class.
|
|||
>
|
||||
> ```python
|
||||
> from spacy.tokens import Doc
|
||||
> Doc.set_extension('has_city', default=False)
|
||||
> assert Doc.has_extension('has_city')
|
||||
> Doc.set_extension("has_city", default=False)
|
||||
> assert Doc.has_extension("has_city")
|
||||
> ```
|
||||
|
||||
| Name | Type | Description |
|
||||
|
@ -175,9 +175,9 @@ Remove a previously registered extension.
|
|||
>
|
||||
> ```python
|
||||
> from spacy.tokens import Doc
|
||||
> Doc.set_extension('has_city', default=False)
|
||||
> removed = Doc.remove_extension('has_city')
|
||||
> assert not Doc.has_extension('has_city')
|
||||
> Doc.set_extension("has_city", default=False)
|
||||
> removed = Doc.remove_extension("has_city")
|
||||
> assert not Doc.has_extension("has_city")
|
||||
> ```
|
||||
|
||||
| Name | Type | Description |
|
||||
|
@ -204,7 +204,7 @@ the character indices don't map to a valid span.
|
|||
| `end` | int | The index of the last character after the span. |
|
||||
| `label` | uint64 / str | A label to attach to the span, e.g. for named entities. |
|
||||
| `kb_id` <Tag variant="new">2.2</Tag> | uint64 / str | An ID from a knowledge base to capture the meaning of a named entity. |
|
||||
| `vector` | `numpy.ndarray[ndim=1, dtype='float32']` | A meaning representation of the span. |
|
||||
| `vector` | `numpy.ndarray[ndim=1, dtype="float32"]` | A meaning representation of the span. |
|
||||
| **RETURNS** | `Span` | The newly constructed object or `None`. |
|
||||
|
||||
## Doc.similarity {#similarity tag="method" model="vectors"}
|
||||
|
@ -264,7 +264,7 @@ ancestor is found, e.g. if span excludes a necessary ancestor.
|
|||
|
||||
| Name | Type | Description |
|
||||
| ----------- | -------------------------------------- | ----------------------------------------------- |
|
||||
| **RETURNS** | `numpy.ndarray[ndim=2, dtype='int32']` | The lowest common ancestor matrix of the `Doc`. |
|
||||
| **RETURNS** | `numpy.ndarray[ndim=2, dtype="int32"]` | The lowest common ancestor matrix of the `Doc`. |
|
||||
|
||||
## Doc.to_json {#to_json tag="method" new="2.1"}
|
||||
|
||||
|
@ -303,7 +303,7 @@ Export given token attributes to a numpy `ndarray`. If `attr_ids` is a sequence
|
|||
of `M` attributes, the output array will be of shape `(N, M)`, where `N` is the
|
||||
length of the `Doc` (in tokens). If `attr_ids` is a single attribute, the output
|
||||
shape will be `(N,)`. You can specify attributes by integer ID (e.g.
|
||||
`spacy.attrs.LEMMA`) or string name (e.g. 'LEMMA' or 'lemma'). The values will
|
||||
`spacy.attrs.LEMMA`) or string name (e.g. "LEMMA" or "lemma"). The values will
|
||||
be 64-bit integers.
|
||||
|
||||
Returns a 2D array with one row per token and one column per attribute (when
|
||||
|
@ -323,7 +323,7 @@ Returns a 2D array with one row per token and one column per attribute (when
|
|||
| Name | Type | Description |
|
||||
| ----------- | ---------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- |
|
||||
| `attr_ids` | list or int or string | A list of attributes (int IDs or string names) or a single attribute (int ID or string name) |
|
||||
| **RETURNS** | `numpy.ndarray[ndim=2, dtype='uint64']` or `numpy.ndarray[ndim=1, dtype='uint64']` | The exported attributes as a numpy array. |
|
||||
| **RETURNS** | `numpy.ndarray[ndim=2, dtype="uint64"]` or `numpy.ndarray[ndim=1, dtype="uint64"]` | The exported attributes as a numpy array. |
|
||||
|
||||
## Doc.from_array {#from_array tag="method"}
|
||||
|
||||
|
@ -345,14 +345,14 @@ array of attributes.
|
|||
| Name | Type | Description |
|
||||
| ----------- | -------------------------------------- | ------------------------------------------------------------------------- |
|
||||
| `attrs` | list | A list of attribute ID ints. |
|
||||
| `array` | `numpy.ndarray[ndim=2, dtype='int32']` | The attribute values to load. |
|
||||
| `array` | `numpy.ndarray[ndim=2, dtype="int32"]` | The attribute values to load. |
|
||||
| `exclude` | list | String names of [serialization fields](#serialization-fields) to exclude. |
|
||||
| **RETURNS** | `Doc` | Itself. |
|
||||
|
||||
|
||||
## Doc.from_docs {#from_docs tag="staticmethod"}
|
||||
|
||||
Concatenate multiple `Doc` objects to form a new one. Raises an error if the `Doc` objects do not all share the same `Vocab`.
|
||||
Concatenate multiple `Doc` objects to form a new one. Raises an error if the
|
||||
`Doc` objects do not all share the same `Vocab`.
|
||||
|
||||
> #### Example
|
||||
>
|
||||
|
@ -634,7 +634,7 @@ vectors.
|
|||
|
||||
| Name | Type | Description |
|
||||
| ----------- | ---------------------------------------- | ------------------------------------------------------- |
|
||||
| **RETURNS** | `numpy.ndarray[ndim=1, dtype='float32']` | A 1D numpy array representing the document's semantics. |
|
||||
| **RETURNS** | `numpy.ndarray[ndim=1, dtype="float32"]` | A 1D numpy array representing the document's semantics. |
|
||||
|
||||
## Doc.vector_norm {#vector_norm tag="property" model="vectors"}
|
||||
|
||||
|
|
|
@ -1,24 +0,0 @@
|
|||
---
|
||||
title: GoldCorpus
|
||||
teaser: An annotated corpus, using the JSON file format
|
||||
tag: class
|
||||
source: spacy/gold.pyx
|
||||
new: 2
|
||||
---
|
||||
|
||||
This class manages annotations for tagging, dependency parsing and NER.
|
||||
|
||||
## GoldCorpus.\_\_init\_\_ {#init tag="method"}
|
||||
|
||||
Create a `GoldCorpus`. IF the input data is an iterable, each item should be a
|
||||
`(text, paragraphs)` tuple, where each paragraph is a tuple
|
||||
`(sentences, brackets)`, and each sentence is a tuple
|
||||
`(ids, words, tags, heads, ner)`. See the implementation of
|
||||
[`gold.read_json_file`](https://github.com/explosion/spaCy/tree/master/spacy/gold.pyx)
|
||||
for further details.
|
||||
|
||||
| Name | Type | Description |
|
||||
| ----------- | ----------------------- | ------------------------------------------------------------ |
|
||||
| `train` | str / `Path` / iterable | Training data, as a path (file or directory) or iterable. |
|
||||
| `dev` | str / `Path` / iterable | Development data, as a path (file or directory) or iterable. |
|
||||
| **RETURNS** | `GoldCorpus` | The newly constructed object. |
|
|
@ -1,10 +1,8 @@
|
|||
---
|
||||
title: Architecture
|
||||
next: /api/annotation
|
||||
title: Library Architecture
|
||||
next: /api/architectures
|
||||
---
|
||||
|
||||
## Library architecture {#architecture}
|
||||
|
||||
import Architecture101 from 'usage/101/\_architecture.md'
|
||||
|
||||
<Architecture101 />
|
||||
|
|
|
@ -296,15 +296,13 @@ component function.
|
|||
Disable one or more pipeline components. If used as a context manager, the
|
||||
pipeline will be restored to the initial state at the end of the block.
|
||||
Otherwise, a `DisabledPipes` object is returned, that has a `.restore()` method
|
||||
you can use to undo your changes.
|
||||
|
||||
You can specify either `disable` (as a list or string), or `enable`. In the
|
||||
latter case, all components not in the `enable` list, will be disabled.
|
||||
you can use to undo your changes. You can specify either `disable` (as a list or
|
||||
string), or `enable`. In the latter case, all components not in the `enable`
|
||||
list, will be disabled.
|
||||
|
||||
> #### Example
|
||||
>
|
||||
> ```python
|
||||
> # New API as of v3.0
|
||||
> with nlp.select_pipes(disable=["tagger", "parser"]):
|
||||
> nlp.begin_training()
|
||||
>
|
||||
|
@ -316,15 +314,7 @@ latter case, all components not in the `enable` list, will be disabled.
|
|||
> disabled.restore()
|
||||
> ```
|
||||
|
||||
| Name | Type | Description |
|
||||
| ----------- | --------------- | ------------------------------------------------------------------------------------ |
|
||||
| `disable` | list | Names of pipeline components to disable. |
|
||||
| `disable` | str | Name of pipeline component to disable. |
|
||||
| `enable` | list | Names of pipeline components that will not be disabled. |
|
||||
| `enable` | str | Name of pipeline component that will not be disabled. |
|
||||
| **RETURNS** | `DisabledPipes` | The disabled pipes that can be restored by calling the object's `.restore()` method. |
|
||||
|
||||
<Infobox title="Changed in v3.0" variant="warning">
|
||||
<Infobox title="Changed in v3.0" variant="warning" id="disable_pipes">
|
||||
|
||||
As of spaCy v3.0, the `disable_pipes` method has been renamed to `select_pipes`:
|
||||
|
||||
|
@ -335,6 +325,12 @@ As of spaCy v3.0, the `disable_pipes` method has been renamed to `select_pipes`:
|
|||
|
||||
</Infobox>
|
||||
|
||||
| Name | Type | Description |
|
||||
| ----------- | --------------- | ------------------------------------------------------------------------------------ |
|
||||
| `disable` | str / list | Name(s) of pipeline components to disable. |
|
||||
| `enable` | str / list | Names(s) of pipeline components that will not be disabled. |
|
||||
| **RETURNS** | `DisabledPipes` | The disabled pipes that can be restored by calling the object's `.restore()` method. |
|
||||
|
||||
## Language.to_disk {#to_disk tag="method" new="2"}
|
||||
|
||||
Save the current state to a directory. If a model is loaded, this will **include
|
||||
|
|
29
website/docs/api/sentencerecognizer.md
Normal file
29
website/docs/api/sentencerecognizer.md
Normal file
|
@ -0,0 +1,29 @@
|
|||
---
|
||||
title: SentenceRecognizer
|
||||
tag: class
|
||||
source: spacy/pipeline/pipes.pyx
|
||||
new: 3
|
||||
---
|
||||
|
||||
A trainable pipeline component for sentence segmentation. For a simpler,
|
||||
ruse-based strategy, see the [`Sentencizer`](/api/sentencizer). This class is a
|
||||
subclass of `Pipe` and follows the same API. The component is also available via
|
||||
the string name `"senter"`. After initialization, it is typically added to the
|
||||
processing pipeline using [`nlp.add_pipe`](/api/language#add_pipe).
|
||||
|
||||
## SentenceRecognizer.\_\_init\_\_ {#init tag="method"}
|
||||
|
||||
Initialize the sentence recognizer.
|
||||
|
||||
> #### Example
|
||||
>
|
||||
> ```python
|
||||
> # Construction via create_pipe
|
||||
> senter = nlp.create_pipe("senter")
|
||||
>
|
||||
> # Construction from class
|
||||
> from spacy.pipeline import SentenceRecognizer
|
||||
> senter = SentenceRecognizer()
|
||||
> ```
|
||||
|
||||
<!-- TODO: document, similar to other trainable pipeline components -->
|
|
@ -12,19 +12,6 @@ require a statistical model to be loaded. The component is also available via
|
|||
the string name `"sentencizer"`. After initialization, it is typically added to
|
||||
the processing pipeline using [`nlp.add_pipe`](/api/language#add_pipe).
|
||||
|
||||
<Infobox title="Important note" variant="warning">
|
||||
|
||||
Compared to the previous `SentenceSegmenter` class, the `Sentencizer` component
|
||||
doesn't add a hook to `doc.user_hooks["sents"]`. Instead, it iterates over the
|
||||
tokens in the `Doc` and sets the `Token.is_sent_start` property. The
|
||||
`SentenceSegmenter` is still available if you import it directly:
|
||||
|
||||
```python
|
||||
from spacy.pipeline import SentenceSegmenter
|
||||
```
|
||||
|
||||
</Infobox>
|
||||
|
||||
## Sentencizer.\_\_init\_\_ {#init tag="method"}
|
||||
|
||||
Initialize the sentencizer.
|
||||
|
@ -40,10 +27,24 @@ Initialize the sentencizer.
|
|||
> sentencizer = Sentencizer()
|
||||
> ```
|
||||
|
||||
| Name | Type | Description |
|
||||
| ------------- | ------------- | ------------------------------------------------------------------------------------------------------ |
|
||||
| `punct_chars` | list | Optional custom list of punctuation characters that mark sentence ends. Defaults to `['!', '.', '?', '։', '؟', '۔', '܀', '܁', '܂', '߹', '।', '॥', '၊', '။', '።', '፧', '፨', '᙮', '᜵', '᜶', '᠃', '᠉', '᥄', '᥅', '᪨', '᪩', '᪪', '᪫', '᭚', '᭛', '᭞', '᭟', '᰻', '᰼', '᱾', '᱿', '‼', '‽', '⁇', '⁈', '⁉', '⸮', '⸼', '꓿', '꘎', '꘏', '꛳', '꛷', '꡶', '꡷', '꣎', '꣏', '꤯', '꧈', '꧉', '꩝', '꩞', '꩟', '꫰', '꫱', '꯫', '﹒', '﹖', '﹗', '!', '.', '?', '𐩖', '𐩗', '𑁇', '𑁈', '𑂾', '𑂿', '𑃀', '𑃁', '𑅁', '𑅂', '𑅃', '𑇅', '𑇆', '𑇍', '𑇞', '𑇟', '𑈸', '𑈹', '𑈻', '𑈼', '𑊩', '𑑋', '𑑌', '𑗂', '𑗃', '𑗉', '𑗊', '𑗋', '𑗌', '𑗍', '𑗎', '𑗏', '𑗐', '𑗑', '𑗒', '𑗓', '𑗔', '𑗕', '𑗖', '𑗗', '𑙁', '𑙂', '𑜼', '𑜽', '𑜾', '𑩂', '𑩃', '𑪛', '𑪜', '𑱁', '𑱂', '𖩮', '𖩯', '𖫵', '𖬷', '𖬸', '𖭄', '𛲟', '𝪈', '。', '。']`. |
|
||||
| **RETURNS** | `Sentencizer` | The newly constructed object. |
|
||||
| Name | Type | Description |
|
||||
| ------------- | ------------- | ----------------------------------------------------------------------------------------------- |
|
||||
| `punct_chars` | list | Optional custom list of punctuation characters that mark sentence ends. See below for defaults. |
|
||||
| **RETURNS** | `Sentencizer` | The newly constructed object. |
|
||||
|
||||
```python
|
||||
### punct_chars defaults
|
||||
['!', '.', '?', '։', '؟', '۔', '܀', '܁', '܂', '߹', '।', '॥', '၊', '။', '።',
|
||||
'፧', '፨', '᙮', '᜵', '᜶', '᠃', '᠉', '᥄', '᥅', '᪨', '᪩', '᪪', '᪫',
|
||||
'᭚', '᭛', '᭞', '᭟', '᰻', '᰼', '᱾', '᱿', '‼', '‽', '⁇', '⁈', '⁉',
|
||||
'⸮', '⸼', '꓿', '꘎', '꘏', '꛳', '꛷', '꡶', '꡷', '꣎', '꣏', '꤯', '꧈',
|
||||
'꧉', '꩝', '꩞', '꩟', '꫰', '꫱', '꯫', '﹒', '﹖', '﹗', '!', '.', '?',
|
||||
'𐩖', '𐩗', '𑁇', '𑁈', '𑂾', '𑂿', '𑃀', '𑃁', '𑅁', '𑅂', '𑅃', '𑇅',
|
||||
'𑇆', '𑇍', '𑇞', '𑇟', '𑈸', '𑈹', '𑈻', '𑈼', '𑊩', '𑑋', '𑑌', '𑗂',
|
||||
'𑗃', '𑗉', '𑗊', '𑗋', '𑗌', '𑗍', '𑗎', '𑗏', '𑗐', '𑗑', '𑗒', '𑗓',
|
||||
'𑗔', '𑗕', '𑗖', '𑗗', '𑙁', '𑙂', '𑜼', '𑜽', '𑜾', '𑩂', '𑩃', '𑪛',
|
||||
'𑪜', '𑱁', '𑱂', '𖩮', '𖩯', '𖫵', '𖬷', '𖬸', '𖭄', '𛲟', '𝪈', '。', '。']
|
||||
```
|
||||
|
||||
## Sentencizer.\_\_call\_\_ {#call tag="method"}
|
||||
|
||||
|
|
|
@ -25,7 +25,7 @@ Create a Span object from the slice `doc[start : end]`.
|
|||
| `end` | int | The index of the first token after the span. |
|
||||
| `label` | int / str | A label to attach to the span, e.g. for named entities. As of v2.1, the label can also be a string. |
|
||||
| `kb_id` | int / str | A knowledge base ID to attach to the span, e.g. for named entities. The ID can be an integer or a string. |
|
||||
| `vector` | `numpy.ndarray[ndim=1, dtype='float32']` | A meaning representation of the span. |
|
||||
| `vector` | `numpy.ndarray[ndim=1, dtype="float32"]` | A meaning representation of the span. |
|
||||
| **RETURNS** | `Span` | The newly constructed object. |
|
||||
|
||||
## Span.\_\_getitem\_\_ {#getitem tag="method"}
|
||||
|
@ -110,7 +110,7 @@ For details, see the documentation on
|
|||
|
||||
| Name | Type | Description |
|
||||
| --------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `name` | str | Name of the attribute to set by the extension. For example, `'my_attr'` will be available as `span._.my_attr`. |
|
||||
| `name` | str | Name of the attribute to set by the extension. For example, `"my_attr"` will be available as `span._.my_attr`. |
|
||||
| `default` | - | Optional default value of the attribute if no getter or method is defined. |
|
||||
| `method` | callable | Set a custom method on the object, for example `span._.compare(other_span)`. |
|
||||
| `getter` | callable | Getter function that takes the object and returns an attribute value. Is called when the user accesses the `._` attribute. |
|
||||
|
@ -191,7 +191,7 @@ the character indices don't map to a valid span.
|
|||
| `end` | int | The index of the last character after the span. |
|
||||
| `label` | uint64 / str | A label to attach to the span, e.g. for named entities. |
|
||||
| `kb_id` | uint64 / str | An ID from a knowledge base to capture the meaning of a named entity. |
|
||||
| `vector` | `numpy.ndarray[ndim=1, dtype='float32']` | A meaning representation of the span. |
|
||||
| `vector` | `numpy.ndarray[ndim=1, dtype="float32"]` | A meaning representation of the span. |
|
||||
| **RETURNS** | `Span` | The newly constructed object or `None`. |
|
||||
|
||||
## Span.similarity {#similarity tag="method" model="vectors"}
|
||||
|
@ -232,7 +232,7 @@ ancestor is found, e.g. if span excludes a necessary ancestor.
|
|||
|
||||
| Name | Type | Description |
|
||||
| ----------- | -------------------------------------- | ------------------------------------------------ |
|
||||
| **RETURNS** | `numpy.ndarray[ndim=2, dtype='int32']` | The lowest common ancestor matrix of the `Span`. |
|
||||
| **RETURNS** | `numpy.ndarray[ndim=2, dtype="int32"]` | The lowest common ancestor matrix of the `Span`. |
|
||||
|
||||
## Span.to_array {#to_array tag="method" new="2"}
|
||||
|
||||
|
@ -440,7 +440,7 @@ vectors.
|
|||
|
||||
| Name | Type | Description |
|
||||
| ----------- | ---------------------------------------- | --------------------------------------------------- |
|
||||
| **RETURNS** | `numpy.ndarray[ndim=1, dtype='float32']` | A 1D numpy array representing the span's semantics. |
|
||||
| **RETURNS** | `numpy.ndarray[ndim=1, dtype="float32"]` | A 1D numpy array representing the span's semantics. |
|
||||
|
||||
## Span.vector_norm {#vector_norm tag="property" model="vectors"}
|
||||
|
||||
|
|
|
@ -58,7 +58,7 @@ For details, see the documentation on
|
|||
|
||||
| Name | Type | Description |
|
||||
| --------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `name` | str | Name of the attribute to set by the extension. For example, `'my_attr'` will be available as `token._.my_attr`. |
|
||||
| `name` | str | Name of the attribute to set by the extension. For example, `"my_attr"` will be available as `token._.my_attr`. |
|
||||
| `default` | - | Optional default value of the attribute if no getter or method is defined. |
|
||||
| `method` | callable | Set a custom method on the object, for example `token._.compare(other_token)`. |
|
||||
| `getter` | callable | Getter function that takes the object and returns an attribute value. Is called when the user accesses the `._` attribute. |
|
||||
|
@ -370,7 +370,7 @@ A real-valued meaning representation.
|
|||
|
||||
| Name | Type | Description |
|
||||
| ----------- | ---------------------------------------- | ---------------------------------------------------- |
|
||||
| **RETURNS** | `numpy.ndarray[ndim=1, dtype='float32']` | A 1D numpy array representing the token's semantics. |
|
||||
| **RETURNS** | `numpy.ndarray[ndim=1, dtype="float32"]` | A 1D numpy array representing the token's semantics. |
|
||||
|
||||
## Token.vector_norm {#vector_norm tag="property" model="vectors"}
|
||||
|
||||
|
@ -435,8 +435,8 @@ The L2 norm of the token's vector representation.
|
|||
| `is_upper` | bool | Is the token in uppercase? Equivalent to `token.text.isupper()`. |
|
||||
| `is_title` | bool | Is the token in titlecase? Equivalent to `token.text.istitle()`. |
|
||||
| `is_punct` | bool | Is the token punctuation? |
|
||||
| `is_left_punct` | bool | Is the token a left punctuation mark, e.g. `'('` ? |
|
||||
| `is_right_punct` | bool | Is the token a right punctuation mark, e.g. `')'` ? |
|
||||
| `is_left_punct` | bool | Is the token a left punctuation mark, e.g. `"("` ? |
|
||||
| `is_right_punct` | bool | Is the token a right punctuation mark, e.g. `")"` ? |
|
||||
| `is_space` | bool | Does the token consist of whitespace characters? Equivalent to `token.text.isspace()`. |
|
||||
| `is_bracket` | bool | Is the token a bracket? |
|
||||
| `is_quote` | bool | Is the token a quotation mark? |
|
||||
|
|
|
@ -3,8 +3,8 @@ title: Top-level Functions
|
|||
menu:
|
||||
- ['spacy', 'spacy']
|
||||
- ['displacy', 'displacy']
|
||||
- ['Data & Alignment', 'gold']
|
||||
- ['Utility Functions', 'util']
|
||||
- ['Compatibility', 'compat']
|
||||
---
|
||||
|
||||
## spaCy {#spacy hidden="true"}
|
||||
|
@ -77,8 +77,8 @@ meta data as a dictionary instead, you can use the `meta` attribute on your
|
|||
>
|
||||
> ```python
|
||||
> spacy.info()
|
||||
> spacy.info("en")
|
||||
> spacy.info("de", markdown=True)
|
||||
> spacy.info("en_core_web_sm")
|
||||
> spacy.info(markdown=True)
|
||||
> ```
|
||||
|
||||
| Name | Type | Description |
|
||||
|
@ -259,6 +259,156 @@ colors for them. Your application or model package can also expose a
|
|||
[`spacy_displacy_colors` entry point](/usage/saving-loading#entry-points-displacy)
|
||||
to add custom labels and their colors automatically.
|
||||
|
||||
## Training data and alignment {#gold source="spacy/gold"}
|
||||
|
||||
### gold.docs_to_json {#docs_to_json tag="function"}
|
||||
|
||||
Convert a list of Doc objects into the
|
||||
[JSON-serializable format](/api/annotation#json-input) used by the
|
||||
[`spacy train`](/api/cli#train) command. Each input doc will be treated as a
|
||||
'paragraph' in the output doc.
|
||||
|
||||
> #### Example
|
||||
>
|
||||
> ```python
|
||||
> from spacy.gold import docs_to_json
|
||||
>
|
||||
> doc = nlp("I like London")
|
||||
> json_data = docs_to_json([doc])
|
||||
> ```
|
||||
|
||||
| Name | Type | Description |
|
||||
| ----------- | ---------------- | ------------------------------------------ |
|
||||
| `docs` | iterable / `Doc` | The `Doc` object(s) to convert. |
|
||||
| `id` | int | ID to assign to the JSON. Defaults to `0`. |
|
||||
| **RETURNS** | dict | The data in spaCy's JSON format. |
|
||||
|
||||
### gold.align {#align tag="function"}
|
||||
|
||||
Calculate alignment tables between two tokenizations, using the Levenshtein
|
||||
algorithm. The alignment is case-insensitive.
|
||||
|
||||
<Infobox title="Important note" variant="warning">
|
||||
|
||||
The current implementation of the alignment algorithm assumes that both
|
||||
tokenizations add up to the same string. For example, you'll be able to align
|
||||
`["I", "'", "m"]` and `["I", "'m"]`, which both add up to `"I'm"`, but not
|
||||
`["I", "'m"]` and `["I", "am"]`.
|
||||
|
||||
</Infobox>
|
||||
|
||||
> #### Example
|
||||
>
|
||||
> ```python
|
||||
> from spacy.gold import align
|
||||
>
|
||||
> bert_tokens = ["obama", "'", "s", "podcast"]
|
||||
> spacy_tokens = ["obama", "'s", "podcast"]
|
||||
> alignment = align(bert_tokens, spacy_tokens)
|
||||
> cost, a2b, b2a, a2b_multi, b2a_multi = alignment
|
||||
> ```
|
||||
|
||||
| Name | Type | Description |
|
||||
| ----------- | ----- | -------------------------------------------------------------------------- |
|
||||
| `tokens_a` | list | String values of candidate tokens to align. |
|
||||
| `tokens_b` | list | String values of reference tokens to align. |
|
||||
| **RETURNS** | tuple | A `(cost, a2b, b2a, a2b_multi, b2a_multi)` tuple describing the alignment. |
|
||||
|
||||
The returned tuple contains the following alignment information:
|
||||
|
||||
> #### Example
|
||||
>
|
||||
> ```python
|
||||
> a2b = array([0, -1, -1, 2])
|
||||
> b2a = array([0, 2, 3])
|
||||
> a2b_multi = {1: 1, 2: 1}
|
||||
> b2a_multi = {}
|
||||
> ```
|
||||
>
|
||||
> If `a2b[3] == 2`, that means that `tokens_a[3]` aligns to `tokens_b[2]`. If
|
||||
> there's no one-to-one alignment for a token, it has the value `-1`.
|
||||
|
||||
| Name | Type | Description |
|
||||
| ----------- | -------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `cost` | int | The number of misaligned tokens. |
|
||||
| `a2b` | `numpy.ndarray[ndim=1, dtype='int32']` | One-to-one mappings of indices in `tokens_a` to indices in `tokens_b`. |
|
||||
| `b2a` | `numpy.ndarray[ndim=1, dtype='int32']` | One-to-one mappings of indices in `tokens_b` to indices in `tokens_a`. |
|
||||
| `a2b_multi` | dict | A dictionary mapping indices in `tokens_a` to indices in `tokens_b`, where multiple tokens of `tokens_a` align to the same token of `tokens_b`. |
|
||||
| `b2a_multi` | dict | A dictionary mapping indices in `tokens_b` to indices in `tokens_a`, where multiple tokens of `tokens_b` align to the same token of `tokens_a`. |
|
||||
|
||||
### gold.biluo_tags_from_offsets {#biluo_tags_from_offsets tag="function"}
|
||||
|
||||
Encode labelled spans into per-token tags, using the
|
||||
[BILUO scheme](/api/annotation#biluo) (Begin, In, Last, Unit, Out). Returns a
|
||||
list of strings, describing the tags. Each tag string will be of the form of
|
||||
either `""`, `"O"` or `"{action}-{label}"`, where action is one of `"B"`, `"I"`,
|
||||
`"L"`, `"U"`. The string `"-"` is used where the entity offsets don't align with
|
||||
the tokenization in the `Doc` object. The training algorithm will view these as
|
||||
missing values. `O` denotes a non-entity token. `B` denotes the beginning of a
|
||||
multi-token entity, `I` the inside of an entity of three or more tokens, and `L`
|
||||
the end of an entity of two or more tokens. `U` denotes a single-token entity.
|
||||
|
||||
> #### Example
|
||||
>
|
||||
> ```python
|
||||
> from spacy.gold import biluo_tags_from_offsets
|
||||
>
|
||||
> doc = nlp("I like London.")
|
||||
> entities = [(7, 13, "LOC")]
|
||||
> tags = biluo_tags_from_offsets(doc, entities)
|
||||
> assert tags == ["O", "O", "U-LOC", "O"]
|
||||
> ```
|
||||
|
||||
| Name | Type | Description |
|
||||
| ----------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `doc` | `Doc` | The document that the entity offsets refer to. The output tags will refer to the token boundaries within the document. |
|
||||
| `entities` | iterable | A sequence of `(start, end, label)` triples. `start` and `end` should be character-offset integers denoting the slice into the original string. |
|
||||
| **RETURNS** | list | str strings, describing the [BILUO](/api/annotation#biluo) tags. |
|
||||
|
||||
### gold.offsets_from_biluo_tags {#offsets_from_biluo_tags tag="function"}
|
||||
|
||||
Encode per-token tags following the [BILUO scheme](/api/annotation#biluo) into
|
||||
entity offsets.
|
||||
|
||||
> #### Example
|
||||
>
|
||||
> ```python
|
||||
> from spacy.gold import offsets_from_biluo_tags
|
||||
>
|
||||
> doc = nlp("I like London.")
|
||||
> tags = ["O", "O", "U-LOC", "O"]
|
||||
> entities = offsets_from_biluo_tags(doc, tags)
|
||||
> assert entities == [(7, 13, "LOC")]
|
||||
> ```
|
||||
|
||||
| Name | Type | Description |
|
||||
| ----------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `doc` | `Doc` | The document that the BILUO tags refer to. |
|
||||
| `entities` | iterable | A sequence of [BILUO](/api/annotation#biluo) tags with each tag describing one token. Each tag string will be of the form of either `""`, `"O"` or `"{action}-{label}"`, where action is one of `"B"`, `"I"`, `"L"`, `"U"`. |
|
||||
| **RETURNS** | list | A sequence of `(start, end, label)` triples. `start` and `end` will be character-offset integers denoting the slice into the original string. |
|
||||
|
||||
### gold.spans_from_biluo_tags {#spans_from_biluo_tags tag="function" new="2.1"}
|
||||
|
||||
Encode per-token tags following the [BILUO scheme](/api/annotation#biluo) into
|
||||
[`Span`](/api/span) objects. This can be used to create entity spans from
|
||||
token-based tags, e.g. to overwrite the `doc.ents`.
|
||||
|
||||
> #### Example
|
||||
>
|
||||
> ```python
|
||||
> from spacy.gold import spans_from_biluo_tags
|
||||
>
|
||||
> doc = nlp("I like London.")
|
||||
> tags = ["O", "O", "U-LOC", "O"]
|
||||
> doc.ents = spans_from_biluo_tags(doc, tags)
|
||||
> ```
|
||||
|
||||
| Name | Type | Description |
|
||||
| ----------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `doc` | `Doc` | The document that the BILUO tags refer to. |
|
||||
| `entities` | iterable | A sequence of [BILUO](/api/annotation#biluo) tags with each tag describing one token. Each tag string will be of the form of either `""`, `"O"` or `"{action}-{label}"`, where action is one of `"B"`, `"I"`, `"L"`, `"U"`. |
|
||||
| **RETURNS** | list | A sequence of `Span` objects with added entity labels. |
|
||||
|
||||
## Utility functions {#util source="spacy/util.py"}
|
||||
|
||||
spaCy comes with a small collection of utility functions located in
|
||||
|
@ -269,32 +419,6 @@ page should be safe to use and we'll try to ensure backwards compatibility.
|
|||
However, we recommend having additional tests in place if your application
|
||||
depends on any of spaCy's utilities.
|
||||
|
||||
### util.get_data_path {#util.get_data_path tag="function"}
|
||||
|
||||
Get path to the data directory where spaCy looks for models. Defaults to
|
||||
`spacy/data`.
|
||||
|
||||
| Name | Type | Description |
|
||||
| ---------------- | --------------- | ------------------------------------------------------- |
|
||||
| `require_exists` | bool | Only return path if it exists, otherwise return `None`. |
|
||||
| **RETURNS** | `Path` / `None` | Data path or `None`. |
|
||||
|
||||
### util.set_data_path {#util.set_data_path tag="function"}
|
||||
|
||||
Set custom path to the data directory where spaCy looks for models.
|
||||
|
||||
> #### Example
|
||||
>
|
||||
> ```python
|
||||
> util.set_data_path("/custom/path")
|
||||
> util.get_data_path()
|
||||
> # PosixPath('/custom/path')
|
||||
> ```
|
||||
|
||||
| Name | Type | Description |
|
||||
| ------ | ------------ | --------------------------- |
|
||||
| `path` | str / `Path` | Path to new data directory. |
|
||||
|
||||
### util.get_lang_class {#util.get_lang_class tag="function"}
|
||||
|
||||
Import and load a `Language` class. Allows lazy-loading
|
||||
|
@ -368,7 +492,7 @@ class. The model data will then be loaded in via
|
|||
> #### Example
|
||||
>
|
||||
> ```python
|
||||
> nlp = util.load_model("en")
|
||||
> nlp = util.load_model("en_core_web_sm")
|
||||
> nlp = util.load_model("en_core_web_sm", disable=["ner"])
|
||||
> nlp = util.load_model("/path/to/data")
|
||||
> ```
|
||||
|
@ -487,28 +611,6 @@ detecting the IPython kernel. Mainly used for the
|
|||
| ----------- | ---- | ------------------------------------- |
|
||||
| **RETURNS** | bool | `True` if in Jupyter, `False` if not. |
|
||||
|
||||
### util.update_exc {#util.update_exc tag="function"}
|
||||
|
||||
Update, validate and overwrite
|
||||
[tokenizer exceptions](/usage/adding-languages#tokenizer-exceptions). Used to
|
||||
combine global exceptions with custom, language-specific exceptions. Will raise
|
||||
an error if key doesn't match `ORTH` values.
|
||||
|
||||
> #### Example
|
||||
>
|
||||
> ```python
|
||||
> BASE = {"a.": [{ORTH: "a."}], ":)": [{ORTH: ":)"}]}
|
||||
> NEW = {"a.": [{ORTH: "a.", NORM: "all"}]}
|
||||
> exceptions = util.update_exc(BASE, NEW)
|
||||
> # {"a.": [{ORTH: "a.", NORM: "all"}], ":)": [{ORTH: ":)"}]}
|
||||
> ```
|
||||
|
||||
| Name | Type | Description |
|
||||
| ----------------- | ----- | --------------------------------------------------------------- |
|
||||
| `base_exceptions` | dict | Base tokenizer exceptions. |
|
||||
| `*addition_dicts` | dicts | Exception dictionaries to add to the base exceptions, in order. |
|
||||
| **RETURNS** | dict | Combined tokenizer exceptions. |
|
||||
|
||||
### util.compile_prefix_regex {#util.compile_prefix_regex tag="function"}
|
||||
|
||||
Compile a sequence of prefix rules into a regex object.
|
||||
|
@ -574,72 +676,11 @@ vary on each step.
|
|||
> nlp.update(texts, annotations)
|
||||
> ```
|
||||
|
||||
| Name | Type | Description |
|
||||
| ---------- | -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `items` | iterable | The items to batch up. |
|
||||
| `size` | int / iterable | The batch size(s). Use [`util.compounding`](/api/top-level#util.compounding) or [`util.decaying`](/api/top-level#util.decaying) or for an infinite series of compounding or decaying values. |
|
||||
| **YIELDS** | list | The batches. |
|
||||
|
||||
### util.compounding {#util.compounding tag="function" new="2"}
|
||||
|
||||
Yield an infinite series of compounding values. Each time the generator is
|
||||
called, a value is produced by multiplying the previous value by the compound
|
||||
rate.
|
||||
|
||||
> #### Example
|
||||
>
|
||||
> ```python
|
||||
> sizes = compounding(1., 10., 1.5)
|
||||
> assert next(sizes) == 1.
|
||||
> assert next(sizes) == 1. * 1.5
|
||||
> assert next(sizes) == 1.5 * 1.5
|
||||
> ```
|
||||
|
||||
| Name | Type | Description |
|
||||
| ---------- | ----------- | ----------------------- |
|
||||
| `start` | int / float | The first value. |
|
||||
| `stop` | int / float | The maximum value. |
|
||||
| `compound` | int / float | The compounding factor. |
|
||||
| **YIELDS** | int | Compounding values. |
|
||||
|
||||
### util.decaying {#util.decaying tag="function" new="2"}
|
||||
|
||||
Yield an infinite series of linearly decaying values.
|
||||
|
||||
> #### Example
|
||||
>
|
||||
> ```python
|
||||
> sizes = decaying(10., 1., 0.001)
|
||||
> assert next(sizes) == 10.
|
||||
> assert next(sizes) == 10. - 0.001
|
||||
> assert next(sizes) == 9.999 - 0.001
|
||||
> ```
|
||||
|
||||
| Name | Type | Description |
|
||||
| ---------- | ----------- | -------------------- |
|
||||
| `start` | int / float | The first value. |
|
||||
| `end` | int / float | The maximum value. |
|
||||
| `decay` | int / float | The decaying factor. |
|
||||
| **YIELDS** | int | The decaying values. |
|
||||
|
||||
### util.itershuffle {#util.itershuffle tag="function" new="2"}
|
||||
|
||||
Shuffle an iterator. This works by holding `bufsize` items back and yielding
|
||||
them sometime later. Obviously, this is not unbiased – but should be good enough
|
||||
for batching. Larger `bufsize` means less bias.
|
||||
|
||||
> #### Example
|
||||
>
|
||||
> ```python
|
||||
> values = range(1000)
|
||||
> shuffled = itershuffle(values)
|
||||
> ```
|
||||
|
||||
| Name | Type | Description |
|
||||
| ---------- | -------- | ----------------------------------- |
|
||||
| `iterable` | iterable | Iterator to shuffle. |
|
||||
| `bufsize` | int | Items to hold back (default: 1000). |
|
||||
| **YIELDS** | iterable | The shuffled iterator. |
|
||||
| Name | Type | Description |
|
||||
| ---------- | -------------- | ---------------------- |
|
||||
| `items` | iterable | The items to batch up. |
|
||||
| `size` | int / iterable | The batch size(s). |
|
||||
| **YIELDS** | list | The batches. |
|
||||
|
||||
### util.filter_spans {#util.filter_spans tag="function" new="2.1.4"}
|
||||
|
||||
|
@ -661,3 +702,13 @@ of one entity) or when merging spans with
|
|||
| ----------- | -------- | -------------------- |
|
||||
| `spans` | iterable | The spans to filter. |
|
||||
| **RETURNS** | list | The filtered spans. |
|
||||
|
||||
## util.get_words_and_spaces {#get_words_and_spaces tag="function" new="3"}
|
||||
|
||||
<!-- TODO: document -->
|
||||
|
||||
| Name | Type | Description |
|
||||
| ----------- | ----- | ----------- |
|
||||
| `words` | list | |
|
||||
| `text` | str | |
|
||||
| **RETURNS** | tuple | |
|
||||
|
|
|
@ -12,6 +12,8 @@ place** by the components of the pipeline. The `Language` object coordinates
|
|||
these components. It takes raw text and sends it through the pipeline, returning
|
||||
an **annotated document**. It also orchestrates training and serialization.
|
||||
|
||||
<!-- TODO: update architecture and tables below to match sidebar in API docs etc. -->
|
||||
|
||||
![Library architecture](../../images/architecture.svg)
|
||||
|
||||
### Container objects {#architecture-containers}
|
||||
|
|
|
@ -29,8 +29,7 @@ import QuickstartInstall from 'widgets/quickstart-install.js'
|
|||
|
||||
### pip {#pip}
|
||||
|
||||
Using pip, spaCy releases are available as source packages and binary wheels (as
|
||||
of v2.0.13).
|
||||
Using pip, spaCy releases are available as source packages and binary wheels.
|
||||
|
||||
```bash
|
||||
$ pip install -U spacy
|
||||
|
@ -50,8 +49,8 @@ $ pip install -U spacy
|
|||
|
||||
<Infobox variant="warning">
|
||||
|
||||
To install additional data tables for lemmatization in **spaCy v2.2+** you can
|
||||
run `pip install spacy[lookups]` or install
|
||||
To install additional data tables for lemmatization you can run
|
||||
`pip install spacy[lookups]` or install
|
||||
[`spacy-lookups-data`](https://github.com/explosion/spacy-lookups-data)
|
||||
separately. The lookups package is needed to create blank models with
|
||||
lemmatization data, and to lemmatize in languages that don't yet come with
|
||||
|
|
|
@ -1353,6 +1353,8 @@ print("After:", [(token.text, token._.is_musician) for token in doc])
|
|||
|
||||
## Sentence Segmentation {#sbd}
|
||||
|
||||
<!-- TODO: include senter -->
|
||||
|
||||
A [`Doc`](/api/doc) object's sentences are available via the `Doc.sents`
|
||||
property. Unlike other libraries, spaCy uses the dependency parse to determine
|
||||
sentence boundaries. This is usually more accurate than a rule-based approach,
|
||||
|
|
|
@ -392,9 +392,7 @@ loading models, the underlying functionality is entirely based on native Python
|
|||
packages. This allows your application to handle a model like any other package
|
||||
dependency.
|
||||
|
||||
For an example of an automated model training and build process, see
|
||||
[this overview](/usage/training#example-training-spacy) of how we're training
|
||||
and packaging our models for spaCy.
|
||||
<!-- TODO: reference relevant spaCy project -->
|
||||
|
||||
### Downloading and requiring model dependencies {#models-download}
|
||||
|
||||
|
|
|
@ -711,67 +711,4 @@ class and call [`from_disk`](/api/language#from_disk) instead.
|
|||
nlp = spacy.blank("en").from_disk("/path/to/data")
|
||||
```
|
||||
|
||||
<Infobox title="Important note: Loading data in v2.x" variant="warning">
|
||||
|
||||
In spaCy 1.x, the distinction between `spacy.load()` and the `Language` class
|
||||
constructor was quite unclear. You could call `spacy.load()` when no model was
|
||||
present, and it would silently return an empty object. Likewise, you could pass
|
||||
a path to `English`, even if the mode required a different language. spaCy v2.0
|
||||
solves this with a clear distinction between setting up the instance and loading
|
||||
the data.
|
||||
|
||||
```diff
|
||||
- nlp = spacy.load("en_core_web_sm", path="/path/to/data")
|
||||
+ nlp = spacy.blank("en_core_web_sm").from_disk("/path/to/data")
|
||||
```
|
||||
|
||||
</Infobox>
|
||||
|
||||
### How we're training and packaging models for spaCy {#example-training-spacy}
|
||||
|
||||
Publishing a new version of spaCy often means re-training all available models,
|
||||
which is [quite a lot](/usage/models#languages). To make this run smoothly,
|
||||
we're using an automated build process and a [`spacy train`](/api/cli#train)
|
||||
template that looks like this:
|
||||
|
||||
```bash
|
||||
$ python -m spacy train {lang} {models_dir}/{name} {train_data} {dev_data} -m meta/{name}.json -V {version} -g {gpu_id} -n {n_epoch} -ns {n_sents}
|
||||
```
|
||||
|
||||
> #### meta.json template
|
||||
>
|
||||
> ```json
|
||||
> {
|
||||
> "lang": "en",
|
||||
> "name": "core_web_sm",
|
||||
> "license": "CC BY-SA 3.0",
|
||||
> "author": "Explosion AI",
|
||||
> "url": "https://explosion.ai",
|
||||
> "email": "contact@explosion.ai",
|
||||
> "sources": ["OntoNotes 5", "Common Crawl"],
|
||||
> "description": "English multi-task CNN trained on OntoNotes, with GloVe vectors trained on common crawl. Assigns word vectors, context-specific token vectors, POS tags, dependency parse and named entities."
|
||||
> }
|
||||
> ```
|
||||
|
||||
In a directory `meta`, we keep `meta.json` templates for the individual models,
|
||||
containing all relevant information that doesn't change across versions, like
|
||||
the name, description, author info and training data sources. When we train the
|
||||
model, we pass in the file to the meta template as the `--meta` argument, and
|
||||
specify the current model version as the `--version` argument.
|
||||
|
||||
On each epoch, the model is saved out with a `meta.json` using our template and
|
||||
added properties, like the `pipeline`, `accuracy` scores and the `spacy_version`
|
||||
used to train the model. After training completion, the best model is selected
|
||||
automatically and packaged using the [`package`](/api/cli#package) command.
|
||||
Since a full meta file is already present on the trained model, no further setup
|
||||
is required to build a valid model package.
|
||||
|
||||
```bash
|
||||
python -m spacy package -f {best_model} dist/
|
||||
cd dist/{model_name}
|
||||
python setup.py sdist
|
||||
```
|
||||
|
||||
This process allows us to quickly trigger the model training and build process
|
||||
for all available models and languages, and generate the correct meta data
|
||||
automatically.
|
||||
<!-- TODO: point to spaCy projects? -->
|
||||
|
|
|
@ -2,174 +2,22 @@
|
|||
title: Training Models
|
||||
next: /usage/projects
|
||||
menu:
|
||||
- ['Basics', 'basics']
|
||||
- ['NER', 'ner']
|
||||
- ['Tagger & Parser', 'tagger-parser']
|
||||
- ['Text Classification', 'textcat']
|
||||
- ['Entity Linking', 'entity-linker']
|
||||
- ['Tips and Advice', 'tips']
|
||||
- ['Introduction', 'basics']
|
||||
- ['CLI & Config', 'cli-config']
|
||||
- ['Custom Models', 'custom-models']
|
||||
- ['Transfer Learning', 'transfer-learning']
|
||||
- ['Parallel Training', 'parallel-training']
|
||||
- ['Internal API', 'api']
|
||||
---
|
||||
|
||||
This guide describes how to train new statistical models for spaCy's
|
||||
part-of-speech tagger, named entity recognizer, dependency parser, text
|
||||
classifier and entity linker. Once the model is trained, you can then
|
||||
[save and load](/usage/saving-loading#models) it.
|
||||
<!-- TODO: intro describing the new v3 training philosophy -->
|
||||
|
||||
## Training basics {#basics}
|
||||
## Introduction to training models {#basics}
|
||||
|
||||
import Training101 from 'usage/101/\_training.md'
|
||||
|
||||
<Training101 />
|
||||
|
||||
### Training via the command-line interface {#spacy-train-cli}
|
||||
|
||||
For most purposes, the best way to train spaCy is via the command-line
|
||||
interface. The [`spacy train`](/api/cli#train) command takes care of many
|
||||
details for you, including making sure that the data is minibatched and shuffled
|
||||
correctly, progress is printed, and models are saved after each epoch. You can
|
||||
prepare your data for use in [`spacy train`](/api/cli#train) using the
|
||||
[`spacy convert`](/api/cli#convert) command, which accepts many common NLP data
|
||||
formats, including `.iob` for named entities, and the CoNLL format for
|
||||
dependencies:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/UniversalDependencies/UD_Spanish-AnCora
|
||||
mkdir ancora-json
|
||||
python -m spacy convert UD_Spanish-AnCora/es_ancora-ud-train.conllu ancora-json
|
||||
python -m spacy convert UD_Spanish-AnCora/es_ancora-ud-dev.conllu ancora-json
|
||||
mkdir models
|
||||
python -m spacy train es models ancora-json/es_ancora-ud-train.json ancora-json/es_ancora-ud-dev.json
|
||||
```
|
||||
|
||||
<Infobox title="Tip: Debug your data">
|
||||
|
||||
If you're running spaCy v2.2 or above, you can use the
|
||||
[`debug-data` command](/api/cli#debug-data) to analyze and validate your
|
||||
training and development data, get useful stats, and find problems like invalid
|
||||
entity annotations, cyclic dependencies, low data labels and more.
|
||||
|
||||
```bash
|
||||
$ python -m spacy debug-data en train.json dev.json --verbose
|
||||
```
|
||||
|
||||
</Infobox>
|
||||
|
||||
You can also use the [`gold.docs_to_json`](/api/goldparse#docs_to_json) helper
|
||||
to convert a list of `Doc` objects to spaCy's JSON training format.
|
||||
|
||||
#### Understanding the training output
|
||||
|
||||
When you train a model using the [`spacy train`](/api/cli#train) command, you'll
|
||||
see a table showing metrics after each pass over the data. Here's what those
|
||||
metrics means:
|
||||
|
||||
> #### Tokenization metrics
|
||||
>
|
||||
> Note that if the development data has raw text, some of the gold-standard
|
||||
> entities might not align to the predicted tokenization. These tokenization
|
||||
> errors are **excluded from the NER evaluation**. If your tokenization makes it
|
||||
> impossible for the model to predict 50% of your entities, your NER F-score
|
||||
> might still look good.
|
||||
|
||||
| Name | Description |
|
||||
| ---------- | ------------------------------------------------------------------------------------------------- |
|
||||
| `Dep Loss` | Training loss for dependency parser. Should decrease, but usually not to 0. |
|
||||
| `NER Loss` | Training loss for named entity recognizer. Should decrease, but usually not to 0. |
|
||||
| `UAS` | Unlabeled attachment score for parser. The percentage of unlabeled correct arcs. Should increase. |
|
||||
| `NER P.` | NER precision on development data. Should increase. |
|
||||
| `NER R.` | NER recall on development data. Should increase. |
|
||||
| `NER F.` | NER F-score on development data. Should increase. |
|
||||
| `Tag %` | Fine-grained part-of-speech tag accuracy on development data. Should increase. |
|
||||
| `Token %` | Tokenization accuracy on development data. |
|
||||
| `CPU WPS` | Prediction speed on CPU in words per second, if available. Should stay stable. |
|
||||
| `GPU WPS` | Prediction speed on GPU in words per second, if available. Should stay stable. |
|
||||
|
||||
### Improving accuracy with transfer learning {#transfer-learning new="2.1"}
|
||||
|
||||
In most projects, you'll usually have a small amount of labelled data, and
|
||||
access to a much bigger sample of raw text. The raw text contains a lot of
|
||||
information about the language in general. Learning this general information
|
||||
from the raw text can help your model use the smaller labelled data more
|
||||
efficiently.
|
||||
|
||||
The two main ways to use raw text in your spaCy models are **word vectors** and
|
||||
**language model pretraining**. Word vectors provide information about the
|
||||
definitions of words. The vectors are a look-up table, so each word only has one
|
||||
representation, regardless of its context. Language model pretraining lets you
|
||||
learn contextualized word representations. Instead of initializing spaCy's
|
||||
convolutional neural network layers with random weights, the `spacy pretrain`
|
||||
command trains a language model to predict each word's word vector based on the
|
||||
surrounding words. The information used to predict this task is a good starting
|
||||
point for other tasks such as named entity recognition, text classification or
|
||||
dependency parsing.
|
||||
|
||||
<Infobox title="📖 Vectors and pretraining">
|
||||
|
||||
For more details, see the documentation on
|
||||
[vectors and similarity](/usage/vectors-similarity) and the
|
||||
[`spacy pretrain`](/api/cli#pretrain) command.
|
||||
|
||||
</Infobox>
|
||||
|
||||
### How do I get training data? {#training-data}
|
||||
|
||||
Collecting training data may sound incredibly painful – and it can be, if you're
|
||||
planning a large-scale annotation project. However, if your main goal is to
|
||||
update an existing model's predictions – for example, spaCy's named entity
|
||||
recognition – the hard part is usually not creating the actual annotations. It's
|
||||
finding representative examples and **extracting potential candidates**. The
|
||||
good news is, if you've been noticing bad performance on your data, you likely
|
||||
already have some relevant text, and you can use spaCy to **bootstrap a first
|
||||
set of training examples**. For example, after processing a few sentences, you
|
||||
may end up with the following entities, some correct, some incorrect.
|
||||
|
||||
> #### How many examples do I need?
|
||||
>
|
||||
> As a rule of thumb, you should allocate at least 10% of your project resources
|
||||
> to creating training and evaluation data. If you're looking to improve an
|
||||
> existing model, you might be able to start off with only a handful of
|
||||
> examples. Keep in mind that you'll always want a lot more than that for
|
||||
> **evaluation** – especially previous errors the model has made. Otherwise, you
|
||||
> won't be able to sufficiently verify that the model has actually made the
|
||||
> **correct generalizations** required for your use case.
|
||||
|
||||
| Text | Entity | Start | End | Label | |
|
||||
| ---------------------------------- | ------- | ----- | ---- | -------- | --- |
|
||||
| Uber blew through 1 million a week | Uber | `0` | `4` | `ORG` | ✅ |
|
||||
| Android Pay expands to Canada | Android | `0` | `7` | `PERSON` | ❌ |
|
||||
| Android Pay expands to Canada | Canada | `23` | `30` | `GPE` | ✅ |
|
||||
| Spotify steps up Asia expansion | Spotify | `0` | `8` | `ORG` | ✅ |
|
||||
| Spotify steps up Asia expansion | Asia | `17` | `21` | `NORP` | ❌ |
|
||||
|
||||
Alternatively, the [rule-based matcher](/usage/rule-based-matching) can be a
|
||||
useful tool to extract tokens or combinations of tokens, as well as their start
|
||||
and end index in a document. In this case, we'll extract mentions of Google and
|
||||
assume they're an `ORG`.
|
||||
|
||||
| Text | Entity | Start | End | Label | |
|
||||
| ------------------------------------- | ------- | ----- | ---- | ----- | --- |
|
||||
| let me google this for you | google | `7` | `13` | `ORG` | ❌ |
|
||||
| Google Maps launches location sharing | Google | `0` | `6` | `ORG` | ❌ |
|
||||
| Google rebrands its business apps | Google | `0` | `6` | `ORG` | ✅ |
|
||||
| look what i found on google! 😂 | google | `21` | `27` | `ORG` | ✅ |
|
||||
|
||||
Based on the few examples above, you can already create six training sentences
|
||||
with eight entities in total. Of course, what you consider a "correct
|
||||
annotation" will always depend on **what you want the model to learn**. While
|
||||
there are some entity annotations that are more or less universally correct –
|
||||
like Canada being a geopolitical entity – your application may have its very own
|
||||
definition of the [NER annotation scheme](/api/annotation#named-entities).
|
||||
|
||||
```python
|
||||
train_data = [
|
||||
("Uber blew through $1 million a week", [(0, 4, 'ORG')]),
|
||||
("Android Pay expands to Canada", [(0, 11, 'PRODUCT'), (23, 30, 'GPE')]),
|
||||
("Spotify steps up Asia expansion", [(0, 8, "ORG"), (17, 21, "LOC")]),
|
||||
("Google Maps launches location sharing", [(0, 11, "PRODUCT")]),
|
||||
("Google rebrands its business apps", [(0, 6, "ORG")]),
|
||||
("look what i found on google! 😂", [(21, 27, "PRODUCT")])]
|
||||
```
|
||||
|
||||
<Infobox title="Tip: Try the Prodigy annotation tool">
|
||||
|
||||
[![Prodigy: Radically efficient machine teaching](../images/prodigy.jpg)](https://prodi.gy)
|
||||
|
@ -183,7 +31,154 @@ ready-to-use spaCy models.
|
|||
|
||||
</Infobox>
|
||||
|
||||
### Training with annotations {#annotations}
|
||||
## Training CLI & config {#cli-config}
|
||||
|
||||
The recommended way to train your spaCy models is via the
|
||||
[`spacy train`](/api/cli#train) command on the command line.
|
||||
|
||||
1. The **training data** in spaCy's binary format created using
|
||||
[`spacy convert`](/api/cli#convert).
|
||||
2. A `config.cfg` **configuration file** with all settings and hyperparameters.
|
||||
3. An optional **Python file** to register
|
||||
[custom models and architectures](#custom-models).
|
||||
|
||||
<!-- TODO: decide how we want to present the "getting started" workflow here, get a default config etc. -->
|
||||
|
||||
### Training data format {#data-format}
|
||||
|
||||
<!-- TODO: explain the new binary DocBin format -->
|
||||
|
||||
> #### Tip: Debug your data
|
||||
>
|
||||
> The [`debug-data` command](/api/cli#debug-data) lets you analyze and validate
|
||||
> your training and development data, get useful stats, and find problems like
|
||||
> invalid entity annotations, cyclic dependencies, low data labels and more.
|
||||
>
|
||||
> ```bash
|
||||
> $ python -m spacy debug-data en train.json dev.json --verbose
|
||||
> ```
|
||||
|
||||
<Accordion title="Understanding the training output">
|
||||
|
||||
When you train a model using the [`spacy train`](/api/cli#train) command, you'll
|
||||
see a table showing metrics after each pass over the data. Here's what those
|
||||
metrics means:
|
||||
|
||||
<!-- TODO: update table below with updated metrics if needed -->
|
||||
|
||||
| Name | Description |
|
||||
| ---------- | ------------------------------------------------------------------------------------------------- |
|
||||
| `Dep Loss` | Training loss for dependency parser. Should decrease, but usually not to 0. |
|
||||
| `NER Loss` | Training loss for named entity recognizer. Should decrease, but usually not to 0. |
|
||||
| `UAS` | Unlabeled attachment score for parser. The percentage of unlabeled correct arcs. Should increase. |
|
||||
| `NER P.` | NER precision on development data. Should increase. |
|
||||
| `NER R.` | NER recall on development data. Should increase. |
|
||||
| `NER F.` | NER F-score on development data. Should increase. |
|
||||
| `Tag %` | Fine-grained part-of-speech tag accuracy on development data. Should increase. |
|
||||
| `Token %` | Tokenization accuracy on development data. |
|
||||
| `CPU WPS` | Prediction speed on CPU in words per second, if available. Should stay stable. |
|
||||
| `GPU WPS` | Prediction speed on GPU in words per second, if available. Should stay stable. |
|
||||
|
||||
Note that if the development data has raw text, some of the gold-standard
|
||||
entities might not align to the predicted tokenization. These tokenization
|
||||
errors are **excluded from the NER evaluation**. If your tokenization makes it
|
||||
impossible for the model to predict 50% of your entities, your NER F-score might
|
||||
still look good.
|
||||
|
||||
</Accordion>
|
||||
|
||||
---
|
||||
|
||||
### Training config files {#cli}
|
||||
|
||||
<!-- TODO: we need to come up with a good way to present the sections and their expected values visually? -->
|
||||
|
||||
<!-- TODO: instead of hard-coding a full config here, we probably want to embed it from GitHub, e.g. from one of the project templates. This also makes it easier to keep it up to date, and the embed widgets take up less space-->
|
||||
|
||||
```ini
|
||||
[training]
|
||||
use_gpu = -1
|
||||
limit = 0
|
||||
dropout = 0.2
|
||||
patience = 1000
|
||||
eval_frequency = 20
|
||||
scores = ["ents_p", "ents_r", "ents_f"]
|
||||
score_weights = {"ents_f": 1}
|
||||
orth_variant_level = 0.0
|
||||
gold_preproc = false
|
||||
max_length = 0
|
||||
seed = 0
|
||||
accumulate_gradient = 1
|
||||
discard_oversize = false
|
||||
|
||||
[training.batch_size]
|
||||
@schedules = "compounding.v1"
|
||||
start = 100
|
||||
stop = 1000
|
||||
compound = 1.001
|
||||
|
||||
[training.optimizer]
|
||||
@optimizers = "Adam.v1"
|
||||
learn_rate = 0.001
|
||||
beta1 = 0.9
|
||||
beta2 = 0.999
|
||||
use_averages = false
|
||||
|
||||
[nlp]
|
||||
lang = "en"
|
||||
vectors = null
|
||||
|
||||
[nlp.pipeline.ner]
|
||||
factory = "ner"
|
||||
|
||||
[nlp.pipeline.ner.model]
|
||||
@architectures = "spacy.TransitionBasedParser.v1"
|
||||
nr_feature_tokens = 3
|
||||
hidden_width = 128
|
||||
maxout_pieces = 3
|
||||
use_upper = true
|
||||
|
||||
[nlp.pipeline.ner.model.tok2vec]
|
||||
@architectures = "spacy.HashEmbedCNN.v1"
|
||||
width = 128
|
||||
depth = 4
|
||||
embed_size = 7000
|
||||
maxout_pieces = 3
|
||||
window_size = 1
|
||||
subword_features = true
|
||||
pretrained_vectors = null
|
||||
dropout = null
|
||||
```
|
||||
|
||||
### Model architectures {#model-architectures}
|
||||
|
||||
<!-- TODO: refer to architectures API: /api/architectures. This should document the architectures in spacy/ml/models -->
|
||||
|
||||
## Custom model implementations and architectures {#custom-models}
|
||||
|
||||
<!-- TODO: document some basic examples for custom models, refer to Thinc, refer to example config/project -->
|
||||
|
||||
### Training with custom code
|
||||
|
||||
<!-- TODO: document usage of spacy train with --code -->
|
||||
|
||||
## Transfer learning {#transfer-learning}
|
||||
|
||||
### Using transformer models like BERT {#transformers}
|
||||
|
||||
<!-- TODO: document usage of spacy-transformers, refer to example config/project -->
|
||||
|
||||
### Pretraining with spaCy {#pretraining}
|
||||
|
||||
<!-- TODO: document spacy pretrain -->
|
||||
|
||||
## Parallel Training with Ray {#parallel-training}
|
||||
|
||||
<!-- TODO: document Ray integration -->
|
||||
|
||||
## Internal training API {#api}
|
||||
|
||||
<!-- TODO: rewrite for new nlp.update / example logic -->
|
||||
|
||||
The [`GoldParse`](/api/goldparse) object collects the annotated training
|
||||
examples, also called the **gold standard**. It's initialized with the
|
||||
|
@ -234,12 +229,12 @@ it harder for the model to memorize the training data. For example, a `0.25`
|
|||
dropout means that each feature or internal representation has a 1/4 likelihood
|
||||
of being dropped.
|
||||
|
||||
> - [`begin_training()`](/api/language#begin_training): Start the training and
|
||||
> - [`begin_training`](/api/language#begin_training): Start the training and
|
||||
> return an optimizer function to update the model's weights. Can take an
|
||||
> optional function converting the training data to spaCy's training format.
|
||||
> - [`update()`](/api/language#update): Update the model with the training
|
||||
> example and gold data.
|
||||
> - [`to_disk()`](/api/language#to_disk): Save the updated model to a directory.
|
||||
> - [`update`](/api/language#update): Update the model with the training example
|
||||
> and gold data.
|
||||
> - [`to_disk`](/api/language#to_disk): Save the updated model to a directory.
|
||||
|
||||
```python
|
||||
### Example training loop
|
||||
|
@ -265,525 +260,4 @@ The [`nlp.update`](/api/language#update) method takes the following arguments:
|
|||
Instead of writing your own training loop, you can also use the built-in
|
||||
[`train`](/api/cli#train) command, which expects data in spaCy's
|
||||
[JSON format](/api/annotation#json-input). On each epoch, a model will be saved
|
||||
out to the directory. After training, you can use the
|
||||
[`package`](/api/cli#package) command to generate an installable Python package
|
||||
from your model.
|
||||
|
||||
```bash
|
||||
python -m spacy convert /tmp/train.conllu /tmp/data
|
||||
python -m spacy train en /tmp/model /tmp/data/train.json -n 5
|
||||
```
|
||||
|
||||
### Simple training style {#training-simple-style new="2"}
|
||||
|
||||
Instead of sequences of `Doc` and `GoldParse` objects, you can also use the
|
||||
"simple training style" and pass **raw texts** and **dictionaries of
|
||||
annotations** to [`nlp.update`](/api/language#update). The dictionaries can have
|
||||
the keys `entities`, `heads`, `deps`, `tags` and `cats`. This is generally
|
||||
recommended, as it removes one layer of abstraction, and avoids unnecessary
|
||||
imports. It also makes it easier to structure and load your training data.
|
||||
|
||||
> #### Example Annotations
|
||||
>
|
||||
> ```python
|
||||
> {
|
||||
> "entities": [(0, 4, "ORG")],
|
||||
> "heads": [1, 1, 1, 5, 5, 2, 7, 5],
|
||||
> "deps": ["nsubj", "ROOT", "prt", "quantmod", "compound", "pobj", "det", "npadvmod"],
|
||||
> "tags": ["PROPN", "VERB", "ADP", "SYM", "NUM", "NUM", "DET", "NOUN"],
|
||||
> "cats": {"BUSINESS": 1.0},
|
||||
> }
|
||||
> ```
|
||||
|
||||
```python
|
||||
### Simple training loop
|
||||
TRAIN_DATA = [
|
||||
("Uber blew through $1 million a week", {"entities": [(0, 4, "ORG")]}),
|
||||
("Google rebrands its business apps", {"entities": [(0, 6, "ORG")]})]
|
||||
|
||||
nlp = spacy.blank("en")
|
||||
optimizer = nlp.begin_training()
|
||||
for i in range(20):
|
||||
random.shuffle(TRAIN_DATA)
|
||||
for text, annotations in TRAIN_DATA:
|
||||
nlp.update([text], [annotations], sgd=optimizer)
|
||||
nlp.to_disk("/model")
|
||||
```
|
||||
|
||||
The above training loop leaves out a few details that can really improve
|
||||
accuracy – but the principle really is _that_ simple. Once you've got your
|
||||
pipeline together and you want to tune the accuracy, you usually want to process
|
||||
your training examples in batches, and experiment with
|
||||
[`minibatch`](/api/top-level#util.minibatch) sizes and dropout rates, set via
|
||||
the `drop` keyword argument. See the [`Language`](/api/language) and
|
||||
[`Pipe`](/api/pipe) API docs for available options.
|
||||
|
||||
## Training the named entity recognizer {#ner}
|
||||
|
||||
All [spaCy models](/models) support online learning, so you can update a
|
||||
pretrained model with new examples. You'll usually need to provide many
|
||||
**examples** to meaningfully improve the system — a few hundred is a good start,
|
||||
although more is better.
|
||||
|
||||
You should avoid iterating over the same few examples multiple times, or the
|
||||
model is likely to "forget" how to annotate other examples. If you iterate over
|
||||
the same few examples, you're effectively changing the loss function. The
|
||||
optimizer will find a way to minimize the loss on your examples, without regard
|
||||
for the consequences on the examples it's no longer paying attention to. One way
|
||||
to avoid this
|
||||
["catastrophic forgetting" problem](https://explosion.ai/blog/pseudo-rehearsal-catastrophic-forgetting)
|
||||
is to "remind" the model of other examples by augmenting your annotations with
|
||||
sentences annotated with entities automatically recognized by the original
|
||||
model. Ultimately, this is an empirical process: you'll need to **experiment on
|
||||
your data** to find a solution that works best for you.
|
||||
|
||||
> #### Tip: Converting entity annotations
|
||||
>
|
||||
> You can train the entity recognizer with entity offsets or annotations in the
|
||||
> [BILUO scheme](/api/annotation#biluo). The `spacy.gold` module also exposes
|
||||
> [two helper functions](/api/goldparse#util) to convert offsets to BILUO tags,
|
||||
> and BILUO tags to entity offsets.
|
||||
|
||||
### Updating the Named Entity Recognizer {#example-train-ner}
|
||||
|
||||
This example shows how to update spaCy's entity recognizer with your own
|
||||
examples, starting off with an existing, pretrained model, or from scratch using
|
||||
a blank `Language` class. To do this, you'll need **example texts** and the
|
||||
**character offsets** and **labels** of each entity contained in the texts.
|
||||
|
||||
```python
|
||||
https://github.com/explosion/spaCy/tree/master/examples/training/train_ner.py
|
||||
```
|
||||
|
||||
#### Step by step guide {#step-by-step-ner}
|
||||
|
||||
1. **Load the model** you want to start with, or create an **empty model** using
|
||||
[`spacy.blank`](/api/top-level#spacy.blank) with the ID of your language. If
|
||||
you're using a blank model, don't forget to add the entity recognizer to the
|
||||
pipeline. If you're using an existing model, make sure to disable all other
|
||||
pipeline components during training using
|
||||
[`nlp.select_pipes`](/api/language#select_pipes). This way, you'll only be
|
||||
training the entity recognizer.
|
||||
2. **Shuffle and loop over** the examples. For each example, **update the
|
||||
model** by calling [`nlp.update`](/api/language#update), which steps through
|
||||
the words of the input. At each word, it makes a **prediction**. It then
|
||||
consults the annotations to see whether it was right. If it was wrong, it
|
||||
adjusts its weights so that the correct action will score higher next time.
|
||||
3. **Save** the trained model using [`nlp.to_disk`](/api/language#to_disk).
|
||||
4. **Test** the model to make sure the entities in the training data are
|
||||
recognized correctly.
|
||||
|
||||
### Training an additional entity type {#example-new-entity-type}
|
||||
|
||||
This script shows how to add a new entity type `ANIMAL` to an existing
|
||||
pretrained NER model, or an empty `Language` class. To keep the example short
|
||||
and simple, only a few sentences are provided as examples. In practice, you'll
|
||||
need many more — a few hundred would be a good start. You will also likely need
|
||||
to mix in examples of other entity types, which might be obtained by running the
|
||||
entity recognizer over unlabelled sentences, and adding their annotations to the
|
||||
training set.
|
||||
|
||||
```python
|
||||
https://github.com/explosion/spaCy/tree/master/examples/training/train_new_entity_type.py
|
||||
```
|
||||
|
||||
<Infobox title="Important note" variant="warning">
|
||||
|
||||
If you're using an existing model, make sure to mix in examples of **other
|
||||
entity types** that spaCy correctly recognized before. Otherwise, your model
|
||||
might learn the new type, but "forget" what it previously knew. This is also
|
||||
referred to as the "catastrophic forgetting" problem.
|
||||
|
||||
</Infobox>
|
||||
|
||||
#### Step by step guide {#step-by-step-ner-new}
|
||||
|
||||
1. **Load the model** you want to start with, or create an **empty model** using
|
||||
[`spacy.blank`](/api/top-level#spacy.blank) with the ID of your language. If
|
||||
you're using a blank model, don't forget to add the entity recognizer to the
|
||||
pipeline. If you're using an existing model, make sure to disable all other
|
||||
pipeline components during training using
|
||||
[`nlp.select_pipes`](/api/language#select_pipes). This way, you'll only be
|
||||
training the entity recognizer.
|
||||
2. **Add the new entity label** to the entity recognizer using the
|
||||
[`add_label`](/api/entityrecognizer#add_label) method. You can access the
|
||||
entity recognizer in the pipeline via `nlp.get_pipe('ner')`.
|
||||
3. **Loop over** the examples and call [`nlp.update`](/api/language#update),
|
||||
which steps through the words of the input. At each word, it makes a
|
||||
**prediction**. It then consults the annotations, to see whether it was
|
||||
right. If it was wrong, it adjusts its weights so that the correct action
|
||||
will score higher next time.
|
||||
4. **Save** the trained model using [`nlp.to_disk`](/api/language#to_disk).
|
||||
5. **Test** the model to make sure the new entity is recognized correctly.
|
||||
|
||||
## Training the tagger and parser {#tagger-parser}
|
||||
|
||||
### Updating the Dependency Parser {#example-train-parser}
|
||||
|
||||
This example shows how to train spaCy's dependency parser, starting off with an
|
||||
existing model or a blank model. You'll need a set of **training examples** and
|
||||
the respective **heads** and **dependency label** for each token of the example
|
||||
texts.
|
||||
|
||||
```python
|
||||
https://github.com/explosion/spaCy/tree/master/examples/training/train_parser.py
|
||||
```
|
||||
|
||||
#### Step by step guide {#step-by-step-parser}
|
||||
|
||||
1. **Load the model** you want to start with, or create an **empty model** using
|
||||
[`spacy.blank`](/api/top-level#spacy.blank) with the ID of your language. If
|
||||
you're using a blank model, don't forget to add the parser to the pipeline.
|
||||
If you're using an existing model, make sure to disable all other pipeline
|
||||
components during training using
|
||||
[`nlp.select_pipes`](/api/language#select_pipes). This way, you'll only be
|
||||
training the parser.
|
||||
2. **Add the dependency labels** to the parser using the
|
||||
[`add_label`](/api/dependencyparser#add_label) method. If you're starting off
|
||||
with a pretrained spaCy model, this is usually not necessary – but it doesn't
|
||||
hurt either, just to be safe.
|
||||
3. **Shuffle and loop over** the examples. For each example, **update the
|
||||
model** by calling [`nlp.update`](/api/language#update), which steps through
|
||||
the words of the input. At each word, it makes a **prediction**. It then
|
||||
consults the annotations to see whether it was right. If it was wrong, it
|
||||
adjusts its weights so that the correct action will score higher next time.
|
||||
4. **Save** the trained model using [`nlp.to_disk`](/api/language#to_disk).
|
||||
5. **Test** the model to make sure the parser works as expected.
|
||||
|
||||
### Updating the Part-of-speech Tagger {#example-train-tagger}
|
||||
|
||||
In this example, we're training spaCy's part-of-speech tagger with a custom tag
|
||||
map. We start off with a blank `Language` class, update its defaults with our
|
||||
custom tags and then train the tagger. You'll need a set of **training
|
||||
examples** and the respective **custom tags**, as well as a dictionary mapping
|
||||
those tags to the
|
||||
[Universal Dependencies scheme](http://universaldependencies.github.io/docs/u/pos/index.html).
|
||||
|
||||
```python
|
||||
https://github.com/explosion/spaCy/tree/master/examples/training/train_tagger.py
|
||||
```
|
||||
|
||||
#### Step by step guide {#step-by-step-tagger}
|
||||
|
||||
1. **Load the model** you want to start with, or create an **empty model** using
|
||||
[`spacy.blank`](/api/top-level#spacy.blank) with the ID of your language. If
|
||||
you're using a blank model, don't forget to add the tagger to the pipeline.
|
||||
If you're using an existing model, make sure to disable all other pipeline
|
||||
components during training using
|
||||
[`nlp.select_pipes`](/api/language#select_pipes). This way, you'll only be
|
||||
training the tagger.
|
||||
2. **Add the tag map** to the tagger using the
|
||||
[`add_label`](/api/tagger#add_label) method. The first argument is the new
|
||||
tag name, the second the mapping to spaCy's coarse-grained tags, e.g.
|
||||
`{'pos': 'NOUN'}`.
|
||||
3. **Shuffle and loop over** the examples. For each example, **update the
|
||||
model** by calling [`nlp.update`](/api/language#update), which steps through
|
||||
the words of the input. At each word, it makes a **prediction**. It then
|
||||
consults the annotations to see whether it was right. If it was wrong, it
|
||||
adjusts its weights so that the correct action will score higher next time.
|
||||
4. **Save** the trained model using [`nlp.to_disk`](/api/language#to_disk).
|
||||
5. **Test** the model to make sure the parser works as expected.
|
||||
|
||||
### Training a parser for custom semantics {#intent-parser}
|
||||
|
||||
spaCy's parser component can be used to be trained to predict any type of tree
|
||||
structure over your input text – including **semantic relations** that are not
|
||||
syntactic dependencies. This can be useful to for **conversational
|
||||
applications**, which need to predict trees over whole documents or chat logs,
|
||||
with connections between the sentence roots used to annotate discourse
|
||||
structure. For example, you can train spaCy's parser to label intents and their
|
||||
targets, like attributes, quality, time and locations. The result could look
|
||||
like this:
|
||||
|
||||
![Custom dependencies](../images/displacy-custom-parser.svg)
|
||||
|
||||
```python
|
||||
doc = nlp("find a hotel with good wifi")
|
||||
print([(t.text, t.dep_, t.head.text) for t in doc if t.dep_ != '-'])
|
||||
# [('find', 'ROOT', 'find'), ('hotel', 'PLACE', 'find'),
|
||||
# ('good', 'QUALITY', 'wifi'), ('wifi', 'ATTRIBUTE', 'hotel')]
|
||||
```
|
||||
|
||||
The above tree attaches "wifi" to "hotel" and assigns the dependency label
|
||||
`ATTRIBUTE`. This may not be a correct syntactic dependency – but in this case,
|
||||
it expresses exactly what we need: the user is looking for a hotel with the
|
||||
attribute "wifi" of the quality "good". This query can then be processed by your
|
||||
application and used to trigger the respective action – e.g. search the database
|
||||
for hotels with high ratings for their wifi offerings.
|
||||
|
||||
> #### Tip: merge phrases and entities
|
||||
>
|
||||
> To achieve even better accuracy, try merging multi-word tokens and entities
|
||||
> specific to your domain into one token before parsing your text. You can do
|
||||
> this by running the entity recognizer or
|
||||
> [rule-based matcher](/usage/rule-based-matching) to find relevant spans, and
|
||||
> merging them using [`Doc.retokenize`](/api/doc#retokenize). You could even add
|
||||
> your own custom
|
||||
> [pipeline component](/usage/processing-pipelines#custom-components) to do this
|
||||
> automatically – just make sure to add it `before='parser'`.
|
||||
|
||||
The following example shows a full implementation of a training loop for a
|
||||
custom message parser for a common "chat intent": finding local businesses. Our
|
||||
message semantics will have the following types of relations: `ROOT`, `PLACE`,
|
||||
`QUALITY`, `ATTRIBUTE`, `TIME` and `LOCATION`.
|
||||
|
||||
```python
|
||||
https://github.com/explosion/spaCy/tree/master/examples/training/train_intent_parser.py
|
||||
```
|
||||
|
||||
#### Step by step guide {#step-by-step-parser-custom}
|
||||
|
||||
1. **Create the training data** consisting of words, their heads and their
|
||||
dependency labels in order. A token's head is the index of the token it is
|
||||
attached to. The heads don't need to be syntactically correct – they should
|
||||
express the **semantic relations** you want the parser to learn. For words
|
||||
that shouldn't receive a label, you can choose an arbitrary placeholder, for
|
||||
example `-`.
|
||||
2. **Load the model** you want to start with, or create an **empty model** using
|
||||
[`spacy.blank`](/api/top-level#spacy.blank) with the ID of your language. If
|
||||
you're using a blank model, don't forget to add the custom parser to the
|
||||
pipeline. If you're using an existing model, make sure to **remove the old
|
||||
parser** from the pipeline, and disable all other pipeline components during
|
||||
training using [`nlp.select_pipes`](/api/language#select_pipes). This way,
|
||||
you'll only be training the parser.
|
||||
3. **Add the dependency labels** to the parser using the
|
||||
[`add_label`](/api/dependencyparser#add_label) method.
|
||||
4. **Shuffle and loop over** the examples. For each example, **update the
|
||||
model** by calling [`nlp.update`](/api/language#update), which steps through
|
||||
the words of the input. At each word, it makes a **prediction**. It then
|
||||
consults the annotations to see whether it was right. If it was wrong, it
|
||||
adjusts its weights so that the correct action will score higher next time.
|
||||
5. **Save** the trained model using [`nlp.to_disk`](/api/language#to_disk).
|
||||
6. **Test** the model to make sure the parser works as expected.
|
||||
|
||||
## Training a text classification model {#textcat}
|
||||
|
||||
### Adding a text classifier to a spaCy model {#example-textcat new="2"}
|
||||
|
||||
This example shows how to train a convolutional neural network text classifier
|
||||
on IMDB movie reviews, using spaCy's new
|
||||
[`TextCategorizer`](/api/textcategorizer) component. The dataset will be loaded
|
||||
automatically via Thinc's built-in dataset loader. Predictions are available via
|
||||
[`Doc.cats`](/api/doc#attributes).
|
||||
|
||||
```python
|
||||
https://github.com/explosion/spaCy/tree/master/examples/training/train_textcat.py
|
||||
```
|
||||
|
||||
#### Step by step guide {#step-by-step-textcat}
|
||||
|
||||
1. **Load the model** you want to start with, or create an **empty model** using
|
||||
[`spacy.blank`](/api/top-level#spacy.blank) with the ID of your language. If
|
||||
you're using an existing model, make sure to disable all other pipeline
|
||||
components during training using
|
||||
[`nlp.select_pipes`](/api/language#select_pipes). This way, you'll only be
|
||||
training the text classifier.
|
||||
2. **Add the text classifier** to the pipeline, and add the labels you want to
|
||||
train – for example, `POSITIVE`.
|
||||
3. **Load and pre-process the dataset**, shuffle the data and split off a part
|
||||
of it to hold back for evaluation. This way, you'll be able to see results on
|
||||
each training iteration.
|
||||
4. **Loop over** the training examples and partition them into batches using
|
||||
spaCy's [`minibatch`](/api/top-level#util.minibatch) and
|
||||
[`compounding`](/api/top-level#util.compounding) helpers.
|
||||
5. **Update the model** by calling [`nlp.update`](/api/language#update), which
|
||||
steps through the examples and makes a **prediction**. It then consults the
|
||||
annotations to see whether it was right. If it was wrong, it adjusts its
|
||||
weights so that the correct prediction will score higher next time.
|
||||
6. Optionally, you can also **evaluate the text classifier** on each iteration,
|
||||
by checking how it performs on the development data held back from the
|
||||
dataset. This lets you print the **precision**, **recall** and **F-score**.
|
||||
7. **Save** the trained model using [`nlp.to_disk`](/api/language#to_disk).
|
||||
8. **Test** the model to make sure the text classifier works as expected.
|
||||
|
||||
## Entity linking {#entity-linker}
|
||||
|
||||
To train an entity linking model, you first need to define a knowledge base
|
||||
(KB).
|
||||
|
||||
### Creating a knowledge base {#kb}
|
||||
|
||||
A KB consists of a list of entities with unique identifiers. Each such entity
|
||||
has an entity vector that will be used to measure similarity with the context in
|
||||
which an entity is used. These vectors have a fixed length and are stored in the
|
||||
KB.
|
||||
|
||||
The following example shows how to build a knowledge base from scratch, given a
|
||||
list of entities and potential aliases. The script requires an `nlp` model with
|
||||
pretrained word vectors to obtain an encoding of an entity's description as its
|
||||
vector.
|
||||
|
||||
```python
|
||||
https://github.com/explosion/spaCy/tree/master/examples/training/create_kb.py
|
||||
```
|
||||
|
||||
#### Step by step guide {#step-by-step-kb}
|
||||
|
||||
1. **Load the model** you want to start with. It should contain pretrained word
|
||||
vectors.
|
||||
2. **Obtain the entity embeddings** by running the descriptions of the entities
|
||||
through the `nlp` model and taking the average of all words with
|
||||
`nlp(desc).vector`. At this point, a custom encoding step can also be used.
|
||||
3. **Construct the KB** by defining all entities with their embeddings, and all
|
||||
aliases with their prior probabilities.
|
||||
4. **Save** the KB using [`kb.dump`](/api/kb#dump).
|
||||
5. **Print** the contents of the KB to make sure the entities were added
|
||||
correctly.
|
||||
|
||||
### Training an entity linking model {#entity-linker-model}
|
||||
|
||||
This example shows how to create an entity linker pipe using a previously
|
||||
created knowledge base. The entity linker is then trained with a set of custom
|
||||
examples. To do so, you need to provide **example texts**, and the **character
|
||||
offsets** and **knowledge base identifiers** of each entity contained in the
|
||||
texts.
|
||||
|
||||
```python
|
||||
https://github.com/explosion/spaCy/tree/master/examples/training/train_entity_linker.py
|
||||
```
|
||||
|
||||
#### Step by step guide {#step-by-step-entity-linker}
|
||||
|
||||
1. **Load the KB** you want to start with, and specify the path to the `Vocab`
|
||||
object that was used to create this KB. Then, create an **empty model** using
|
||||
[`spacy.blank`](/api/top-level#spacy.blank) with the ID of your language. Add
|
||||
a component for recognizing sentences en one for identifying relevant
|
||||
entities. In practical applications, you will want a more advanced pipeline
|
||||
including also a component for
|
||||
[named entity recognition](/usage/training#ner). Then, create a new entity
|
||||
linker component, add the KB to it, and then add the entity linker to the
|
||||
pipeline. If you're using a model with additional components, make sure to
|
||||
disable all other pipeline components during training using
|
||||
[`nlp.select_pipes`](/api/language#select_pipes). This way, you'll only be
|
||||
training the entity linker.
|
||||
2. **Shuffle and loop over** the examples. For each example, **update the
|
||||
model** by calling [`nlp.update`](/api/language#update), which steps through
|
||||
the annotated examples of the input. For each combination of a mention in
|
||||
text and a potential KB identifier, the model makes a **prediction** whether
|
||||
or not this is the correct match. It then consults the annotations to see
|
||||
whether it was right. If it was wrong, it adjusts its weights so that the
|
||||
correct combination will score higher next time.
|
||||
3. **Save** the trained model using [`nlp.to_disk`](/api/language#to_disk).
|
||||
4. **Test** the model to make sure the entities in the training data are
|
||||
recognized correctly.
|
||||
|
||||
## Optimization tips and advice {#tips}
|
||||
|
||||
There are lots of conflicting "recipes" for training deep neural networks at the
|
||||
moment. The cutting-edge models take a very long time to train, so most
|
||||
researchers can't run enough experiments to figure out what's _really_ going on.
|
||||
For what it's worth, here's a recipe that seems to work well on a lot of NLP
|
||||
problems:
|
||||
|
||||
1. Initialize with batch size 1, and compound to a maximum determined by your
|
||||
data size and problem type.
|
||||
2. Use Adam solver with fixed learning rate.
|
||||
3. Use averaged parameters
|
||||
4. Use L2 regularization.
|
||||
5. Clip gradients by L2 norm to 1.
|
||||
6. On small data sizes, start at a high dropout rate, with linear decay.
|
||||
|
||||
This recipe has been cobbled together experimentally. Here's why the various
|
||||
elements of the recipe made enough sense to try initially, and what you might
|
||||
try changing, depending on your problem.
|
||||
|
||||
### Compounding batch size {#tips-batch-size}
|
||||
|
||||
The trick of increasing the batch size is starting to become quite popular (see
|
||||
[Smith et al., 2017](https://arxiv.org/abs/1711.00489)). Their recipe is quite
|
||||
different from how spaCy's models are being trained, but there are some
|
||||
similarities. In training the various spaCy models, we haven't found much
|
||||
advantage from decaying the learning rate – but starting with a low batch size
|
||||
has definitely helped. You should try it out on your data, and see how you go.
|
||||
Here's our current strategy:
|
||||
|
||||
```python
|
||||
### Batch heuristic
|
||||
def get_batches(train_data, model_type):
|
||||
max_batch_sizes = {"tagger": 32, "parser": 16, "ner": 16, "textcat": 64}
|
||||
max_batch_size = max_batch_sizes[model_type]
|
||||
if len(train_data) < 1000:
|
||||
max_batch_size /= 2
|
||||
if len(train_data) < 500:
|
||||
max_batch_size /= 2
|
||||
batch_size = compounding(1, max_batch_size, 1.001)
|
||||
batches = minibatch(train_data, size=batch_size)
|
||||
return batches
|
||||
```
|
||||
|
||||
This will set the batch size to start at `1`, and increase each batch until it
|
||||
reaches a maximum size. The tagger, parser and entity recognizer all take whole
|
||||
sentences as input, so they're learning a lot of labels in a single example. You
|
||||
therefore need smaller batches for them. The batch size for the text categorizer
|
||||
should be somewhat larger, especially if your documents are long.
|
||||
|
||||
### Learning rate, regularization and gradient clipping {#tips-hyperparams}
|
||||
|
||||
By default spaCy uses the Adam solver, with default settings
|
||||
(`learn_rate=0.001`, `beta1=0.9`, `beta2=0.999`). Some researchers have said
|
||||
they found these settings terrible on their problems – but they've always
|
||||
performed very well in training spaCy's models, in combination with the rest of
|
||||
our recipe. You can change these settings directly, by modifying the
|
||||
corresponding attributes on the `optimizer` object. You can also set environment
|
||||
variables, to adjust the defaults.
|
||||
|
||||
There are two other key hyper-parameters of the solver: `L2` **regularization**,
|
||||
and **gradient clipping** (`max_grad_norm`). Gradient clipping is a hack that's
|
||||
not discussed often, but everybody seems to be using. It's quite important in
|
||||
helping to ensure the network doesn't diverge, which is a fancy way of saying
|
||||
"fall over during training". The effect is sort of similar to setting the
|
||||
learning rate low. It can also compensate for a large batch size (this is a good
|
||||
example of how the choices of all these hyper-parameters intersect).
|
||||
|
||||
### Dropout rate {#tips-dropout}
|
||||
|
||||
For small datasets, it's useful to set a **high dropout rate at first**, and
|
||||
**decay** it down towards a more reasonable value. This helps avoid the network
|
||||
immediately overfitting, while still encouraging it to learn some of the more
|
||||
interesting things in your data. spaCy comes with a
|
||||
[`decaying`](/api/top-level#util.decaying) utility function to facilitate this.
|
||||
You might try setting:
|
||||
|
||||
```python
|
||||
from spacy.util import decaying
|
||||
dropout = decaying(0.6, 0.2, 1e-4)
|
||||
```
|
||||
|
||||
You can then draw values from the iterator with `next(dropout)`, which you would
|
||||
pass to the `drop` keyword argument of [`nlp.update`](/api/language#update).
|
||||
It's pretty much always a good idea to use at least **some dropout**. All of the
|
||||
models currently use Bernoulli dropout, for no particularly principled reason –
|
||||
we just haven't experimented with another scheme like Gaussian dropout yet.
|
||||
|
||||
### Parameter averaging {#tips-param-avg}
|
||||
|
||||
The last part of our optimization recipe is **parameter averaging**, an old
|
||||
trick introduced by
|
||||
[Freund and Schapire (1999)](https://cseweb.ucsd.edu/~yfreund/papers/LargeMarginsUsingPerceptron.pdf),
|
||||
popularized in the NLP community by
|
||||
[Collins (2002)](http://www.aclweb.org/anthology/P04-1015), and explained in
|
||||
more detail by [Leon Bottou](http://leon.bottou.org/projects/sgd). Just about
|
||||
the only other people who seem to be using this for neural network training are
|
||||
the SyntaxNet team (one of whom is Michael Collins) – but it really seems to
|
||||
work great on every problem.
|
||||
|
||||
The trick is to store the moving average of the weights during training. We
|
||||
don't optimize this average – we just track it. Then when we want to actually
|
||||
use the model, we use the averages, not the most recent value. In spaCy (and
|
||||
[Thinc](https://github.com/explosion/thinc)) this is done by using a context
|
||||
manager, [`use_params`](/api/language#use_params), to temporarily replace the
|
||||
weights:
|
||||
|
||||
```python
|
||||
with nlp.use_params(optimizer.averages):
|
||||
nlp.to_disk("/model")
|
||||
```
|
||||
|
||||
The context manager is handy because you naturally want to evaluate and save the
|
||||
model at various points during training (e.g. after each epoch). After
|
||||
evaluating and saving, the context manager will exit and the weights will be
|
||||
restored, so you resume training from the most recent value, rather than the
|
||||
average. By evaluating the model after each epoch, you can remove one
|
||||
hyper-parameter from consideration (the number of epochs). Having one less magic
|
||||
number to guess is extremely nice – so having the averaging under a context
|
||||
manager is very convenient.
|
||||
out to the directory.
|
||||
|
|
|
@ -19,7 +19,7 @@
|
|||
{ "text": "Rule-based Matching", "url": "/usage/rule-based-matching" },
|
||||
{ "text": "Processing Pipelines", "url": "/usage/processing-pipelines" },
|
||||
{ "text": "Vectors & Similarity", "url": "/usage/vectors-similarity" },
|
||||
{ "text": "Training Models", "url": "/usage/training" },
|
||||
{ "text": "Training Models", "url": "/usage/training", "tag": "new" },
|
||||
{ "text": "spaCy Projects", "url": "/usage/projects", "tag": "new" },
|
||||
{ "text": "Saving & Loading", "url": "/usage/saving-loading" },
|
||||
{ "text": "Visualizers", "url": "/usage/visualizers" }
|
||||
|
@ -54,7 +54,8 @@
|
|||
{
|
||||
"label": "Overview",
|
||||
"items": [
|
||||
{ "text": "Architecture", "url": "/api" },
|
||||
{ "text": "Library Architecture", "url": "/api" },
|
||||
{ "text": "Model Architectures", "url": "/api/architectures" },
|
||||
{ "text": "Annotation Specs", "url": "/api/annotation" },
|
||||
{ "text": "Command Line", "url": "/api/cli" },
|
||||
{ "text": "Functions", "url": "/api/top-level" }
|
||||
|
@ -67,7 +68,8 @@
|
|||
{ "text": "Token", "url": "/api/token" },
|
||||
{ "text": "Span", "url": "/api/span" },
|
||||
{ "text": "Lexeme", "url": "/api/lexeme" },
|
||||
{ "text": "Example", "url": "/api/example" }
|
||||
{ "text": "Example", "url": "/api/example" },
|
||||
{ "text": "DocBin", "url": "/api/docbin" }
|
||||
]
|
||||
},
|
||||
{
|
||||
|
@ -85,6 +87,7 @@
|
|||
{ "text": "PhraseMatcher", "url": "/api/phrasematcher" },
|
||||
{ "text": "EntityRuler", "url": "/api/entityruler" },
|
||||
{ "text": "Sentencizer", "url": "/api/sentencizer" },
|
||||
{ "text": "SentenceRecognizer", "url": "/api/sentencerecognizer" },
|
||||
{ "text": "Other Functions", "url": "/api/pipeline-functions" }
|
||||
]
|
||||
},
|
||||
|
@ -96,10 +99,8 @@
|
|||
{ "text": "Vectors", "url": "/api/vectors" },
|
||||
{ "text": "Lookups", "url": "/api/lookups" },
|
||||
{ "text": "KnowledgeBase", "url": "/api/kb" },
|
||||
{ "text": "GoldParse", "url": "/api/goldparse" },
|
||||
{ "text": "GoldCorpus", "url": "/api/goldcorpus" },
|
||||
{ "text": "Scorer", "url": "/api/scorer" },
|
||||
{ "text": "DocBin", "url": "/api/docbin" }
|
||||
{ "text": "Corpus", "url": "/api/corpus" }
|
||||
]
|
||||
},
|
||||
{
|
||||
|
|
|
@ -83,12 +83,13 @@ export class Code extends React.Component {
|
|||
executable,
|
||||
github,
|
||||
prompt,
|
||||
wrap,
|
||||
highlight,
|
||||
className,
|
||||
children,
|
||||
} = this.props
|
||||
const codeClassNames = classNames(classes.code, className, `language-${lang}`, {
|
||||
[classes.wrap]: !!highlight,
|
||||
[classes.wrap]: !!highlight || !!wrap,
|
||||
})
|
||||
const ghClassNames = classNames(codeClassNames, classes.maxHeight)
|
||||
const { Juniper } = this.state
|
||||
|
|
|
@ -321,20 +321,20 @@ body [id]:target
|
|||
&.comment, &.prolog, &.doctype, &.cdata, &.punctuation
|
||||
color: var(--syntax-comment)
|
||||
|
||||
&.property, &.tag, &.constant, &.symbol
|
||||
&.property, &.tag, &.symbol
|
||||
color: var(--syntax-tag)
|
||||
|
||||
&.boolean, &.number
|
||||
color: var(--syntax-number)
|
||||
|
||||
&.selector, &.attr-name, &.string, &.char, &.builtin
|
||||
&.attr-name, &.string, &.char, &.builtin, &.attr-value
|
||||
color: var(--syntax-selector)
|
||||
|
||||
@at-root .language-css .token.string,
|
||||
&.operator, &.entity, &.url, &.variable
|
||||
color: var(--syntax-operator)
|
||||
|
||||
&.atrule, &.attr-value, &.function
|
||||
&.atrule, &.function, &.selector
|
||||
color: var(--syntax-function)
|
||||
|
||||
&.regex, &.important
|
||||
|
@ -395,13 +395,13 @@ body [id]:target
|
|||
.cm-comment
|
||||
color: var(--syntax-comment)
|
||||
|
||||
.cm-keyword, .cm-builtin
|
||||
.cm-keyword
|
||||
color: var(--syntax-keyword)
|
||||
|
||||
.cm-operator
|
||||
color: var(--syntax-operator)
|
||||
|
||||
.cm-string
|
||||
.cm-string, .cm-builtin
|
||||
color: var(--syntax-selector)
|
||||
|
||||
.cm-number
|
||||
|
|
|
@ -83,7 +83,7 @@ const QuickstartInstall = ({ id, title }) => (
|
|||
export PYTHONPATH=`pwd`
|
||||
</QS>
|
||||
<QS package="source" os="windows">
|
||||
set PYTHONPATH=/path/to/spaCy
|
||||
set PYTHONPATH=C:\path\to\spaCy
|
||||
</QS>
|
||||
<QS package="source">pip install -r requirements.txt</QS>
|
||||
<QS data="lookups" package="pip">
|
||||
|
|
Loading…
Reference in New Issue
Block a user