* Use Vectors.shape rather than Vectors.data.shape * Use Vectors.size rather than Vectors.data.size * Add Vectors.to_ops to move data between different ops * Add documentation for Vector.to_ops
20 KiB
title | teaser | tag | source | new |
---|---|---|---|---|
Vectors | Store, save and load word vectors | class | spacy/vectors.pyx | 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).
As of spaCy v3.2, Vectors
supports two types of vector tables:
default
: A standard vector table (as in spaCy v3.1 and earlier) where each key is mapped to one row in the vector table. Multiple keys can be mapped to the same vector, and not all of the rows in the table need to be assigned – sovectors.n_keys
may be greater or smaller thanvectors.shape[0]
.floret
: Only supports vectors trained with floret, an extended version of fastText that produces compact vector tables by combining fastText's subword ngrams with Bloom embeddings. The compact tables are similar to theHashEmbed
embeddings already used in many spaCy components. Each word is represented as the sum of one or more rows as determined by the settings related to character ngrams and the hash table.
Vectors.__init__
Create a new vector store. With the default mode, 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. In floret mode, the complete
vector data and settings must be provided on initialization and cannot be
modified later.
Example
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)
Name | Description |
---|---|
keyword-only | |
strings |
The string store. A new string store is created if one is not provided. Defaults to None . |
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 . |
data |
The vector data. |
keys |
A sequence of keys aligned with the data. |
name |
A name to identify the vectors table. |
mode 3.2 |
Vectors mode: "default" or "floret" (default: "default" ). |
minn 3.2 |
The floret char ngram minn (default: 0 ). |
maxn 3.2 |
The floret char ngram maxn (default: 0 ). |
hash_count 3.2 |
The floret hash count. Supported values: 1--4 (default: 1 ). |
hash_seed 3.2 |
The floret hash seed (default: 0 ). |
bow 3.2 |
The floret BOW string (default: "<" ). |
eow 3.2 |
The floret EOW string (default: ">" ). |
Vectors.__getitem__
Get a vector by key. If the key is not found in the table, a KeyError
is
raised.
Example
cat_id = nlp.vocab.strings["cat"] cat_vector = nlp.vocab.vectors[cat_id] assert cat_vector == nlp.vocab["cat"].vector
Name | Description |
---|---|
key |
The key to get the vector for. |
RETURNS | The vector for the key. |
Vectors.__setitem__
Set a vector for the given key. Not supported for floret
mode.
Example
cat_id = nlp.vocab.strings["cat"] vector = numpy.random.uniform(-1, 1, (300,)) nlp.vocab.vectors[cat_id] = vector
Name | Description |
---|---|
key |
The key to set the vector for. |
vector |
The vector to set. |
Vectors.__iter__
Iterate over the keys in the table. In floret
mode, the keys table is not
used.
Example
for key in nlp.vocab.vectors: print(key, nlp.vocab.strings[key])
Name | Description |
---|---|
YIELDS | A key in the table. |
Vectors.__len__
Return the number of vectors in the table.
Example
vectors = Vectors(shape=(3, 300)) assert len(vectors) == 3
Name | Description |
---|---|
RETURNS | The number of vectors in the table. |
Vectors.__contains__
Check whether a key has been mapped to a vector entry in the table. In floret
mode, returns True
for all keys.
Example
cat_id = nlp.vocab.strings["cat"] nlp.vocab.vectors.add(cat_id, numpy.random.uniform(-1, 1, (300,))) assert cat_id in vectors
Name | Description |
---|---|
key |
The key to check. |
RETURNS | Whether the key has a vector entry. |
Vectors.add
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. Not
supported for floret
mode.
Example
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)
Name | Description |
---|---|
key |
The key to add. |
keyword-only | |
vector |
An optional vector to add for the key. |
row |
An optional row number of a vector to map the key to. |
RETURNS | The row the vector was added to. |
Vectors.resize
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. Not supported
for floret
mode.
Example
removed = nlp.vocab.vectors.resize((10000, 300))
Name | Description |
---|---|
shape |
A (rows, dims) tuple describing the number of rows and dimensions. |
inplace |
Reallocate the memory. |
RETURNS | The removed items as a list of (key, row) tuples. |
Vectors.keys
A sequence of the keys in the table. In floret
mode, the keys table is not
used.
Example
for key in nlp.vocab.vectors.keys(): print(key, nlp.vocab.strings[key])
Name | Description |
---|---|
RETURNS | The keys. |
Vectors.values
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. In floret
mode, the keys table is not used.
Example
for vector in nlp.vocab.vectors.values(): print(vector)
Name | Description |
---|---|
YIELDS | A vector in the table. |
Vectors.items
Iterate over (key, vector)
pairs, in order. In floret
mode, the keys table
is empty.
Example
for key, vector in nlp.vocab.vectors.items(): print(key, nlp.vocab.strings[key], vector)
Name | Description |
---|---|
YIELDS | (key, vector) pairs, in order. |
Vectors.find
Look up one or more keys by row, or vice versa. Not supported for floret
mode.
Example
row = nlp.vocab.vectors.find(key="cat") rows = nlp.vocab.vectors.find(keys=["cat", "dog"]) key = nlp.vocab.vectors.find(row=256) keys = nlp.vocab.vectors.find(rows=[18, 256, 985])
Name | Description |
---|---|
keyword-only | |
key |
Find the row that the given key points to. Returns int, -1 if missing. |
keys |
Find rows that the keys point to. Returns numpy.ndarray . |
row |
Find the first key that points to the row. Returns integer. |
rows |
Find the keys that point to the rows. Returns numpy.ndarray . |
RETURNS | The requested key, keys, row or rows. |
Vectors.shape
Get (rows, dims)
tuples of number of rows and number of dimensions in the
vector table.
Example
vectors = Vectors(shape(1, 300)) vectors.add("cat", numpy.random.uniform(-1, 1, (300,))) rows, dims = vectors.shape assert rows == 1 assert dims == 300
Name | Description |
---|---|
RETURNS | A (rows, dims) pair. |
Vectors.size
The vector size, i.e. rows * dims
.
Example
vectors = Vectors(shape=(500, 300)) assert vectors.size == 150000
Name | Description |
---|---|
RETURNS | The vector size. |
Vectors.is_full
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
. In floret
mode, the table is always
full and cannot be resized.
Example
vectors = Vectors(shape=(1, 300)) vectors.add("cat", numpy.random.uniform(-1, 1, (300,))) assert vectors.is_full
Name | Description |
---|---|
RETURNS | Whether the vectors table is full. |
Vectors.n_keys
Get the number of keys in the table. Note that this is the number of all keys,
not just unique vectors. If several keys are mapped to the same vectors, they
will be counted individually. In floret
mode, the keys table is not used.
Example
vectors = Vectors(shape=(10, 300)) assert len(vectors) == 10 assert vectors.n_keys == 0
Name | Description |
---|---|
RETURNS | The number of all keys in the table. |
Vectors.most_similar
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. Not
supported for floret
mode.
Example
queries = numpy.asarray([numpy.random.uniform(-1, 1, (300,))]) most_similar = nlp.vocab.vectors.most_similar(queries, n=10)
Name | Description |
---|---|
queries |
An array with one or more vectors. |
keyword-only | |
batch_size |
The batch size to use. Default to 1024 . |
n |
The number of entries to return for each query. Defaults to 1 . |
sort |
Whether to sort the entries returned by score. Defaults to True . |
RETURNS | tuple |
Vectors.get_batch
Get the vectors for the provided keys efficiently as a batch.
Example
words = ["cat", "dog"] vectors = nlp.vocab.vectors.get_batch(words)
Name | Description |
---|---|
keys |
The keys. |
Vectors.to_ops
Change the embedding matrix to use different Thinc ops.
Example
from thinc.api import NumpyOps vectors.to_ops(NumpyOps())
Name | Description |
---|---|
ops |
The Thinc ops to switch the embedding matrix to. |
Vectors.to_disk
Save the current state to a directory.
Example
vectors.to_disk("/path/to/vectors")
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. |
Vectors.from_disk
Loads state from a directory. Modifies the object in place and returns it.
Example
vectors = Vectors(StringStore()) vectors.from_disk("/path/to/vectors")
Name | Description |
---|---|
path |
A path to a directory. Paths may be either strings or Path -like objects. |
RETURNS | The modified Vectors object. |
Vectors.to_bytes
Serialize the current state to a binary string.
Example
vectors_bytes = vectors.to_bytes()
Name | Description |
---|---|
RETURNS | The serialized form of the Vectors object. |
Vectors.from_bytes
Load state from a binary string.
Example
fron spacy.vectors import Vectors vectors_bytes = vectors.to_bytes() new_vectors = Vectors(StringStore()) new_vectors.from_bytes(vectors_bytes)
Name | Description |
---|---|
data |
The data to load from. |
RETURNS | The Vectors object. |
Attributes
Name | Description |
---|---|
data |
Stored vectors data. numpy is used for CPU vectors, cupy for GPU vectors. |
key2row |
Dictionary mapping word hashes to rows in the Vectors.data table. |
keys |
Array keeping the keys in order, such that keys[vectors.key2row[key]] == key . |