mirror of
https://github.com/explosion/spaCy.git
synced 2024-12-26 01:46:28 +03:00
Documentation for Entity Linking (#4065)
* document token ent_kb_id * document span kb_id * update pipeline documentation * prior and context weights as bool's instead * entitylinker api documentation * drop for both models * finish entitylinker documentation * small fixes * documentation for KB * candidate documentation * links to api pages in code * small fix * frequency examples as counts for consistency * consistent documentation about tensors returned by predict * add entity linking to usage 101 * add entity linking infobox and KB section to 101 * entity-linking in linguistic features * small typo corrections * training example and docs for entity_linker * predefined nlp and kb * revert back to similarity encodings for simplicity (for now) * set prior probabilities to 0 when excluded * code clean up * bugfix: deleting kb ID from tokens when entities were removed * refactor train el example to use either model or vocab * pretrain_kb example for example kb generation * add to training docs for KB + EL example scripts * small fixes * error numbering * ensure the language of vocab and nlp stay consistent across serialization * equality with = * avoid conflict in errors file * add error 151 * final adjustements to the train scripts - consistency * update of goldparse documentation * small corrections * push commit * typo fix * add candidate API to kb documentation * update API sidebar with EntityLinker and KnowledgeBase * remove EL from 101 docs * remove entity linker from 101 pipelines / rephrase * custom el model instead of existing model * set version to 2.2 for EL functionality * update documentation for 2 CLI scripts
This commit is contained in:
parent
7fbb559045
commit
0b4b4f1819
0
examples/pipeline/dummy_entity_linking.py
Normal file
0
examples/pipeline/dummy_entity_linking.py
Normal file
0
examples/pipeline/wikidata_entity_linking.py
Normal file
0
examples/pipeline/wikidata_entity_linking.py
Normal file
|
@ -8,8 +8,8 @@ For more details, see the documentation:
|
||||||
* Knowledge base: https://spacy.io/api/kb
|
* Knowledge base: https://spacy.io/api/kb
|
||||||
* Entity Linking: https://spacy.io/usage/linguistic-features#entity-linking
|
* Entity Linking: https://spacy.io/usage/linguistic-features#entity-linking
|
||||||
|
|
||||||
Compatible with: spaCy vX.X
|
Compatible with: spaCy v2.2
|
||||||
Last tested with: vX.X
|
Last tested with: v2.2
|
||||||
"""
|
"""
|
||||||
from __future__ import unicode_literals, print_function
|
from __future__ import unicode_literals, print_function
|
||||||
|
|
||||||
|
@ -73,7 +73,6 @@ def main(vocab_path=None, model=None, output_dir=None, n_iter=50):
|
||||||
input_dim=INPUT_DIM,
|
input_dim=INPUT_DIM,
|
||||||
desc_width=DESC_WIDTH,
|
desc_width=DESC_WIDTH,
|
||||||
epochs=n_iter,
|
epochs=n_iter,
|
||||||
threshold=0.001,
|
|
||||||
)
|
)
|
||||||
encoder.train(description_list=descriptions, to_print=True)
|
encoder.train(description_list=descriptions, to_print=True)
|
||||||
|
|
||||||
|
|
|
@ -8,8 +8,8 @@ For more details, see the documentation:
|
||||||
* Training: https://spacy.io/usage/training
|
* Training: https://spacy.io/usage/training
|
||||||
* Entity Linking: https://spacy.io/usage/linguistic-features#entity-linking
|
* Entity Linking: https://spacy.io/usage/linguistic-features#entity-linking
|
||||||
|
|
||||||
Compatible with: spaCy vX.X
|
Compatible with: spaCy v2.2
|
||||||
Last tested with: vX.X
|
Last tested with: v2.2
|
||||||
"""
|
"""
|
||||||
from __future__ import unicode_literals, print_function
|
from __future__ import unicode_literals, print_function
|
||||||
|
|
||||||
|
|
|
@ -24,7 +24,7 @@ cdef class Candidate:
|
||||||
algorithm which will disambiguate the various candidates to the correct one.
|
algorithm which will disambiguate the various candidates to the correct one.
|
||||||
Each candidate (alias, entity) pair is assigned to a certain prior probability.
|
Each candidate (alias, entity) pair is assigned to a certain prior probability.
|
||||||
|
|
||||||
DOCS: https://spacy.io/api/candidate
|
DOCS: https://spacy.io/api/kb/#candidate_init
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, KnowledgeBase kb, entity_hash, entity_freq, entity_vector, alias_hash, prior_prob):
|
def __init__(self, KnowledgeBase kb, entity_hash, entity_freq, entity_vector, alias_hash, prior_prob):
|
||||||
|
|
|
@ -226,7 +226,7 @@ $ python -m spacy train [lang] [output_path] [train_path] [dev_path]
|
||||||
| `--entity-multitasks`, `-et` | option | Side objectives for NER CNN, e.g. `'dep'` or `'dep,tag'` |
|
| `--entity-multitasks`, `-et` | option | Side objectives for NER CNN, e.g. `'dep'` or `'dep,tag'` |
|
||||||
| `--noise-level`, `-nl` | option | Float indicating the amount of corruption for data augmentation. |
|
| `--noise-level`, `-nl` | option | Float indicating the amount of corruption for data augmentation. |
|
||||||
| `--gold-preproc`, `-G` | flag | Use gold preprocessing. |
|
| `--gold-preproc`, `-G` | flag | Use gold preprocessing. |
|
||||||
| `--learn-tokens`, `-T` | flag | Make parser learn gold-standard tokenization by merging ] subtokens. Typically used for languages like Chinese. |
|
| `--learn-tokens`, `-T` | flag | Make parser learn gold-standard tokenization by merging subtokens. Typically used for languages like Chinese. |
|
||||||
| `--verbose`, `-VV` <Tag variant="new">2.0.13</Tag> | flag | Show more detailed messages during training. |
|
| `--verbose`, `-VV` <Tag variant="new">2.0.13</Tag> | flag | Show more detailed messages during training. |
|
||||||
| `--help`, `-h` | flag | Show help message and available arguments. |
|
| `--help`, `-h` | flag | Show help message and available arguments. |
|
||||||
| **CREATES** | model, pickle | A spaCy model on each epoch. |
|
| **CREATES** | model, pickle | A spaCy model on each epoch. |
|
||||||
|
|
297
website/docs/api/entitylinker.md
Normal file
297
website/docs/api/entitylinker.md
Normal file
|
@ -0,0 +1,297 @@
|
||||||
|
---
|
||||||
|
title: EntityLinker
|
||||||
|
teaser: Functionality to disambiguate a named entity in text to a unique knowledge base identifier.
|
||||||
|
tag: class
|
||||||
|
source: spacy/pipeline/pipes.pyx
|
||||||
|
new: 2.2
|
||||||
|
---
|
||||||
|
|
||||||
|
This class is a subclass of `Pipe` and follows the same API. The pipeline
|
||||||
|
component is available in the [processing pipeline](/usage/processing-pipelines)
|
||||||
|
via the ID `"entity_linker"`.
|
||||||
|
|
||||||
|
## EntityLinker.Model {#model tag="classmethod"}
|
||||||
|
|
||||||
|
Initialize a model for the pipe. The model should implement the
|
||||||
|
`thinc.neural.Model` API, and should contain a field `tok2vec` that contains
|
||||||
|
the context encoder. Wrappers are under development for most major machine
|
||||||
|
learning libraries.
|
||||||
|
|
||||||
|
| Name | Type | Description |
|
||||||
|
| ----------- | ------ | ------------------------------------- |
|
||||||
|
| `**kwargs` | - | Parameters for initializing the model |
|
||||||
|
| **RETURNS** | object | The initialized model. |
|
||||||
|
|
||||||
|
## EntityLinker.\_\_init\_\_ {#init tag="method"}
|
||||||
|
|
||||||
|
Create a new pipeline instance. In your application, you would normally use a
|
||||||
|
shortcut for this and instantiate the component using its string name and
|
||||||
|
[`nlp.create_pipe`](/api/language#create_pipe).
|
||||||
|
|
||||||
|
> #### Example
|
||||||
|
>
|
||||||
|
> ```python
|
||||||
|
> # Construction via create_pipe
|
||||||
|
> entity_linker = nlp.create_pipe("entity_linker")
|
||||||
|
>
|
||||||
|
> # Construction from class
|
||||||
|
> from spacy.pipeline import EntityLinker
|
||||||
|
> entity_linker = EntityLinker(nlp.vocab)
|
||||||
|
> entity_linker.from_disk("/path/to/model")
|
||||||
|
> ```
|
||||||
|
|
||||||
|
| Name | Type | Description |
|
||||||
|
| --------------- | ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||||
|
| `vocab` | `Vocab` | The shared vocabulary. |
|
||||||
|
| `model` | `thinc.neural.Model` / `True` | The model powering the pipeline component. If no model is supplied, the model is created when you call `begin_training`, `from_disk` or `from_bytes`. |
|
||||||
|
| `hidden_width` | int | Width of the hidden layer of the entity linking model, defaults to 128. |
|
||||||
|
| `incl_prior` | bool | Whether or not to include prior probabilities in the model. Defaults to True. |
|
||||||
|
| `incl_context` | bool | Whether or not to include the local context in the model (if not: only prior probabilites are used). Defaults to True. |
|
||||||
|
| **RETURNS** | `EntityLinker` | The newly constructed object. |
|
||||||
|
|
||||||
|
## EntityLinker.\_\_call\_\_ {#call tag="method"}
|
||||||
|
|
||||||
|
Apply the pipe to one document. The document is modified in place, and returned.
|
||||||
|
This usually happens under the hood when the `nlp` object is called on a text
|
||||||
|
and all pipeline components are applied to the `Doc` in order. Both
|
||||||
|
[`__call__`](/api/entitylinker#call) and
|
||||||
|
[`pipe`](/api/entitylinker#pipe) delegate to the
|
||||||
|
[`predict`](/api/entitylinker#predict) and
|
||||||
|
[`set_annotations`](/api/entitylinker#set_annotations) methods.
|
||||||
|
|
||||||
|
> #### Example
|
||||||
|
>
|
||||||
|
> ```python
|
||||||
|
> entity_linker = EntityLinker(nlp.vocab)
|
||||||
|
> doc = nlp(u"This is a sentence.")
|
||||||
|
> # This usually happens under the hood
|
||||||
|
> processed = entity_linker(doc)
|
||||||
|
> ```
|
||||||
|
|
||||||
|
| Name | Type | Description |
|
||||||
|
| ----------- | ----- | ------------------------ |
|
||||||
|
| `doc` | `Doc` | The document to process. |
|
||||||
|
| **RETURNS** | `Doc` | The processed document. |
|
||||||
|
|
||||||
|
## EntityLinker.pipe {#pipe tag="method"}
|
||||||
|
|
||||||
|
Apply the pipe to a stream of documents. This usually happens under the hood
|
||||||
|
when the `nlp` object is called on a text and all pipeline components are
|
||||||
|
applied to the `Doc` in order. Both [`__call__`](/api/entitylinker#call) and
|
||||||
|
[`pipe`](/api/entitylinker#pipe) delegate to the
|
||||||
|
[`predict`](/api/entitylinker#predict) and
|
||||||
|
[`set_annotations`](/api/entitylinker#set_annotations) methods.
|
||||||
|
|
||||||
|
> #### Example
|
||||||
|
>
|
||||||
|
> ```python
|
||||||
|
> entity_linker = EntityLinker(nlp.vocab)
|
||||||
|
> for doc in entity_linker.pipe(docs, batch_size=50):
|
||||||
|
> pass
|
||||||
|
> ```
|
||||||
|
|
||||||
|
| Name | Type | Description |
|
||||||
|
| ------------ | -------- | ------------------------------------------------------ |
|
||||||
|
| `stream` | iterable | A stream of documents. |
|
||||||
|
| `batch_size` | int | The number of texts to buffer. Defaults to `128`. |
|
||||||
|
| **YIELDS** | `Doc` | Processed documents in the order of the original text. |
|
||||||
|
|
||||||
|
## EntityLinker.predict {#predict tag="method"}
|
||||||
|
|
||||||
|
Apply the pipeline's model to a batch of docs, without modifying them.
|
||||||
|
|
||||||
|
> #### Example
|
||||||
|
>
|
||||||
|
> ```python
|
||||||
|
> entity_linker = EntityLinker(nlp.vocab)
|
||||||
|
> kb_ids, tensors = entity_linker.predict([doc1, doc2])
|
||||||
|
> ```
|
||||||
|
|
||||||
|
| Name | Type | Description |
|
||||||
|
| ----------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||||
|
| `docs` | iterable | The documents to predict. |
|
||||||
|
| **RETURNS** | tuple | A `(kb_ids, tensors)` tuple where `kb_ids` are the model's predicted KB identifiers for the entities in the `docs`, and `tensors` are the token representations used to predict these identifiers. |
|
||||||
|
|
||||||
|
## EntityLinker.set_annotations {#set_annotations tag="method"}
|
||||||
|
|
||||||
|
Modify a batch of documents, using pre-computed entity IDs for a list of named entities.
|
||||||
|
|
||||||
|
> #### Example
|
||||||
|
>
|
||||||
|
> ```python
|
||||||
|
> entity_linker = EntityLinker(nlp.vocab)
|
||||||
|
> kb_ids, tensors = entity_linker.predict([doc1, doc2])
|
||||||
|
> entity_linker.set_annotations([doc1, doc2], kb_ids, tensors)
|
||||||
|
> ```
|
||||||
|
|
||||||
|
| Name | Type | Description |
|
||||||
|
| ---------- | -------- | --------------------------------------------------------------------------------------------------- |
|
||||||
|
| `docs` | iterable | The documents to modify. |
|
||||||
|
| `kb_ids` | iterable | The knowledge base identifiers for the entities in the docs, predicted by `EntityLinker.predict`. |
|
||||||
|
| `tensors` | iterable | The token representations used to predict the identifiers. |
|
||||||
|
|
||||||
|
## EntityLinker.update {#update tag="method"}
|
||||||
|
|
||||||
|
Learn from a batch of documents and gold-standard information, updating both the
|
||||||
|
pipe's entity linking model and context encoder. Delegates to [`predict`](/api/entitylinker#predict) and
|
||||||
|
[`get_loss`](/api/entitylinker#get_loss).
|
||||||
|
|
||||||
|
> #### Example
|
||||||
|
>
|
||||||
|
> ```python
|
||||||
|
> entity_linker = EntityLinker(nlp.vocab)
|
||||||
|
> losses = {}
|
||||||
|
> optimizer = nlp.begin_training()
|
||||||
|
> entity_linker.update([doc1, doc2], [gold1, gold2], losses=losses, sgd=optimizer)
|
||||||
|
> ```
|
||||||
|
|
||||||
|
| Name | Type | Description |
|
||||||
|
| -------- | -------- | ------------------------------------------------------------------------------------------------------------- |
|
||||||
|
| `docs` | iterable | A batch of documents to learn from. |
|
||||||
|
| `golds` | iterable | The gold-standard data. Must have the same length as `docs`. |
|
||||||
|
| `drop` | float | The dropout rate, used both for the EL model and the context encoder. |
|
||||||
|
| `sgd` | callable | The optimizer for the EL model. Should take two arguments `weights` and `gradient`, and an optional ID. |
|
||||||
|
| `losses` | dict | Optional record of the loss during training. The value keyed by the model's name is updated. |
|
||||||
|
|
||||||
|
## EntityLinker.get_loss {#get_loss tag="method"}
|
||||||
|
|
||||||
|
Find the loss and gradient of loss for the entities in a batch of documents and their
|
||||||
|
predicted scores.
|
||||||
|
|
||||||
|
> #### Example
|
||||||
|
>
|
||||||
|
> ```python
|
||||||
|
> entity_linker = EntityLinker(nlp.vocab)
|
||||||
|
> kb_ids, tensors = entity_linker.predict(docs)
|
||||||
|
> loss, d_loss = entity_linker.get_loss(docs, [gold1, gold2], kb_ids, tensors)
|
||||||
|
> ```
|
||||||
|
|
||||||
|
| Name | Type | Description |
|
||||||
|
| --------------- | -------- | ------------------------------------------------------------ |
|
||||||
|
| `docs` | iterable | The batch of documents. |
|
||||||
|
| `golds` | iterable | The gold-standard data. Must have the same length as `docs`. |
|
||||||
|
| `kb_ids` | iterable | KB identifiers representing the model's predictions. |
|
||||||
|
| `tensors` | iterable | The token representations used to predict the identifiers |
|
||||||
|
| **RETURNS** | tuple | The loss and the gradient, i.e. `(loss, gradient)`. |
|
||||||
|
|
||||||
|
## EntityLinker.set_kb {#set_kb tag="method"}
|
||||||
|
|
||||||
|
Define the knowledge base (KB) used for disambiguating named entities to KB identifiers.
|
||||||
|
|
||||||
|
> #### Example
|
||||||
|
>
|
||||||
|
> ```python
|
||||||
|
> entity_linker = EntityLinker(nlp.vocab)
|
||||||
|
> entity_linker.set_kb(kb)
|
||||||
|
> ```
|
||||||
|
|
||||||
|
| Name | Type | Description |
|
||||||
|
| --------------- | --------------- | ------------------------------------------------------------ |
|
||||||
|
| `kb` | `KnowledgeBase` | The [`KnowledgeBase`](/api/kb). |
|
||||||
|
|
||||||
|
## EntityLinker.begin_training {#begin_training tag="method"}
|
||||||
|
|
||||||
|
Initialize the pipe for training, using data examples if available. If no model
|
||||||
|
has been initialized yet, the model is added.
|
||||||
|
Before calling this method, a knowledge base should have been defined with [`set_kb`](/api/entitylinker#set_kb).
|
||||||
|
|
||||||
|
> #### Example
|
||||||
|
>
|
||||||
|
> ```python
|
||||||
|
> entity_linker = EntityLinker(nlp.vocab)
|
||||||
|
> entity_linker.set_kb(kb)
|
||||||
|
> nlp.add_pipe(entity_linker, last=True)
|
||||||
|
> optimizer = entity_linker.begin_training(pipeline=nlp.pipeline)
|
||||||
|
> ```
|
||||||
|
|
||||||
|
| Name | Type | Description |
|
||||||
|
| ------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||||
|
| `gold_tuples` | iterable | Optional gold-standard annotations from which to construct [`GoldParse`](/api/goldparse) objects. |
|
||||||
|
| `pipeline` | list | Optional list of pipeline components that this component is part of. |
|
||||||
|
| `sgd` | callable | An optional optimizer. Should take two arguments `weights` and `gradient`, and an optional ID. Will be created via [`EntityLinker`](/api/entitylinker#create_optimizer) if not set. |
|
||||||
|
| **RETURNS** | callable | An optimizer. |
|
||||||
|
|
||||||
|
## EntityLinker.create_optimizer {#create_optimizer tag="method"}
|
||||||
|
|
||||||
|
Create an optimizer for the pipeline component.
|
||||||
|
|
||||||
|
> #### Example
|
||||||
|
>
|
||||||
|
> ```python
|
||||||
|
> entity_linker = EntityLinker(nlp.vocab)
|
||||||
|
> optimizer = entity_linker.create_optimizer()
|
||||||
|
> ```
|
||||||
|
|
||||||
|
| Name | Type | Description |
|
||||||
|
| ----------- | -------- | -------------- |
|
||||||
|
| **RETURNS** | callable | The optimizer. |
|
||||||
|
|
||||||
|
## EntityLinker.use_params {#use_params tag="method, contextmanager"}
|
||||||
|
|
||||||
|
Modify the pipe's EL model, to use the given parameter values.
|
||||||
|
|
||||||
|
> #### Example
|
||||||
|
>
|
||||||
|
> ```python
|
||||||
|
> entity_linker = EntityLinker(nlp.vocab)
|
||||||
|
> with entity_linker.use_params(optimizer.averages):
|
||||||
|
> entity_linker.to_disk("/best_model")
|
||||||
|
> ```
|
||||||
|
|
||||||
|
| Name | Type | Description |
|
||||||
|
| -------- | ---- | ---------------------------------------------------------------------------------------------------------- |
|
||||||
|
| `params` | dict | The parameter values to use in the model. At the end of the context, the original parameters are restored. |
|
||||||
|
|
||||||
|
|
||||||
|
## EntityLinker.to_disk {#to_disk tag="method"}
|
||||||
|
|
||||||
|
Serialize the pipe to disk.
|
||||||
|
|
||||||
|
> #### Example
|
||||||
|
>
|
||||||
|
> ```python
|
||||||
|
> entity_linker = EntityLinker(nlp.vocab)
|
||||||
|
> entity_linker.to_disk("/path/to/entity_linker")
|
||||||
|
> ```
|
||||||
|
|
||||||
|
| Name | Type | Description |
|
||||||
|
| --------- | ---------------- | --------------------------------------------------------------------------------------------------------------------- |
|
||||||
|
| `path` | unicode / `Path` | A path to a directory, which will be created if it doesn't exist. Paths may be either strings or `Path`-like objects. |
|
||||||
|
| `exclude` | list | String names of [serialization fields](#serialization-fields) to exclude. |
|
||||||
|
|
||||||
|
## EntityLinker.from_disk {#from_disk tag="method"}
|
||||||
|
|
||||||
|
Load the pipe from disk. Modifies the object in place and returns it.
|
||||||
|
|
||||||
|
> #### Example
|
||||||
|
>
|
||||||
|
> ```python
|
||||||
|
> entity_linker = EntityLinker(nlp.vocab)
|
||||||
|
> entity_linker.from_disk("/path/to/entity_linker")
|
||||||
|
> ```
|
||||||
|
|
||||||
|
| Name | Type | Description |
|
||||||
|
| ----------- | ------------------ | -------------------------------------------------------------------------- |
|
||||||
|
| `path` | unicode / `Path` | A path to a directory. Paths may be either strings or `Path`-like objects. |
|
||||||
|
| `exclude` | list | String names of [serialization fields](#serialization-fields) to exclude. |
|
||||||
|
| **RETURNS** | `EntityLinker` | The modified `EntityLinker` object. |
|
||||||
|
|
||||||
|
## Serialization fields {#serialization-fields}
|
||||||
|
|
||||||
|
During serialization, spaCy will export several data fields used to restore
|
||||||
|
different aspects of the object. If needed, you can exclude them from
|
||||||
|
serialization by passing in the string names via the `exclude` argument.
|
||||||
|
|
||||||
|
> #### Example
|
||||||
|
>
|
||||||
|
> ```python
|
||||||
|
> data = entity_linker.to_disk("/path", exclude=["vocab"])
|
||||||
|
> ```
|
||||||
|
|
||||||
|
| Name | Description |
|
||||||
|
| ------- | -------------------------------------------------------------- |
|
||||||
|
| `vocab` | The shared [`Vocab`](/api/vocab). |
|
||||||
|
| `cfg` | The config file. You usually don't want to exclude this. |
|
||||||
|
| `model` | The binary model data. You usually don't want to exclude this. |
|
||||||
|
| `kb` | The knowledge base. You usually don't want to exclude this. |
|
||||||
|
|
|
@ -99,7 +99,7 @@ Apply the pipeline's model to a batch of docs, without modifying them.
|
||||||
>
|
>
|
||||||
> ```python
|
> ```python
|
||||||
> ner = EntityRecognizer(nlp.vocab)
|
> ner = EntityRecognizer(nlp.vocab)
|
||||||
> scores = ner.predict([doc1, doc2])
|
> scores, tensors = ner.predict([doc1, doc2])
|
||||||
> ```
|
> ```
|
||||||
|
|
||||||
| Name | Type | Description |
|
| Name | Type | Description |
|
||||||
|
@ -115,14 +115,15 @@ Modify a batch of documents, using pre-computed scores.
|
||||||
>
|
>
|
||||||
> ```python
|
> ```python
|
||||||
> ner = EntityRecognizer(nlp.vocab)
|
> ner = EntityRecognizer(nlp.vocab)
|
||||||
> scores = ner.predict([doc1, doc2])
|
> scores, tensors = ner.predict([doc1, doc2])
|
||||||
> ner.set_annotations([doc1, doc2], scores)
|
> ner.set_annotations([doc1, doc2], scores, tensors)
|
||||||
> ```
|
> ```
|
||||||
|
|
||||||
| Name | Type | Description |
|
| Name | Type | Description |
|
||||||
| -------- | -------- | ---------------------------------------------------------- |
|
| -------- | -------- | ---------------------------------------------------------- |
|
||||||
| `docs` | iterable | The documents to modify. |
|
| `docs` | iterable | The documents to modify. |
|
||||||
| `scores` | - | The scores to set, produced by `EntityRecognizer.predict`. |
|
| `scores` | - | The scores to set, produced by `EntityRecognizer.predict`. |
|
||||||
|
| `tensors`| iterable | The token representations used to predict the scores. |
|
||||||
|
|
||||||
## EntityRecognizer.update {#update tag="method"}
|
## EntityRecognizer.update {#update tag="method"}
|
||||||
|
|
||||||
|
@ -210,13 +211,13 @@ Modify the pipe's model, to use the given parameter values.
|
||||||
>
|
>
|
||||||
> ```python
|
> ```python
|
||||||
> ner = EntityRecognizer(nlp.vocab)
|
> ner = EntityRecognizer(nlp.vocab)
|
||||||
> with ner.use_params():
|
> with ner.use_params(optimizer.averages):
|
||||||
> ner.to_disk("/best_model")
|
> ner.to_disk("/best_model")
|
||||||
> ```
|
> ```
|
||||||
|
|
||||||
| Name | Type | Description |
|
| Name | Type | Description |
|
||||||
| -------- | ---- | ---------------------------------------------------------------------------------------------------------- |
|
| -------- | ---- | ---------------------------------------------------------------------------------------------------------- |
|
||||||
| `params` | - | The parameter values to use in the model. At the end of the context, the original parameters are restored. |
|
| `params` | dict | The parameter values to use in the model. At the end of the context, the original parameters are restored. |
|
||||||
|
|
||||||
## EntityRecognizer.add_label {#add_label tag="method"}
|
## EntityRecognizer.add_label {#add_label tag="method"}
|
||||||
|
|
||||||
|
|
|
@ -23,6 +23,7 @@ gradient for those labels will be zero.
|
||||||
| `deps` | iterable | A sequence of strings, representing the syntactic relation types. |
|
| `deps` | iterable | A sequence of strings, representing the syntactic relation types. |
|
||||||
| `entities` | iterable | A sequence of named entity annotations, either as BILUO tag strings, or as `(start_char, end_char, label)` tuples, representing the entity positions. If BILUO tag strings, you can specify missing values by setting the tag to None. |
|
| `entities` | iterable | A sequence of named entity annotations, either as BILUO tag strings, or as `(start_char, end_char, label)` tuples, representing the entity positions. If BILUO tag strings, you can specify missing values by setting the tag to None. |
|
||||||
| `cats` | dict | Labels for text classification. Each key in the dictionary may be a string or an int, or a `(start_char, end_char, label)` tuple, indicating that the label is applied to only part of the document (usually a sentence). |
|
| `cats` | dict | Labels for text classification. Each key in the dictionary may be a string or an int, or a `(start_char, end_char, label)` tuple, indicating that the label is applied to only part of the document (usually a sentence). |
|
||||||
|
| `links` | dict | Labels for entity linking. A dict with `(start_char, end_char)` keys, and the values being dicts with `kb_id:value` entries, representing external KB IDs mapped to either 1.0 (positive) or 0.0 (negative). |
|
||||||
| **RETURNS** | `GoldParse` | The newly constructed object. |
|
| **RETURNS** | `GoldParse` | The newly constructed object. |
|
||||||
|
|
||||||
## GoldParse.\_\_len\_\_ {#len tag="method"}
|
## GoldParse.\_\_len\_\_ {#len tag="method"}
|
||||||
|
@ -44,7 +45,7 @@ Whether the provided syntactic annotations form a projective dependency tree.
|
||||||
## Attributes {#attributes}
|
## Attributes {#attributes}
|
||||||
|
|
||||||
| Name | Type | Description |
|
| Name | Type | Description |
|
||||||
| --------------------------------- | ---- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
| ------------------------------------ | ---- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||||
| `words` | list | The words. |
|
| `words` | list | The words. |
|
||||||
| `tags` | list | The part-of-speech tag annotations. |
|
| `tags` | list | The part-of-speech tag annotations. |
|
||||||
| `heads` | list | The syntactic head annotations. |
|
| `heads` | list | The syntactic head annotations. |
|
||||||
|
@ -53,6 +54,7 @@ Whether the provided syntactic annotations form a projective dependency tree.
|
||||||
| `cand_to_gold` | list | The alignment from candidate tokenization to gold tokenization. |
|
| `cand_to_gold` | list | The alignment from candidate tokenization to gold tokenization. |
|
||||||
| `gold_to_cand` | list | The alignment from gold tokenization to candidate tokenization. |
|
| `gold_to_cand` | list | The alignment from gold tokenization to candidate tokenization. |
|
||||||
| `cats` <Tag variant="new">2</Tag> | list | Entries in the list should be either a label, or a `(start, end, label)` triple. The tuple form is used for categories applied to spans of the document. |
|
| `cats` <Tag variant="new">2</Tag> | list | Entries in the list should be either a label, or a `(start, end, label)` triple. The tuple form is used for categories applied to spans of the document. |
|
||||||
|
| `links` <Tag variant="new">2.2</Tag> | dict | Keys in the dictionary are `(start_char, end_char)` triples, and the values are dictionaries with `kb_id:value` entries. |
|
||||||
|
|
||||||
## Utilities {#util}
|
## Utilities {#util}
|
||||||
|
|
||||||
|
|
268
website/docs/api/kb.md
Normal file
268
website/docs/api/kb.md
Normal file
|
@ -0,0 +1,268 @@
|
||||||
|
---
|
||||||
|
title: KnowledgeBase
|
||||||
|
teaser: A storage class for entities and aliases of a specific knowledge base (ontology)
|
||||||
|
tag: class
|
||||||
|
source: spacy/kb.pyx
|
||||||
|
new: 2.2
|
||||||
|
---
|
||||||
|
|
||||||
|
The `KnowledgeBase` object provides a method to generate [`Candidate`](/api/kb/#candidate_init)
|
||||||
|
objects, which are plausible external identifiers given a certain textual mention.
|
||||||
|
Each such `Candidate` holds information from the relevant KB entities,
|
||||||
|
such as its frequency in text and possible aliases.
|
||||||
|
Each entity in the knowledge base also has a pre-trained entity vector of a fixed size.
|
||||||
|
|
||||||
|
## KnowledgeBase.\_\_init\_\_ {#init tag="method"}
|
||||||
|
|
||||||
|
Create the knowledge base.
|
||||||
|
|
||||||
|
> #### Example
|
||||||
|
>
|
||||||
|
> ```python
|
||||||
|
> from spacy.kb import KnowledgeBase
|
||||||
|
> vocab = nlp.vocab
|
||||||
|
> kb = KnowledgeBase(vocab=vocab, entity_vector_length=64)
|
||||||
|
> ```
|
||||||
|
|
||||||
|
| Name | Type | Description |
|
||||||
|
| ----------------------- | ---------------- | ----------------------------------------- |
|
||||||
|
| `vocab` | `Vocab` | A `Vocab` object. |
|
||||||
|
| `entity_vector_length` | int | Length of the fixed-size entity vectors. |
|
||||||
|
| **RETURNS** | `KnowledgeBase` | The newly constructed object. |
|
||||||
|
|
||||||
|
|
||||||
|
## KnowledgeBase.entity_vector_length {#entity_vector_length tag="property"}
|
||||||
|
|
||||||
|
The length of the fixed-size entity vectors in the knowledge base.
|
||||||
|
|
||||||
|
| Name | Type | Description |
|
||||||
|
| ----------- | ---- | ----------------------------------------- |
|
||||||
|
| **RETURNS** | int | Length of the fixed-size entity vectors. |
|
||||||
|
|
||||||
|
## KnowledgeBase.add_entity {#add_entity tag="method"}
|
||||||
|
|
||||||
|
Add an entity to the knowledge base, specifying its corpus frequency
|
||||||
|
and entity vector, which should be of length [`entity_vector_length`](/api/kb#entity_vector_length).
|
||||||
|
|
||||||
|
> #### Example
|
||||||
|
>
|
||||||
|
> ```python
|
||||||
|
> kb.add_entity(entity="Q42", freq=32, entity_vector=vector1)
|
||||||
|
> kb.add_entity(entity="Q463035", freq=111, entity_vector=vector2)
|
||||||
|
> ```
|
||||||
|
|
||||||
|
| Name | Type | Description |
|
||||||
|
| --------------- | ------------- | ------------------------------------------------- |
|
||||||
|
| `entity` | unicode | The unique entity identifier |
|
||||||
|
| `freq` | float | The frequency of the entity in a typical corpus |
|
||||||
|
| `entity_vector` | vector | The pre-trained vector of the entity |
|
||||||
|
|
||||||
|
## KnowledgeBase.set_entities {#set_entities tag="method"}
|
||||||
|
|
||||||
|
Define the full list of entities in the knowledge base, specifying the corpus frequency
|
||||||
|
and entity vector for each entity.
|
||||||
|
|
||||||
|
> #### Example
|
||||||
|
>
|
||||||
|
> ```python
|
||||||
|
> kb.set_entities(entity_list=["Q42", "Q463035"], freq_list=[32, 111], vector_list=[vector1, vector2])
|
||||||
|
> ```
|
||||||
|
|
||||||
|
| Name | Type | Description |
|
||||||
|
| ------------- | ------------- | ------------------------------------------------- |
|
||||||
|
| `entity_list` | iterable | List of unique entity identifiers |
|
||||||
|
| `freq_list` | iterable | List of entity frequencies |
|
||||||
|
| `vector_list` | iterable | List of entity vectors |
|
||||||
|
|
||||||
|
## KnowledgeBase.add_alias {#add_alias tag="method"}
|
||||||
|
|
||||||
|
Add an alias or mention to the knowledge base, specifying its potential KB identifiers
|
||||||
|
and their prior probabilities. The entity identifiers should refer to entities previously
|
||||||
|
added with [`add_entity`](/api/kb#add_entity) or [`set_entities`](/api/kb#set_entities).
|
||||||
|
The sum of the prior probabilities should not exceed 1.
|
||||||
|
|
||||||
|
> #### Example
|
||||||
|
>
|
||||||
|
> ```python
|
||||||
|
> kb.add_alias(alias="Douglas", entities=["Q42", "Q463035"], probabilities=[0.6, 0.3])
|
||||||
|
> ```
|
||||||
|
|
||||||
|
| Name | Type | Description |
|
||||||
|
| -------------- | ------------- | -------------------------------------------------- |
|
||||||
|
| `alias` | unicode | The textual mention or alias |
|
||||||
|
| `entities` | iterable | The potential entities that the alias may refer to |
|
||||||
|
| `probabilities`| iterable | The prior probabilities of each entity |
|
||||||
|
|
||||||
|
## KnowledgeBase.\_\_len\_\_ {#len tag="method"}
|
||||||
|
|
||||||
|
Get the total number of entities in the knowledge base.
|
||||||
|
|
||||||
|
> #### Example
|
||||||
|
>
|
||||||
|
> ```python
|
||||||
|
> total_entities = len(kb)
|
||||||
|
> ```
|
||||||
|
|
||||||
|
| Name | Type | Description |
|
||||||
|
| ----------- | ---- | --------------------------------------------- |
|
||||||
|
| **RETURNS** | int | The number of entities in the knowledge base. |
|
||||||
|
|
||||||
|
## KnowledgeBase.get_entity_strings {#get_entity_strings tag="method"}
|
||||||
|
|
||||||
|
Get a list of all entity IDs in the knowledge base.
|
||||||
|
|
||||||
|
> #### Example
|
||||||
|
>
|
||||||
|
> ```python
|
||||||
|
> all_entities = kb.get_entity_strings()
|
||||||
|
> ```
|
||||||
|
|
||||||
|
| Name | Type | Description |
|
||||||
|
| ----------- | ---- | --------------------------------------------- |
|
||||||
|
| **RETURNS** | list | The list of entities in the knowledge base. |
|
||||||
|
|
||||||
|
## KnowledgeBase.get_size_aliases {#get_size_aliases tag="method"}
|
||||||
|
|
||||||
|
Get the total number of aliases in the knowledge base.
|
||||||
|
|
||||||
|
> #### Example
|
||||||
|
>
|
||||||
|
> ```python
|
||||||
|
> total_aliases = kb.get_size_aliases()
|
||||||
|
> ```
|
||||||
|
|
||||||
|
| Name | Type | Description |
|
||||||
|
| ----------- | ---- | --------------------------------------------- |
|
||||||
|
| **RETURNS** | int | The number of aliases in the knowledge base. |
|
||||||
|
|
||||||
|
## KnowledgeBase.get_alias_strings {#get_alias_strings tag="method"}
|
||||||
|
|
||||||
|
Get a list of all aliases in the knowledge base.
|
||||||
|
|
||||||
|
> #### Example
|
||||||
|
>
|
||||||
|
> ```python
|
||||||
|
> all_aliases = kb.get_alias_strings()
|
||||||
|
> ```
|
||||||
|
|
||||||
|
| Name | Type | Description |
|
||||||
|
| ----------- | ---- | --------------------------------------------- |
|
||||||
|
| **RETURNS** | list | The list of aliases in the knowledge base. |
|
||||||
|
|
||||||
|
## KnowledgeBase.get_candidates {#get_candidates tag="method"}
|
||||||
|
|
||||||
|
Given a certain textual mention as input, retrieve a list of candidate entities
|
||||||
|
of type [`Candidate`](/api/kb/#candidate_init).
|
||||||
|
|
||||||
|
> #### Example
|
||||||
|
>
|
||||||
|
> ```python
|
||||||
|
> candidates = kb.get_candidates("Douglas")
|
||||||
|
> ```
|
||||||
|
|
||||||
|
| Name | Type | Description |
|
||||||
|
| ------------- | ------------- | -------------------------------------------------- |
|
||||||
|
| `alias` | unicode | The textual mention or alias |
|
||||||
|
| **RETURNS** | iterable | The list of relevant `Candidate` objects |
|
||||||
|
|
||||||
|
## KnowledgeBase.get_vector {#get_vector tag="method"}
|
||||||
|
|
||||||
|
Given a certain entity ID, retrieve its pre-trained entity vector.
|
||||||
|
|
||||||
|
> #### Example
|
||||||
|
>
|
||||||
|
> ```python
|
||||||
|
> vector = kb.get_vector("Q42")
|
||||||
|
> ```
|
||||||
|
|
||||||
|
| Name | Type | Description |
|
||||||
|
| ------------- | ------------- | -------------------------------------------------- |
|
||||||
|
| `entity` | unicode | The entity ID |
|
||||||
|
| **RETURNS** | vector | The entity vector |
|
||||||
|
|
||||||
|
## KnowledgeBase.get_prior_prob {#get_prior_prob tag="method"}
|
||||||
|
|
||||||
|
Given a certain entity ID and a certain textual mention, retrieve
|
||||||
|
the prior probability of the fact that the mention links to the entity ID.
|
||||||
|
|
||||||
|
> #### Example
|
||||||
|
>
|
||||||
|
> ```python
|
||||||
|
> probability = kb.get_prior_prob("Q42", "Douglas")
|
||||||
|
> ```
|
||||||
|
|
||||||
|
| Name | Type | Description |
|
||||||
|
| ------------- | ------------- | --------------------------------------------------------------- |
|
||||||
|
| `entity` | unicode | The entity ID |
|
||||||
|
| `alias` | unicode | The textual mention or alias |
|
||||||
|
| **RETURNS** | float | The prior probability of the `alias` referring to the `entity` |
|
||||||
|
|
||||||
|
## KnowledgeBase.dump {#dump tag="method"}
|
||||||
|
|
||||||
|
Save the current state of the knowledge base to a directory.
|
||||||
|
|
||||||
|
> #### Example
|
||||||
|
>
|
||||||
|
> ```python
|
||||||
|
> kb.dump(loc)
|
||||||
|
> ```
|
||||||
|
|
||||||
|
| Name | Type | Description |
|
||||||
|
| ------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------ |
|
||||||
|
| `loc` | unicode / `Path` | A path to a directory, which will be created if it doesn't exist. Paths may be either strings or `Path`-like objects. |
|
||||||
|
|
||||||
|
## KnowledgeBase.load_bulk {#load_bulk tag="method"}
|
||||||
|
|
||||||
|
Restore the state of the knowledge base from a given directory. Note that the [`Vocab`](/api/vocab)
|
||||||
|
should also be the same as the one used to create the KB.
|
||||||
|
|
||||||
|
> #### Example
|
||||||
|
>
|
||||||
|
> ```python
|
||||||
|
> from spacy.kb import KnowledgeBase
|
||||||
|
> from spacy.vocab import Vocab
|
||||||
|
> vocab = Vocab().from_disk("/path/to/vocab")
|
||||||
|
> kb = KnowledgeBase(vocab=vocab, entity_vector_length=64)
|
||||||
|
> kb.load_bulk("/path/to/kb")
|
||||||
|
> ```
|
||||||
|
|
||||||
|
|
||||||
|
| Name | Type | Description |
|
||||||
|
| ----------- | ---------------- | ----------------------------------------------------------------------------------------- |
|
||||||
|
| `loc` | unicode / `Path` | A path to a directory. Paths may be either strings or `Path`-like objects. |
|
||||||
|
| **RETURNS** | `KnowledgeBase` | The modified `KnowledgeBase` object. |
|
||||||
|
|
||||||
|
|
||||||
|
## Candidate.\_\_init\_\_ {#candidate_init tag="method"}
|
||||||
|
|
||||||
|
Construct a `Candidate` object. Usually this constructor is not called directly,
|
||||||
|
but instead these objects are returned by the [`get_candidates`](/api/kb#get_candidates) method
|
||||||
|
of a `KnowledgeBase`.
|
||||||
|
|
||||||
|
> #### Example
|
||||||
|
>
|
||||||
|
> ```python
|
||||||
|
> from spacy.kb import Candidate
|
||||||
|
> candidate = Candidate(kb, entity_hash, entity_freq, entity_vector, alias_hash, prior_prob)
|
||||||
|
> ```
|
||||||
|
|
||||||
|
| Name | Type | Description |
|
||||||
|
| ------------- | --------------- | -------------------------------------------------------------- |
|
||||||
|
| `kb` | `KnowledgeBase` | The knowledge base that defined this candidate. |
|
||||||
|
| `entity_hash` | int | The hash of the entity's KB ID. |
|
||||||
|
| `entity_freq` | float | The entity frequency as recorded in the KB. |
|
||||||
|
| `alias_hash` | int | The hash of the textual mention or alias. |
|
||||||
|
| `prior_prob` | float | The prior probability of the `alias` referring to the `entity` |
|
||||||
|
| **RETURNS** | `Candidate` | The newly constructed object. |
|
||||||
|
|
||||||
|
## Candidate attributes {#candidate_attributes}
|
||||||
|
|
||||||
|
| Name | Type | Description |
|
||||||
|
| ---------------------- | ------------ | ------------------------------------------------------------------ |
|
||||||
|
| `entity` | int | The entity's unique KB identifier |
|
||||||
|
| `entity_` | unicode | The entity's unique KB identifier |
|
||||||
|
| `alias` | int | The alias or textual mention |
|
||||||
|
| `alias_` | unicode | The alias or textual mention |
|
||||||
|
| `prior_prob` | long | The prior probability of the `alias` referring to the `entity` |
|
||||||
|
| `entity_freq` | long | The frequency of the entity in a typical corpus |
|
||||||
|
| `entity_vector` | vector | The pre-trained vector of the entity |
|
|
@ -19,11 +19,12 @@ Create a Span object from the slice `doc[start : end]`.
|
||||||
> ```
|
> ```
|
||||||
|
|
||||||
| Name | Type | Description |
|
| Name | Type | Description |
|
||||||
| ----------- | ---------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
|
| ----------- | ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------|
|
||||||
| `doc` | `Doc` | The parent document. |
|
| `doc` | `Doc` | The parent document. |
|
||||||
| `start` | int | The index of the first token of the span. |
|
| `start` | int | The index of the first token of the span. |
|
||||||
| `end` | int | The index of the first token after the span. |
|
| `end` | int | The index of the first token after the span. |
|
||||||
| `label` | int / unicode | A label to attach to the span, e.g. for named entities. As of v2.1, the label can also be a unicode string. |
|
| `label` | int / unicode | A label to attach to the span, e.g. for named entities. As of v2.1, the label can also be a unicode string. |
|
||||||
|
| `kb_id` | int / unicode | A knowledge base ID to attach to the span, e.g. for named entities. The ID can be an integer or a unicode 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. |
|
| **RETURNS** | `Span` | The newly constructed object. |
|
||||||
|
|
||||||
|
@ -477,9 +478,11 @@ The L2 norm of the span's vector representation.
|
||||||
| `text_with_ws` | unicode | The text content of the span with a trailing whitespace character if the last token has one. |
|
| `text_with_ws` | unicode | The text content of the span with a trailing whitespace character if the last token has one. |
|
||||||
| `orth` | int | ID of the verbatim text content. |
|
| `orth` | int | ID of the verbatim text content. |
|
||||||
| `orth_` | unicode | Verbatim text content (identical to `Span.text`). Exists mostly for consistency with the other attributes. |
|
| `orth_` | unicode | Verbatim text content (identical to `Span.text`). Exists mostly for consistency with the other attributes. |
|
||||||
| `label` | int | The span's label. |
|
| `label` | int | The hash value of the span's label. |
|
||||||
| `label_` | unicode | The span's label. |
|
| `label_` | unicode | The span's label. |
|
||||||
| `lemma_` | unicode | The span's lemma. |
|
| `lemma_` | unicode | The span's lemma. |
|
||||||
|
| `kb_id` | int | The hash value of the knowledge base ID referred to by the span. |
|
||||||
|
| `kb_id_` | unicode | The knowledge base ID referred to by the span. |
|
||||||
| `ent_id` | int | The hash value of the named entity the token is an instance of. |
|
| `ent_id` | int | The hash value of the named entity the token is an instance of. |
|
||||||
| `ent_id_` | unicode | The string ID of the named entity the token is an instance of. |
|
| `ent_id_` | unicode | The string ID of the named entity the token is an instance of. |
|
||||||
| `sentiment` | float | A scalar value indicating the positivity or negativity of the span. |
|
| `sentiment` | float | A scalar value indicating the positivity or negativity of the span. |
|
||||||
|
|
|
@ -97,7 +97,7 @@ Apply the pipeline's model to a batch of docs, without modifying them.
|
||||||
>
|
>
|
||||||
> ```python
|
> ```python
|
||||||
> tagger = Tagger(nlp.vocab)
|
> tagger = Tagger(nlp.vocab)
|
||||||
> scores = tagger.predict([doc1, doc2])
|
> scores, tensors = tagger.predict([doc1, doc2])
|
||||||
> ```
|
> ```
|
||||||
|
|
||||||
| Name | Type | Description |
|
| Name | Type | Description |
|
||||||
|
@ -113,14 +113,16 @@ Modify a batch of documents, using pre-computed scores.
|
||||||
>
|
>
|
||||||
> ```python
|
> ```python
|
||||||
> tagger = Tagger(nlp.vocab)
|
> tagger = Tagger(nlp.vocab)
|
||||||
> scores = tagger.predict([doc1, doc2])
|
> scores, tensors = tagger.predict([doc1, doc2])
|
||||||
> tagger.set_annotations([doc1, doc2], scores)
|
> tagger.set_annotations([doc1, doc2], scores, tensors)
|
||||||
> ```
|
> ```
|
||||||
|
|
||||||
| Name | Type | Description |
|
| Name | Type | Description |
|
||||||
| -------- | -------- | ------------------------------------------------ |
|
| -------- | -------- | ----------------------------------------------------- |
|
||||||
| `docs` | iterable | The documents to modify. |
|
| `docs` | iterable | The documents to modify. |
|
||||||
| `scores` | - | The scores to set, produced by `Tagger.predict`. |
|
| `scores` | - | The scores to set, produced by `Tagger.predict`. |
|
||||||
|
| `tensors`| iterable | The token representations used to predict the scores. |
|
||||||
|
|
||||||
|
|
||||||
## Tagger.update {#update tag="method"}
|
## Tagger.update {#update tag="method"}
|
||||||
|
|
||||||
|
|
|
@ -116,7 +116,7 @@ Apply the pipeline's model to a batch of docs, without modifying them.
|
||||||
>
|
>
|
||||||
> ```python
|
> ```python
|
||||||
> textcat = TextCategorizer(nlp.vocab)
|
> textcat = TextCategorizer(nlp.vocab)
|
||||||
> scores = textcat.predict([doc1, doc2])
|
> scores, tensors = textcat.predict([doc1, doc2])
|
||||||
> ```
|
> ```
|
||||||
|
|
||||||
| Name | Type | Description |
|
| Name | Type | Description |
|
||||||
|
@ -132,14 +132,15 @@ Modify a batch of documents, using pre-computed scores.
|
||||||
>
|
>
|
||||||
> ```python
|
> ```python
|
||||||
> textcat = TextCategorizer(nlp.vocab)
|
> textcat = TextCategorizer(nlp.vocab)
|
||||||
> scores = textcat.predict([doc1, doc2])
|
> scores, tensors = textcat.predict([doc1, doc2])
|
||||||
> textcat.set_annotations([doc1, doc2], scores)
|
> textcat.set_annotations([doc1, doc2], scores, tensors)
|
||||||
> ```
|
> ```
|
||||||
|
|
||||||
| Name | Type | Description |
|
| Name | Type | Description |
|
||||||
| -------- | -------- | --------------------------------------------------------- |
|
| -------- | -------- | --------------------------------------------------------- |
|
||||||
| `docs` | iterable | The documents to modify. |
|
| `docs` | iterable | The documents to modify. |
|
||||||
| `scores` | - | The scores to set, produced by `TextCategorizer.predict`. |
|
| `scores` | - | The scores to set, produced by `TextCategorizer.predict`. |
|
||||||
|
| `tensors`| iterable | The token representations used to predict the scores. |
|
||||||
|
|
||||||
## TextCategorizer.update {#update tag="method"}
|
## TextCategorizer.update {#update tag="method"}
|
||||||
|
|
||||||
|
@ -227,13 +228,13 @@ Modify the pipe's model, to use the given parameter values.
|
||||||
>
|
>
|
||||||
> ```python
|
> ```python
|
||||||
> textcat = TextCategorizer(nlp.vocab)
|
> textcat = TextCategorizer(nlp.vocab)
|
||||||
> with textcat.use_params():
|
> with textcat.use_params(optimizer.averages):
|
||||||
> textcat.to_disk("/best_model")
|
> textcat.to_disk("/best_model")
|
||||||
> ```
|
> ```
|
||||||
|
|
||||||
| Name | Type | Description |
|
| Name | Type | Description |
|
||||||
| -------- | ---- | ---------------------------------------------------------------------------------------------------------- |
|
| -------- | ---- | ---------------------------------------------------------------------------------------------------------- |
|
||||||
| `params` | - | The parameter values to use in the model. At the end of the context, the original parameters are restored. |
|
| `params` | dict | The parameter values to use in the model. At the end of the context, the original parameters are restored. |
|
||||||
|
|
||||||
## TextCategorizer.add_label {#add_label tag="method"}
|
## TextCategorizer.add_label {#add_label tag="method"}
|
||||||
|
|
||||||
|
|
|
@ -425,8 +425,10 @@ The L2 norm of the token's vector representation.
|
||||||
| `i` | int | The index of the token within the parent document. |
|
| `i` | int | The index of the token within the parent document. |
|
||||||
| `ent_type` | int | Named entity type. |
|
| `ent_type` | int | Named entity type. |
|
||||||
| `ent_type_` | unicode | Named entity type. |
|
| `ent_type_` | unicode | Named entity type. |
|
||||||
| `ent_iob` | int | IOB code of named entity tag. `3` means the token begins an entity, `2` means it is outside an entity, `1` means it is inside an entity, and `0` means no entity tag is set. | |
|
| `ent_iob` | int | IOB code of named entity tag. `3` means the token begins an entity, `2` means it is outside an entity, `1` means it is inside an entity, and `0` means no entity tag is set. |
|
||||||
| `ent_iob_` | unicode | IOB code of named entity tag. "B" means the token begins an entity, "I" means it is inside an entity, "O" means it is outside an entity, and "" means no entity tag is set. |
|
| `ent_iob_` | unicode | IOB code of named entity tag. "B" means the token begins an entity, "I" means it is inside an entity, "O" means it is outside an entity, and "" means no entity tag is set. |
|
||||||
|
| `ent_kb_id` <Tag variant="new">2.2</Tag> | int | Knowledge base ID that refers to the named entity this token is a part of, if any. |
|
||||||
|
| `ent_kb_id_` <Tag variant="new">2.2</Tag> | unicode | Knowledge base ID that refers to the named entity this token is a part of, if any. |
|
||||||
| `ent_id` | int | ID of the entity the token is an instance of, if any. Currently not used, but potentially for coreference resolution. |
|
| `ent_id` | int | ID of the entity the token is an instance of, if any. Currently not used, but potentially for coreference resolution. |
|
||||||
| `ent_id_` | unicode | ID of the entity the token is an instance of, if any. Currently not used, but potentially for coreference resolution. |
|
| `ent_id_` | unicode | ID of the entity the token is an instance of, if any. Currently not used, but potentially for coreference resolution. |
|
||||||
| `lemma` | int | Base form of the token, with no inflectional suffixes. |
|
| `lemma` | int | Base form of the token, with no inflectional suffixes. |
|
||||||
|
|
|
@ -21,7 +21,7 @@ for ent in doc.ents:
|
||||||
> - **Text:** The original entity text.
|
> - **Text:** The original entity text.
|
||||||
> - **Start:** Index of start of entity in the `Doc`.
|
> - **Start:** Index of start of entity in the `Doc`.
|
||||||
> - **End:** Index of end of entity in the `Doc`.
|
> - **End:** Index of end of entity in the `Doc`.
|
||||||
> - **LabeL:** Entity label, i.e. type.
|
> - **Label:** Entity label, i.e. type.
|
||||||
|
|
||||||
| Text | Start | End | Label | Description |
|
| Text | Start | End | Label | Description |
|
||||||
| ----------- | :---: | :-: | ------- | ---------------------------------------------------- |
|
| ----------- | :---: | :-: | ------- | ---------------------------------------------------- |
|
||||||
|
|
|
@ -13,7 +13,7 @@ passed on to the next component.
|
||||||
> component.
|
> component.
|
||||||
|
|
||||||
| Name | Component | Creates | Description |
|
| Name | Component | Creates | Description |
|
||||||
| ------------- | ------------------------------------------------------------------ | ----------------------------------------------------------- | ------------------------------------------------ |
|
| ----------------- | ------------------------------------------------------------------ | ----------------------------------------------------------- | ------------------------------------------------ |
|
||||||
| **tokenizer** | [`Tokenizer`](/api/tokenizer) | `Doc` | Segment text into tokens. |
|
| **tokenizer** | [`Tokenizer`](/api/tokenizer) | `Doc` | Segment text into tokens. |
|
||||||
| **tagger** | [`Tagger`](/api/tagger) | `Doc[i].tag` | Assign part-of-speech tags. |
|
| **tagger** | [`Tagger`](/api/tagger) | `Doc[i].tag` | Assign part-of-speech tags. |
|
||||||
| **parser** | [`DependencyParser`](/api/dependencyparser) | `Doc[i].head`, `Doc[i].dep`, `Doc.sents`, `Doc.noun_chunks` | Assign dependency labels. |
|
| **parser** | [`DependencyParser`](/api/dependencyparser) | `Doc[i].head`, `Doc[i].dep`, `Doc.sents`, `Doc.noun_chunks` | Assign dependency labels. |
|
||||||
|
@ -49,6 +49,10 @@ them, its dependency predictions may be different. Similarly, it matters if you
|
||||||
add the [`EntityRuler`](/api/entityruler) before or after the statistical entity
|
add the [`EntityRuler`](/api/entityruler) before or after the statistical entity
|
||||||
recognizer: if it's added before, the entity recognizer will take the existing
|
recognizer: if it's added before, the entity recognizer will take the existing
|
||||||
entities into account when making predictions.
|
entities into account when making predictions.
|
||||||
|
The [`EntityLinker`](/api/entitylinker), which resolves named entities to
|
||||||
|
knowledge base IDs, should be preceded by
|
||||||
|
a pipeline component that recognizes entities such as the
|
||||||
|
[`EntityRecognizer`](/api/entityrecognizer).
|
||||||
|
|
||||||
</Accordion>
|
</Accordion>
|
||||||
|
|
||||||
|
|
|
@ -20,7 +20,7 @@ difference, the more significant the gradient and the updates to our model.
|
||||||
![The training process](../../images/training.svg)
|
![The training process](../../images/training.svg)
|
||||||
|
|
||||||
When training a model, we don't just want it to memorize our examples – we want
|
When training a model, we don't just want it to memorize our examples – we want
|
||||||
it to come up with theory that can be **generalized across other examples**.
|
it to come up with a theory that can be **generalized across other examples**.
|
||||||
After all, we don't just want the model to learn that this one instance of
|
After all, we don't just want the model to learn that this one instance of
|
||||||
"Amazon" right here is a company – we want it to learn that "Amazon", in
|
"Amazon" right here is a company – we want it to learn that "Amazon", in
|
||||||
contexts _like this_, is most likely a company. That's why the training data
|
contexts _like this_, is most likely a company. That's why the training data
|
||||||
|
|
|
@ -26,7 +26,7 @@ Here's a quick comparison of the functionalities offered by spaCy,
|
||||||
| Sentence segmentation | ✅ | ✅ | ✅ |
|
| Sentence segmentation | ✅ | ✅ | ✅ |
|
||||||
| Dependency parsing | ✅ | ❌ | ✅ |
|
| Dependency parsing | ✅ | ❌ | ✅ |
|
||||||
| Entity recognition | ✅ | ✅ | ✅ |
|
| Entity recognition | ✅ | ✅ | ✅ |
|
||||||
| Entity linking | ❌ | ❌ | ❌ |
|
| Entity linking | ✅ | ❌ | ❌ |
|
||||||
| Coreference resolution | ❌ | ❌ | ✅ |
|
| Coreference resolution | ❌ | ❌ | ✅ |
|
||||||
|
|
||||||
### When should I use what? {#comparison-usage}
|
### When should I use what? {#comparison-usage}
|
||||||
|
|
|
@ -576,6 +576,54 @@ import DisplacyEntHtml from 'images/displacy-ent2.html'
|
||||||
|
|
||||||
<Iframe title="displaCy visualizer for entities" html={DisplacyEntHtml} height={180} />
|
<Iframe title="displaCy visualizer for entities" html={DisplacyEntHtml} height={180} />
|
||||||
|
|
||||||
|
## Entity Linking {#entity-linking}
|
||||||
|
|
||||||
|
To ground the named entities into the "real-world",
|
||||||
|
spaCy provides functionality to perform entity linking, which resolves a textual entity
|
||||||
|
to a unique identifier from a knowledge base (KB).
|
||||||
|
|
||||||
|
The default model assigns WikiData identifiers, but you can create your own
|
||||||
|
[`KnowledgeBase`](/api/kb) and [train a new Entity Linking model](/usage/training#entity-linker) using
|
||||||
|
that custom-made KB.
|
||||||
|
|
||||||
|
|
||||||
|
### Accessing entity identifiers {#accessing}
|
||||||
|
|
||||||
|
The annotated KB identifier is accessible as either a hash value
|
||||||
|
or as a string, using the attributes
|
||||||
|
`ent.kb_id` and `ent.kb_id_` of a [`Span`](/api/span) object,
|
||||||
|
or the `ent_kb_id` and `ent_kb_id_` attributes of a [`Token`](/api/token) object.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
### {executable="true"}
|
||||||
|
import spacy
|
||||||
|
|
||||||
|
nlp = spacy.load("my_custom_el_model")
|
||||||
|
doc = nlp(u"Ada Lovelace was born in London")
|
||||||
|
|
||||||
|
# document level
|
||||||
|
ents = [(e.text, e.label_, e.kb_id_) for e in doc.ents]
|
||||||
|
print(ents) # [('Ada Lovelace', 'PERSON', 'Q7259'), ('London', 'GPE', 'Q84')]
|
||||||
|
|
||||||
|
# token level
|
||||||
|
ent_ada_0 = [doc[0].text, doc[0].ent_type_, doc[0].ent_kb_id_]
|
||||||
|
ent_ada_1 = [doc[1].text, doc[1].ent_type_, doc[1].ent_kb_id_]
|
||||||
|
ent_london_5 = [doc[5].text, doc[5].ent_type_, doc[5].ent_kb_id_]
|
||||||
|
print(ent_ada_0) # ['Ada', 'PERSON', 'Q7259']
|
||||||
|
print(ent_ada_1) # ['Lovelace', 'PERSON', 'Q7259']
|
||||||
|
print(ent_london_5) # ['London', 'GPE', 'Q84']
|
||||||
|
```
|
||||||
|
|
||||||
|
| Text | ent_type\_ | ent_kb_id\_ |
|
||||||
|
| --------- | ---------- | ------------ |
|
||||||
|
| Ada | `"PERSON"` | `"Q7259"` |
|
||||||
|
| Lovelace | `"PERSON"` | `"Q7259"` |
|
||||||
|
| was | `""` | `""` |
|
||||||
|
| born | `""` | `""` |
|
||||||
|
| in | `""` | `""` |
|
||||||
|
| London | `"GPE"` | `"Q84"` |
|
||||||
|
|
||||||
## Tokenization {#tokenization}
|
## Tokenization {#tokenization}
|
||||||
|
|
||||||
Tokenization is the task of splitting a text into meaningful segments, called
|
Tokenization is the task of splitting a text into meaningful segments, called
|
||||||
|
|
|
@ -213,6 +213,7 @@ require them in the pipeline settings in your model's `meta.json`.
|
||||||
| `tagger` | [`Tagger`](/api/tagger) | Assign part-of-speech-tags. |
|
| `tagger` | [`Tagger`](/api/tagger) | Assign part-of-speech-tags. |
|
||||||
| `parser` | [`DependencyParser`](/api/dependencyparser) | Assign dependency labels. |
|
| `parser` | [`DependencyParser`](/api/dependencyparser) | Assign dependency labels. |
|
||||||
| `ner` | [`EntityRecognizer`](/api/entityrecognizer) | Assign named entities. |
|
| `ner` | [`EntityRecognizer`](/api/entityrecognizer) | Assign named entities. |
|
||||||
|
| `entity_linker` | [`EntityLinker`](/api/entitylinker) | Assign knowledge base IDs to named entities. Should be added after the entity recognizer. |
|
||||||
| `textcat` | [`TextCategorizer`](/api/textcategorizer) | Assign text categories. |
|
| `textcat` | [`TextCategorizer`](/api/textcategorizer) | Assign text categories. |
|
||||||
| `entity_ruler` | [`EntityRuler`](/api/entityruler) | Assign named entities based on pattern rules. |
|
| `entity_ruler` | [`EntityRuler`](/api/entityruler) | Assign named entities based on pattern rules. |
|
||||||
| `sentencizer` | [`Sentencizer`](/api/sentencizer) | Add rule-based sentence segmentation without the dependency parse. |
|
| `sentencizer` | [`Sentencizer`](/api/sentencizer) | Add rule-based sentence segmentation without the dependency parse. |
|
||||||
|
|
|
@ -122,6 +122,7 @@ related to more general machine learning functionality.
|
||||||
| **Lemmatization** | Assigning the base forms of words. For example, the lemma of "was" is "be", and the lemma of "rats" is "rat". |
|
| **Lemmatization** | Assigning the base forms of words. For example, the lemma of "was" is "be", and the lemma of "rats" is "rat". |
|
||||||
| **Sentence Boundary Detection** (SBD) | Finding and segmenting individual sentences. |
|
| **Sentence Boundary Detection** (SBD) | Finding and segmenting individual sentences. |
|
||||||
| **Named Entity Recognition** (NER) | Labelling named "real-world" objects, like persons, companies or locations. |
|
| **Named Entity Recognition** (NER) | Labelling named "real-world" objects, like persons, companies or locations. |
|
||||||
|
| **Entity Linking** (EL) | Disambiguating textual entities to unique identifiers in a Knowledge Base. |
|
||||||
| **Similarity** | Comparing words, text spans and documents and how similar they are to each other. |
|
| **Similarity** | Comparing words, text spans and documents and how similar they are to each other. |
|
||||||
| **Text Classification** | Assigning categories or labels to a whole document, or parts of a document. |
|
| **Text Classification** | Assigning categories or labels to a whole document, or parts of a document. |
|
||||||
| **Rule-based Matching** | Finding sequences of tokens based on their texts and linguistic annotations, similar to regular expressions. |
|
| **Rule-based Matching** | Finding sequences of tokens based on their texts and linguistic annotations, similar to regular expressions. |
|
||||||
|
@ -237,6 +238,15 @@ of a model, see the usage guides on
|
||||||
|
|
||||||
</Infobox>
|
</Infobox>
|
||||||
|
|
||||||
|
<Infobox title="📖 Entity Linking">
|
||||||
|
|
||||||
|
To learn more about entity linking in spaCy, and how to **train and update**
|
||||||
|
the entity linker predictions, see the usage guides on
|
||||||
|
[entity linking](/usage/linguistic-features#entity-linking) and
|
||||||
|
[training the entity linker](/usage/training#entity-linker).
|
||||||
|
|
||||||
|
</Infobox>
|
||||||
|
|
||||||
### Word vectors and similarity {#vectors-similarity model="vectors"}
|
### Word vectors and similarity {#vectors-similarity model="vectors"}
|
||||||
|
|
||||||
import Vectors101 from 'usage/101/\_vectors-similarity.md'
|
import Vectors101 from 'usage/101/\_vectors-similarity.md'
|
||||||
|
@ -383,6 +393,75 @@ spaCy will also export the `Vocab` when you save a `Doc` or `nlp` object. This
|
||||||
will give you the object and its encoded annotations, plus the "key" to decode
|
will give you the object and its encoded annotations, plus the "key" to decode
|
||||||
it.
|
it.
|
||||||
|
|
||||||
|
## Knowledge Base {#kb}
|
||||||
|
|
||||||
|
To support the entity linking task, spaCy stores external knowledge in a
|
||||||
|
[`KnowledgeBase`](/api/kb). The knowledge base (KB) uses the `Vocab` to store its
|
||||||
|
data efficiently.
|
||||||
|
|
||||||
|
> - **Mention**: A textual occurrence of a named entity, e.g. 'Miss Lovelace'.
|
||||||
|
> - **KB ID**: A unique identifier refering to a particular real-world concept, e.g. 'Q7259'.
|
||||||
|
> - **Alias**: A plausible synonym or description for a certain KB ID, e.g. 'Ada Lovelace'.
|
||||||
|
> - **Prior probability**: The probability of a certain mention resolving to a certain KB ID,
|
||||||
|
prior to knowing anything about the context in which the mention is used.
|
||||||
|
> - **Entity vector**: A pretrained word vector capturing the entity description.
|
||||||
|
|
||||||
|
A knowledge base is created by first adding all entities to it. Next, for each
|
||||||
|
potential mention or alias, a list of relevant KB IDs and their prior probabilities
|
||||||
|
is added. The sum of these prior probabilities should never exceed 1 for any given alias.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
### {executable="true"}
|
||||||
|
import spacy
|
||||||
|
from spacy.kb import KnowledgeBase
|
||||||
|
|
||||||
|
# load the model and create an empty KB
|
||||||
|
nlp = spacy.load('en_core_web_sm')
|
||||||
|
kb = KnowledgeBase(vocab=nlp.vocab, entity_vector_length=3)
|
||||||
|
|
||||||
|
# adding entities
|
||||||
|
kb.add_entity(entity="Q1004791", freq=6, entity_vector=[0, 3, 5])
|
||||||
|
kb.add_entity(entity="Q42", freq=342, entity_vector=[1, 9, -3])
|
||||||
|
kb.add_entity(entity="Q5301561", freq=12, entity_vector=[-2, 4, 2])
|
||||||
|
|
||||||
|
# adding aliases
|
||||||
|
kb.add_alias(alias="Douglas", entities=["Q1004791", "Q42", "Q5301561"], probabilities=[0.6, 0.1, 0.2])
|
||||||
|
kb.add_alias(alias="Douglas Adams", entities=["Q42"], probabilities=[0.9])
|
||||||
|
|
||||||
|
print()
|
||||||
|
print("Number of entities in KB:",kb.get_size_entities()) # 3
|
||||||
|
print("Number of aliases in KB:", kb.get_size_aliases()) # 2
|
||||||
|
```
|
||||||
|
|
||||||
|
### Candidate generation
|
||||||
|
|
||||||
|
Given a textual entity, the Knowledge Base can provide a list of plausible candidates or
|
||||||
|
entity identifiers. The [`EntityLinker`](/api/entitylinker) will take this list of candidates
|
||||||
|
as input, and disambiguate the mention to the most probable identifier, given the
|
||||||
|
document context.
|
||||||
|
|
||||||
|
```python
|
||||||
|
### {executable="true"}
|
||||||
|
import spacy
|
||||||
|
from spacy.kb import KnowledgeBase
|
||||||
|
|
||||||
|
nlp = spacy.load('en_core_web_sm')
|
||||||
|
kb = KnowledgeBase(vocab=nlp.vocab, entity_vector_length=3)
|
||||||
|
|
||||||
|
# adding entities
|
||||||
|
kb.add_entity(entity="Q1004791", freq=6, entity_vector=[0, 3, 5])
|
||||||
|
kb.add_entity(entity="Q42", freq=342, entity_vector=[1, 9, -3])
|
||||||
|
kb.add_entity(entity="Q5301561", freq=12, entity_vector=[-2, 4, 2])
|
||||||
|
|
||||||
|
# adding aliases
|
||||||
|
kb.add_alias(alias="Douglas", entities=["Q1004791", "Q42", "Q5301561"], probabilities=[0.6, 0.1, 0.2])
|
||||||
|
|
||||||
|
candidates = kb.get_candidates("Douglas")
|
||||||
|
for c in candidates:
|
||||||
|
print(" ", c.entity_, c.prior_prob, c.entity_vector)
|
||||||
|
```
|
||||||
|
|
||||||
## Serialization {#serialization}
|
## Serialization {#serialization}
|
||||||
|
|
||||||
import Serialization101 from 'usage/101/\_serialization.md'
|
import Serialization101 from 'usage/101/\_serialization.md'
|
||||||
|
|
|
@ -10,8 +10,9 @@ menu:
|
||||||
---
|
---
|
||||||
|
|
||||||
This guide describes how to train new statistical models for spaCy's
|
This guide describes how to train new statistical models for spaCy's
|
||||||
part-of-speech tagger, named entity recognizer and dependency parser. Once the
|
part-of-speech tagger, named entity recognizer, dependency parser,
|
||||||
model is trained, you can then [save and load](/usage/saving-loading#models) it.
|
text classifier and entity linker. Once the model is trained,
|
||||||
|
you can then [save and load](/usage/saving-loading#models) it.
|
||||||
|
|
||||||
## Training basics {#basics}
|
## Training basics {#basics}
|
||||||
|
|
||||||
|
@ -221,9 +222,10 @@ 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
|
> return an optimizer function to update the model's weights. Can take an
|
||||||
> optional function converting the training data to spaCy's training
|
> optional function converting the training data to spaCy's training format.
|
||||||
> format. -[`update()`](/api/language#update): Update the model with the
|
> - [`update()`](/api/language#update): Update the model with the
|
||||||
> training example and gold data. -[`to_disk()`](/api/language#to_disk): Save
|
> training example and gold data.
|
||||||
|
> - [`to_disk()`](/api/language#to_disk): Save
|
||||||
> the updated model to a directory.
|
> the updated model to a directory.
|
||||||
|
|
||||||
```python
|
```python
|
||||||
|
@ -401,6 +403,77 @@ referred to as the "catastrophic forgetting" problem.
|
||||||
4. **Save** the trained model using [`nlp.to_disk`](/api/language#to_disk).
|
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.
|
5. **Test** the model to make sure the new entity is recognized correctly.
|
||||||
|
|
||||||
|
## 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 are pretrained and stored in the KB before
|
||||||
|
the entity linking model will be trained.
|
||||||
|
|
||||||
|
The following example shows how to build a knowledge base from scratch,
|
||||||
|
given a list of entities and potential aliases. The script further demonstrates
|
||||||
|
how to pretrain and store the entity vectors. To run this example, the script
|
||||||
|
needs access to a `vocab` instance or an `nlp` model with pretrained word embeddings.
|
||||||
|
|
||||||
|
```python
|
||||||
|
https://github.com/explosion/spaCy/tree/master/examples/training/pretrain_kb.py
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Step by step guide {#step-by-step-kb}
|
||||||
|
|
||||||
|
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 and
|
||||||
|
a pre-defined [`vocab`](/api/vocab) object.
|
||||||
|
2. **Pretrain the entity embeddings** by running the descriptions of the entities
|
||||||
|
through a simple encoder-decoder network. The current implementation requires
|
||||||
|
the `nlp` model to have access to pre-trained word embeddings, but a custom
|
||||||
|
implementation of this enoding step can also be used.
|
||||||
|
3. **Construct the KB** by defining all entities with their pretrained vectors,
|
||||||
|
and all aliases with their prior probabilities.
|
||||||
|
4. **Save** the KB using [`kb.dump`](/api/kb#dump).
|
||||||
|
5. **Test** 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 pipe is then trained with your own
|
||||||
|
examples. To do so, you'll 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.
|
||||||
|
Don't forget to add the KB to the entity linker,
|
||||||
|
and to add the entity linker to the pipeline.
|
||||||
|
In practical applications, you will want a more advanced pipeline including
|
||||||
|
also a component for [named entity recognition](/usage/training#ner).
|
||||||
|
If you're using a model with additional components, make sure to disable all other
|
||||||
|
pipeline components during training using
|
||||||
|
[`nlp.disable_pipes`](/api/language#disable_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.
|
||||||
|
|
||||||
## Training the tagger and parser {#tagger-parser}
|
## Training the tagger and parser {#tagger-parser}
|
||||||
|
|
||||||
### Updating the Dependency Parser {#example-train-parser}
|
### Updating the Dependency Parser {#example-train-parser}
|
||||||
|
|
|
@ -75,6 +75,7 @@
|
||||||
{ "text": "Tagger", "url": "/api/tagger" },
|
{ "text": "Tagger", "url": "/api/tagger" },
|
||||||
{ "text": "DependencyParser", "url": "/api/dependencyparser" },
|
{ "text": "DependencyParser", "url": "/api/dependencyparser" },
|
||||||
{ "text": "EntityRecognizer", "url": "/api/entityrecognizer" },
|
{ "text": "EntityRecognizer", "url": "/api/entityrecognizer" },
|
||||||
|
{ "text": "EntityLinker", "url": "/api/entitylinker" },
|
||||||
{ "text": "TextCategorizer", "url": "/api/textcategorizer" },
|
{ "text": "TextCategorizer", "url": "/api/textcategorizer" },
|
||||||
{ "text": "Matcher", "url": "/api/matcher" },
|
{ "text": "Matcher", "url": "/api/matcher" },
|
||||||
{ "text": "PhraseMatcher", "url": "/api/phrasematcher" },
|
{ "text": "PhraseMatcher", "url": "/api/phrasematcher" },
|
||||||
|
@ -89,6 +90,7 @@
|
||||||
{ "text": "Vocab", "url": "/api/vocab" },
|
{ "text": "Vocab", "url": "/api/vocab" },
|
||||||
{ "text": "StringStore", "url": "/api/stringstore" },
|
{ "text": "StringStore", "url": "/api/stringstore" },
|
||||||
{ "text": "Vectors", "url": "/api/vectors" },
|
{ "text": "Vectors", "url": "/api/vectors" },
|
||||||
|
{ "text": "KnowledgeBase", "url": "/api/kb" },
|
||||||
{ "text": "GoldParse", "url": "/api/goldparse" },
|
{ "text": "GoldParse", "url": "/api/goldparse" },
|
||||||
{ "text": "GoldCorpus", "url": "/api/goldcorpus" },
|
{ "text": "GoldCorpus", "url": "/api/goldcorpus" },
|
||||||
{ "text": "Scorer", "url": "/api/scorer" }
|
{ "text": "Scorer", "url": "/api/scorer" }
|
||||||
|
|
Loading…
Reference in New Issue
Block a user