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_vectorcontract:scikitplot.annoy.Index— the high-level, mixin-composed class (adds a validated bulkadd_itemspath).scikitplot.annoy._annoy.Index— the Cython class, which additionally acceptsdtype(embedding precision) andindex_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;
-1lets 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, likedtype.- allow_fallbackbool, optional
What happens when the binding that runs cannot honour
dtypeorindex_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);FalseraisesFallbackRefusedErrorwhenbuildis called.dtypeandindex_dtypespellings are validated by the binding that honours them; a value dropped by a fallback is reported verbatim.
- Parameters:
Notes
Developer note: Annoy’s
"angular"metric operates on internally normalised vectors, so for two vectors with cosine similaritycthe reported distance isd = sqrt(2 * (1 - c)). Cosine is recovered exactly asc = 1 - d**2 / 2— the correct inverse (a plain1 - d/2is not).- build(embeddings)[source]#
Build the index from an
(n_docs, dim)embedding matrix.- Parameters:
- embeddingsnumpy.ndarray
Row-major
float32matrix. Rows are not required to be unit-normalised; each backend normalises internally as needed for cosine similarity.
- Parameters:
embeddings (Any)
- Return type:
None
- dependency_modules: ClassVar[str | tuple[str, ...] | None] = ('scikitplot.annoy', 'scikitplot.annoy._annoy')#
- 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_fallbackisTrueandfallback_reasonis"option_unsupported".
- 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:
- classmethod is_installed()[source]#
Return whether
scikitplot.annoycan 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:
- classmethod load_error()[source]#
Return why no Annoy binding loads, or
Nonewhen one does.Notes
Developer. This imports the bindings, so it costs what using them costs;
capability_snapshotcalls 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_availableimports the backend’s packages (a native library);capability_snapshot(load=False)then asks only once the modules inprobe_modulesare already loaded (F-50).
- provenance()[source]#
Return
VectorIndexBackend.provenanceplus the binding.
- query(vector, k)[source]#
Return up to
k(row_index, cosine_score)pairs.Results are sorted by descending
cosine_scorein[-1, 1]with deterministic, index-ascending tie breaking. A zero-norm query returns an empty list (cosine is undefined). Non-finite queries raise.
- score_semantics: str = 'cosine_similarity'#
Meaning of the
scoreinqueryresults."cosine_similarity"– range[-1, 1], higher is better."bounded_inverse_distance"– range(0, 1], higher is better, but not a similarity: it is1 / (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.
TruesinceANNIndexArtifactlanded: 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 wasFalse– accurately.