spaCy/website/docs/api/vectors.md

402 lines
16 KiB
Markdown
Raw Normal View History

---
title: Vectors
teaser: Store, save and load word vectors
tag: class
source: spacy/vectors.pyx
new: 2
---
Vectors data is kept in the `Vectors.data` attribute, which should be an
instance of `numpy.ndarray` (for CPU vectors) or `cupy.ndarray` (for GPU
vectors). Multiple keys can be mapped to the same vector, and not all of the
rows in the table need to be assigned so `vectors.n_keys` may be greater or
smaller than `vectors.shape[0]`.
## Vectors.\_\_init\_\_ {#init tag="method"}
Create a new vector store. You can set the vector values and keys directly on
initialization, or supply a `shape` keyword argument to create an empty table
you can add vectors to later.
> #### Example
>
> ```python
> from spacy.vectors import Vectors
>
> empty_vectors = Vectors(shape=(10000, 300))
>
> data = numpy.zeros((3, 300), dtype='f')
> keys = ["cat", "dog", "rat"]
> vectors = Vectors(data=data, keys=keys)
> ```
2020-08-17 14:45:24 +00:00
| Name | Description |
| -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| _keyword-only_ | |
| `shape` | Size of the table as `(n_entries, n_columns)`, the number of entries and number of columns. Not required if you're initializing the object with `data` and `keys`. ~~Tuple[int, int]~~ |
| `data` | The vector data. ~~numpy.ndarray[ndim=1, dtype=float32]~~ |
| `keys` | A sequence of keys aligned with the data. ~~Iterable[Union[str, int]]~~ |
| `name` | A name to identify the vectors table. ~~str~~ |
## Vectors.\_\_getitem\_\_ {#getitem tag="method"}
Get a vector by key. If the key is not found in the table, a `KeyError` is
raised.
> #### Example
>
> ```python
> cat_id = nlp.vocab.strings["cat"]
> cat_vector = nlp.vocab.vectors[cat_id]
> assert cat_vector == nlp.vocab["cat"].vector
> ```
2020-08-17 14:45:24 +00:00
| Name | Description |
| ----------- | ---------------------------------------------------------------- |
| `key` | The key to get the vector for. ~~int~~ |
| **RETURNS** | The vector for the key. ~~numpy.ndarray[ndim=1, dtype=float32]~~ |
## Vectors.\_\_setitem\_\_ {#setitem tag="method"}
Set a vector for the given key.
> #### Example
>
> ```python
> cat_id = nlp.vocab.strings["cat"]
> vector = numpy.random.uniform(-1, 1, (300,))
> nlp.vocab.vectors[cat_id] = vector
> ```
2020-08-17 14:45:24 +00:00
| Name | Description |
| -------- | ----------------------------------------------------------- |
| `key` | The key to set the vector for. ~~int~~ |
| `vector` | The vector to set. ~~numpy.ndarray[ndim=1, dtype=float32]~~ |
## Vectors.\_\_iter\_\_ {#iter tag="method"}
Iterate over the keys in the table.
> #### Example
>
> ```python
> for key in nlp.vocab.vectors:
> print(key, nlp.vocab.strings[key])
> ```
2020-08-17 14:45:24 +00:00
| Name | Description |
| ---------- | --------------------------- |
| **YIELDS** | A key in the table. ~~int~~ |
## Vectors.\_\_len\_\_ {#len tag="method"}
Return the number of vectors in the table.
> #### Example
>
> ```python
> vectors = Vectors(shape=(3, 300))
> assert len(vectors) == 3
> ```
2020-08-17 14:45:24 +00:00
| Name | Description |
| ----------- | ------------------------------------------- |
| **RETURNS** | The number of vectors in the table. ~~int~~ |
## Vectors.\_\_contains\_\_ {#contains tag="method"}
Check whether a key has been mapped to a vector entry in the table.
> #### Example
>
> ```python
> cat_id = nlp.vocab.strings["cat"]
> nlp.vocab.vectors.add(cat_id, numpy.random.uniform(-1, 1, (300,)))
> assert cat_id in vectors
> ```
2020-08-17 14:45:24 +00:00
| Name | Description |
| ----------- | -------------------------------------------- |
| `key` | The key to check. ~~int~~ |
| **RETURNS** | Whether the key has a vector entry. ~~bool~~ |
## Vectors.add {#add tag="method"}
Add a key to the table, optionally setting a vector value as well. Keys can be
mapped to an existing vector by setting `row`, or a new vector can be added.
When adding string keys, keep in mind that the `Vectors` class itself has no
[`StringStore`](/api/stringstore), so you have to store the hash-to-string
mapping separately. If you need to manage the strings, you should use the
`Vectors` via the [`Vocab`](/api/vocab) class, e.g. `vocab.vectors`.
> #### Example
>
> ```python
> vector = numpy.random.uniform(-1, 1, (300,))
> cat_id = nlp.vocab.strings["cat"]
> nlp.vocab.vectors.add(cat_id, vector=vector)
> nlp.vocab.vectors.add("dog", row=0)
> ```
2020-08-17 14:45:24 +00:00
| Name | Description |
| -------------- | ------------------------------------------------------------------------------- |
| `key` | The key to add. ~~Union[str, int]~~ |
| _keyword-only_ | |
| `vector` | An optional vector to add for the key. ~~numpy.ndarray[ndim=1, dtype=float32]~~ |
| `row` | An optional row number of a vector to map the key to. ~~int~~ |
| **RETURNS** | The row the vector was added to. ~~int~~ |
## Vectors.resize {#resize tag="method"}
Resize the underlying vectors array. If `inplace=True`, the memory is
reallocated. This may cause other references to the data to become invalid, so
only use `inplace=True` if you're sure that's what you want. If the number of
vectors is reduced, keys mapped to rows that have been deleted are removed.
These removed items are returned as a list of `(key, row)` tuples.
> #### Example
>
> ```python
> removed = nlp.vocab.vectors.resize((10000, 300))
> ```
2020-08-17 14:45:24 +00:00
| Name | Description |
| ----------- | ---------------------------------------------------------------------------------------- |
| `shape` | A `(rows, dims)` tuple describing the number of rows and dimensions. ~~Tuple[int, int]~~ |
| `inplace` | Reallocate the memory. ~~bool~~ |
| **RETURNS** | The removed items as a list of `(key, row)` tuples. ~~List[Tuple[int, int]]~~ |
## Vectors.keys {#keys tag="method"}
A sequence of the keys in the table.
> #### Example
>
> ```python
> for key in nlp.vocab.vectors.keys():
> print(key, nlp.vocab.strings[key])
> ```
2020-08-17 14:45:24 +00:00
| Name | Description |
| ----------- | --------------------------- |
| **RETURNS** | The keys. ~~Iterable[int]~~ |
## Vectors.values {#values tag="method"}
Iterate over vectors that have been assigned to at least one key. Note that some
vectors may be unassigned, so the number of vectors returned may be less than
the length of the vectors table.
> #### Example
>
> ```python
> for vector in nlp.vocab.vectors.values():
> print(vector)
> ```
2020-08-17 14:45:24 +00:00
| Name | Description |
| ---------- | --------------------------------------------------------------- |
| **YIELDS** | A vector in the table. ~~numpy.ndarray[ndim=1, dtype=float32]~~ |
## Vectors.items {#items tag="method"}
Iterate over `(key, vector)` pairs, in order.
> #### Example
>
> ```python
> for key, vector in nlp.vocab.vectors.items():
> print(key, nlp.vocab.strings[key], vector)
> ```
2020-08-17 14:45:24 +00:00
| Name | Description |
| ---------- | ------------------------------------------------------------------------------------- |
| **YIELDS** | `(key, vector)` pairs, in order. ~~Tuple[int, numpy.ndarray[ndim=1, dtype=float32]]~~ |
2019-09-26 14:22:33 +00:00
## Vectors.find {#find tag="method"}
2019-03-16 16:10:57 +00:00
Look up one or more keys by row, or vice versa.
> #### Example
>
> ```python
> row = nlp.vocab.vectors.find(key="cat")
> rows = nlp.vocab.vectors.find(keys=["cat", "dog"])
2019-03-16 16:10:57 +00:00
> key = nlp.vocab.vectors.find(row=256)
> keys = nlp.vocab.vectors.find(rows=[18, 256, 985])
> ```
2020-08-17 14:45:24 +00:00
| Name | Description |
| -------------- | -------------------------------------------------------------------------------------------- |
| _keyword-only_ | |
| `key` | Find the row that the given key points to. Returns int, `-1` if missing. ~~Union[str, int]~~ |
| `keys` | Find rows that the keys point to. Returns `numpy.ndarray`. ~~Iterable[Union[str, int]]~~ |
| `row` | Find the first key that points to the row. Returns integer. ~~int~~ |
| `rows` | Find the keys that point to the rows. Returns `numpy.ndarray`. ~~Iterable[int]~~ |
| **RETURNS** | The requested key, keys, row or rows. ~~Union[int, numpy.ndarray[ndim=1, dtype=float32]]~~ |
2019-03-16 16:10:57 +00:00
## Vectors.shape {#shape tag="property"}
Get `(rows, dims)` tuples of number of rows and number of dimensions in the
vector table.
> #### Example
>
> ```python
> vectors = Vectors(shape(1, 300))
> vectors.add("cat", numpy.random.uniform(-1, 1, (300,)))
> rows, dims = vectors.shape
> assert rows == 1
> assert dims == 300
> ```
2020-08-17 14:45:24 +00:00
| Name | Description |
| ----------- | ------------------------------------------ |
| **RETURNS** | A `(rows, dims)` pair. ~~Tuple[int, int]~~ |
## Vectors.size {#size tag="property"}
The vector size, i.e. `rows * dims`.
> #### Example
>
> ```python
> vectors = Vectors(shape=(500, 300))
> assert vectors.size == 150000
> ```
2020-08-17 14:45:24 +00:00
| Name | Description |
| ----------- | ------------------------ |
| **RETURNS** | The vector size. ~~int~~ |
## Vectors.is_full {#is_full tag="property"}
Whether the vectors table is full and has no slots are available for new keys.
If a table is full, it can be resized using
[`Vectors.resize`](/api/vectors#resize).
> #### Example
>
> ```python
> vectors = Vectors(shape=(1, 300))
> vectors.add("cat", numpy.random.uniform(-1, 1, (300,)))
> assert vectors.is_full
> ```
2020-08-17 14:45:24 +00:00
| Name | Description |
| ----------- | ------------------------------------------- |
| **RETURNS** | Whether the vectors table is full. ~~bool~~ |
## Vectors.n_keys {#n_keys tag="property"}
Get the number of keys in the table. Note that this is the number of _all_ keys,
2021-06-28 09:48:11 +00:00
not just unique vectors. If several keys are mapped to the same vectors, they
will be counted individually.
> #### Example
>
> ```python
> vectors = Vectors(shape=(10, 300))
> assert len(vectors) == 10
> assert vectors.n_keys == 0
> ```
2020-08-17 14:45:24 +00:00
| Name | Description |
| ----------- | -------------------------------------------- |
| **RETURNS** | The number of all keys in the table. ~~int~~ |
## Vectors.most_similar {#most_similar tag="method"}
For each of the given vectors, find the `n` most similar entries to it by
cosine. Queries are by vector. Results are returned as a
`(keys, best_rows, scores)` tuple. If `queries` is large, the calculations are
performed in chunks to avoid consuming too much memory. You can set the
`batch_size` to control the size/space trade-off during the calculations.
> #### Example
>
> ```python
> queries = numpy.asarray([numpy.random.uniform(-1, 1, (300,))])
> most_similar = nlp.vocab.vectors.most_similar(queries, n=10)
> ```
2020-08-17 14:45:24 +00:00
| Name | Description |
Document Assigned Attributes of Pipeline Components (#9041) * Add textcat docs * Add NER docs * Add Entity Linker docs * Add assigned fields docs for the tagger This also adds a preamble, since there wasn't one. * Add morphologizer docs * Add dependency parser docs * Update entityrecognizer docs This is a little weird because `Doc.ents` is the only thing assigned to, but it's actually a bidirectional property. * Add token fields for entityrecognizer * Fix section name * Add entity ruler docs * Add lemmatizer docs * Add sentencizer/recognizer docs * Update website/docs/api/entityrecognizer.md Co-authored-by: Adriane Boyd <adrianeboyd@gmail.com> * Update website/docs/api/entityruler.md Co-authored-by: Adriane Boyd <adrianeboyd@gmail.com> * Update website/docs/api/tagger.md Co-authored-by: Adriane Boyd <adrianeboyd@gmail.com> * Update website/docs/api/entityruler.md Co-authored-by: Adriane Boyd <adrianeboyd@gmail.com> * Update type for Doc.ents This was `Tuple[Span, ...]` everywhere but `Tuple[Span]` seems to be correct. * Run prettier * Apply suggestions from code review Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com> * Run prettier * Add transformers section This basically just moves and renames the "custom attributes" section from the bottom of the page to be consistent with "assigned attributes" on other pages. I looked at moving the paragraph just above the section into the section, but it includes the unrelated registry additions, so it seemed better to leave it unchanged. * Make table header consistent Co-authored-by: Adriane Boyd <adrianeboyd@gmail.com> Co-authored-by: Sofie Van Landeghem <svlandeg@users.noreply.github.com>
2021-09-01 10:09:39 +00:00
| -------------- | --------------------------------------------------------------------------- |
2020-08-17 14:45:24 +00:00
| `queries` | An array with one or more vectors. ~~numpy.ndarray~~ |
| _keyword-only_ | |
| `batch_size` | The batch size to use. Default to `1024`. ~~int~~ |
| `n` | The number of entries to return for each query. Defaults to `1`. ~~int~~ |
| `sort` | Whether to sort the entries returned by score. Defaults to `True`. ~~bool~~ |
| **RETURNS** | tuple | The most similar entries as a `(keys, best_rows, scores)` tuple. ~~Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray]~~ |
## Vectors.to_disk {#to_disk tag="method"}
Save the current state to a directory.
> #### Example
>
> ```python
> vectors.to_disk("/path/to/vectors")
>
> ```
2020-08-17 14:45:24 +00:00
| Name | Description |
| ------ | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `path` | A path to a directory, which will be created if it doesn't exist. Paths may be either strings or `Path`-like objects. ~~Union[str, Path]~~ |
## Vectors.from_disk {#from_disk tag="method"}
Loads state from a directory. Modifies the object in place and returns it.
> #### Example
>
> ```python
> vectors = Vectors(StringStore())
> vectors.from_disk("/path/to/vectors")
> ```
2020-08-17 14:45:24 +00:00
| Name | Description |
| ----------- | ----------------------------------------------------------------------------------------------- |
| `path` | A path to a directory. Paths may be either strings or `Path`-like objects. ~~Union[str, Path]~~ |
| **RETURNS** | The modified `Vectors` object. ~~Vectors~~ |
## Vectors.to_bytes {#to_bytes tag="method"}
Serialize the current state to a binary string.
> #### Example
>
> ```python
> vectors_bytes = vectors.to_bytes()
> ```
2020-08-17 14:45:24 +00:00
| Name | Description |
| ----------- | ------------------------------------------------------ |
| **RETURNS** | The serialized form of the `Vectors` object. ~~bytes~~ |
## Vectors.from_bytes {#from_bytes tag="method"}
Load state from a binary string.
> #### Example
>
> ```python
> fron spacy.vectors import Vectors
> vectors_bytes = vectors.to_bytes()
> new_vectors = Vectors(StringStore())
> new_vectors.from_bytes(vectors_bytes)
> ```
2020-08-17 14:45:24 +00:00
| Name | Description |
| ----------- | --------------------------------- |
| `data` | The data to load from. ~~bytes~~ |
| **RETURNS** | The `Vectors` object. ~~Vectors~~ |
## Attributes {#attributes}
2020-08-17 14:45:24 +00:00
| Name | Description |
| --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `data` | Stored vectors data. `numpy` is used for CPU vectors, `cupy` for GPU vectors. ~~Union[numpy.ndarray[ndim=1, dtype=float32], cupy.ndarray[ndim=1, dtype=float32]]~~ |
| `key2row` | Dictionary mapping word hashes to rows in the `Vectors.data` table. ~~Dict[int, int]~~ |
| `keys` | Array keeping the keys in order, such that `keys[vectors.key2row[key]] == key`. ~~Union[numpy.ndarray[ndim=1, dtype=float32], cupy.ndarray[ndim=1, dtype=float32]]~~ |