Other

Vectors

class
Store, save and load word vectors

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 – so vectors.n_keys may be greater or smaller than vectors.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 the HashEmbed 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__ method

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.

NameDescription
keyword-only
stringsThe string store. A new string store is created if one is not provided. Defaults to None. Optional[StringStore]
shapeSize 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]
dataThe vector data. numpy.ndarray[ndim=2, dtype=float32]
keysA sequence of keys aligned with the data. Iterable[Union[str, int]]
nameA name to identify the vectors table. str
mode v3.2Vectors mode: "default" or "floret" (default: "default"). str
minn v3.2The floret char ngram minn (default: 0). int
maxn v3.2The floret char ngram maxn (default: 0). int
hash_count v3.2The floret hash count. Supported values: 1—4 (default: 1). int
hash_seed v3.2The floret hash seed (default: 0). int
bow v3.2The floret BOW string (default: "<"). str
eow v3.2The floret EOW string (default: ">"). str
attr v3.6The token attribute for the vector keys (default: "ORTH"). Union[int, str]

Vectors.__getitem__ method

Get a vector by key. If the key is not found in the table, a KeyError is raised.

NameDescription
keyThe key to get the vector for. Union[int, str]

Vectors.__setitem__ method

Set a vector for the given key. Not supported for floret mode.

NameDescription
keyThe key to set the vector for. int
vectorThe vector to set. numpy.ndarray[ndim=1, dtype=float32]

Vectors.__iter__ method

Iterate over the keys in the table. In floret mode, the keys table is not used.

NameDescription

Vectors.__len__ method

Return the number of vectors in the table.

NameDescription

Vectors.__contains__ method

Check whether a key has been mapped to a vector entry in the table. In floret mode, returns True for all keys.

NameDescription
keyThe key to check. int

Vectors.add 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. Not supported for floret mode.

NameDescription
keyThe key to add. Union[str, int]
keyword-only
vectorAn optional vector to add for the key. numpy.ndarray[ndim=1, dtype=float32]
rowAn optional row number of a vector to map the key to. int

Vectors.resize 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. Not supported for floret mode.

NameDescription
shapeA (rows, dims) tuple describing the number of rows and dimensions. Tuple[int, int]
inplaceReallocate the memory. bool

Vectors.keys method

A sequence of the keys in the table. In floret mode, the keys table is not used.

NameDescription

Vectors.values 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. In floret mode, the keys table is not used.

NameDescription

Vectors.items method

Iterate over (key, vector) pairs, in order. In floret mode, the keys table is empty.

NameDescription

Vectors.find method

Look up one or more keys by row, or vice versa. Not supported for floret mode.

NameDescription
keyword-only
keyFind the row that the given key points to. Returns int, -1 if missing. Union[str, int]
keysFind rows that the keys point to. Returns numpy.ndarray. Iterable[Union[str, int]]
rowFind the first key that points to the row. Returns integer. int
rowsFind the keys that point to the rows. Returns numpy.ndarray. Iterable[int]

Vectors.shape property

Get (rows, dims) tuples of number of rows and number of dimensions in the vector table.

NameDescription

Vectors.size property

The vector size, i.e. rows * dims.

NameDescription

Vectors.is_full property

Whether the vectors table is full and 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.

NameDescription

Vectors.n_keys property

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.

NameDescription

Vectors.most_similar 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. Not supported for floret mode.

NameDescription
queriesAn array with one or more vectors. numpy.ndarray
keyword-only
batch_sizeThe batch size to use. Default to 1024. int
nThe number of entries to return for each query. Defaults to 1. int
sortWhether to sort the entries returned by score. Defaults to True. bool

Vectors.get_batch methodv3.2

Get the vectors for the provided keys efficiently as a batch.

NameDescription
keysThe keys. Iterable[Union[int, str]]

Vectors.to_ops method

Change the embedding matrix to use different Thinc ops.

NameDescription
opsThe Thinc ops to switch the embedding matrix to. Ops

Vectors.to_disk method

Save the current state to a directory.

NameDescription
pathA 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 method

Loads state from a directory. Modifies the object in place and returns it.

NameDescription
pathA path to a directory. Paths may be either strings or Path-like objects. Union[str,Path]

Vectors.to_bytes method

Serialize the current state to a binary string.

NameDescription

Vectors.from_bytes method

Load state from a binary string.

NameDescription
dataThe data to load from. bytes

Attributes

NameDescription
dataStored 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]]
key2rowDictionary mapping word hashes to rows in the Vectors.data table. Dict[int, int]
keysArray 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]]
attr v3.6The token attribute for the vector keys. int