AnnoyBackend#

class scikitplot.corpus.AnnoyBackend(*, metric='angular', n_trees=10, search_k=-1, impl='auto', dtype=None, index_dtype=None, allow_fallback=True)[source]#

ANN backend over a scikit-plots Annoy Index (default backend).

Works with both shipped Annoy index classes, which expose the same add_item / build / get_nns_by_vector contract:

  • scikitplot.annoy.Index — the high-level, mixin-composed class (adds a validated bulk add_items path).

  • scikitplot.annoy._annoy.Index — the Cython class, which additionally accepts dtype (embedding precision) and index_dtype (id width).

Parameters:
metricstr, optional

Annoy distance metric. "angular" (default) yields cosine-like ranking; the angular distance is converted back to exact cosine similarity for the unified score contract.

n_treesint, optional

Number of trees built (accuracy/size trade-off).

search_kint, optional

Query-time node budget passed to Annoy; -1 lets Annoy choose.

implstr, optional

Which index class to use: "auto" (default: a binding that accepts every requested option, the high-level class first), "highlevel", or "cython".

dtypestr or None, optional

Embedding precision (e.g. "float32", "float64"). Accepted by the Cython class only; impl="auto" therefore picks it.

index_dtypestr or None, optional

Item-id integer width (e.g. "int32", "uint64") for very large corpora. Cython class only, like dtype.

allow_fallbackbool, optional

What happens when the binding that runs cannot honour dtype or index_dtype (impl="highlevel", or no accepting binding loads), or the preferred binding under "auto" cannot load: True (default) builds anyway and reports it (fallback_reason, discarded_options, one warning); False raises FallbackRefusedError when build is called. dtype and index_dtype spellings are validated by the binding that honours them; a value dropped by a fallback is reported verbatim.

Parameters:
  • metric (str)

  • n_trees (int)

  • search_k (int)

  • impl (str)

  • dtype (str)

  • index_dtype (str | None)

  • allow_fallback (bool)

Notes

Developer note: Annoy’s "angular" metric operates on internally normalised vectors, so for two vectors with cosine similarity c the reported distance is d = sqrt(2 * (1 - c)). Cosine is recovered exactly as c = 1 - d**2 / 2 — the correct inverse (a plain 1 - d/2 is not).

property allow_fallback: bool#

Whether a fallback was allowed (False raises instead).

build(embeddings)[source]#

Build the index from an (n_docs, dim) embedding matrix.

Parameters:
embeddingsnumpy.ndarray

Row-major float32 matrix. Rows are not required to be unit-normalised; each backend normalises internally as needed for cosine similarity.

Parameters:

embeddings (Any)

Return type:

None

capabilities()[source]#

Return every declared capability as a mapping.

Returns:
dict

Suitable for a capability report or a build manifest.

Return type:

dict[str, Any]

dependency_modules: ClassVar[str | tuple[str, ...] | None] = ('scikitplot.annoy', 'scikitplot.annoy._annoy')#
property dimension: int | None#

Vector length this index was built with, None before build.

property discarded_options: dict[str, Any]#

Options this backend requested and the binding that ran cannot honour.

Returns:
dict

Empty when everything requested was honoured. Non-empty only when allow_fallback is True and fallback_reason is "option_unsupported".

dtype: str = 'float32'#

Element type of the indexed vectors.

property fallback_reason: str | None#

Why what runs differs from what was requested, or None.

The selection reason ("<backend>_broken") first, then the binding’s ("option_unsupported", "<binding>_unavailable").

classmethod is_available()[source]#

Return whether this backend can be used now: installed and loading.

Return type:

bool

classmethod is_installed()[source]#

Return whether scikitplot.annoy can be found, importing nothing.

Notes

Developer. Only the package is looked up: finding a submodule (scikitplot.annoy._annoy) would import the package, whose mixins import scikit-learn and SciPy (F-50).

Return type:

bool

classmethod load_error()[source]#

Return why no Annoy binding loads, or None when one does.

Notes

Developer. This imports the bindings, so it costs what using them costs; capability_snapshot calls it only when asked to load (load=True) or once Annoy is already loaded.

Return type:

BaseException | None

loads_on_probe: ClassVar[bool] = True#

Whether answering is_available imports the backend’s packages (a native library); capability_snapshot(load=False) then asks only once the modules in probe_modules are already loaded (F-50).

memory_profile: str = 'in_memory'#

"in_memory", "mmap" or "hybrid".

metric: str = 'cosine'#

Distance/similarity metric this backend computes.

name: ClassVar[str] = 'annoy'#
probe_modules: ClassVar[tuple[str, ...]] = ('scikitplot.annoy',)#
provenance()[source]#

Return VectorIndexBackend.provenance plus the binding.

Returns:
dict

Adds requested_impl, impl (None before build) and discarded_options.

Return type:

dict[str, Any]

query(vector, k)[source]#

Return up to k (row_index, cosine_score) pairs.

Results are sorted by descending cosine_score in [-1, 1] with deterministic, index-ascending tie breaking. A zero-norm query returns an empty list (cosine is undefined). Non-finite queries raise.

Parameters:
Return type:

list[tuple[int, float]]

property requested_backend: str#

"auto", a name or a class.

Type:

What the configuration asked for

score_semantics: str = 'cosine_similarity'#

Meaning of the score in query results.

"cosine_similarity" – range [-1, 1], higher is better. "bounded_inverse_distance" – range (0, 1], higher is better, but not a similarity: it is 1 / (1 + d) and is not comparable with a cosine score. Declaring this is what lets a threshold be validated against the scale it will actually be applied to (finding F-R06-02).

supports_persistence: bool = True#

Whether this backend’s index can be persisted and reloaded.

True since ANNIndexArtifact landed: an artifact writes the native payload alongside a versioned ordinal->doc_id sidecar and the embedding manifest, so a reloaded index can prove its rows still name the documents they named at write time. Before that, R06 found zero persistence surface in this module and the declaration was False – accurately.

thread_safety: str = 'concurrent_read'#

"single_thread", "concurrent_read" or "full".