mojolearn.NearestNeighbors#
- class mojolearn.NearestNeighbors(n_neighbors=5, query_tile=0, *, metric='euclidean', algorithm='brute', p=2)[source]#
Bases:
NumericModeMixinExact k-nearest-neighbor search.
Every query is compared against every fitted point (
algorithm='brute', the default), or searched over an exact random ball cover index (algorithm='rbc'). Both return the exact neighbors; there is no approximate index and no recall to trade away. Input is converted to float32. Neighbors come back nearest first, with ties in distance broken by the lower index.- Parameters:
n_neighbors (int, default 5) – Number of neighbors returned by
kneighbors, scikit-learn’s default. Must be between 1 and the number of fitted samples; a larger value raisesValueError.query_tile (int, default 0) – Queries processed per pass. It changes memory use only, never the answer.
0lets the library choose, within its workspace limit and clamped to the query count; a positive value requests a fixed starting size.used_query_tile_reports the size that ran.metric (str, default ‘euclidean’) – Distance, by name. With
algorithm='brute'or'auto': ‘euclidean’/’l2’, ‘sqeuclidean’, ‘manhattan’/’l1’/’cityblock’/ ‘taxicab’, ‘chebyshev’/’linf’, ‘cosine’, ‘minkowski’/’lp’, ‘canberra’, ‘braycurtis’, ‘correlation’, ‘jensenshannon’ (needsX >= 0) and ‘inner_product’ (a similarity: larger is nearer, andkneighborsreturns the products themselves). Withalgorithm='rbc', only true metrics: ‘euclidean’/’l2’, ‘manhattan’/’l1’/’cityblock’/’taxicab’, ‘chebyshev’/’linf’ and ‘minkowski’/’lp’ withp >= 1. ‘haversine’, a callable and unknown names raiseValueError.algorithm ({‘brute’, ‘auto’, ‘rbc’}, default ‘brute’) – ‘brute’ and ‘auto’ (which means ‘brute’) compare every pair. ‘rbc’ searches an exact random ball cover, whose pruning rests on the triangle inequality, so it accepts only true metrics. ‘kd_tree’ and ‘ball_tree’ raise
ValueError.p (float, default 2) – Minkowski exponent, read only by
metric='minkowski'(or ‘lp’). It must be finite and positive (and at least 1 withalgorithm='rbc'). Under any other metric, a value other than 2 raisesValueErrorinstead of being ignored. Unlike scikit-learn,metric='minkowski', p=2runs the Minkowski computation rather than switching to Euclidean; the two agree to a few units in the last place.numeric_mode ({‘identical’, ‘deterministic’, ‘fast’}, optional) – Numeric mode for this estimator;
Noneuses the process default (mojolearn.set_numeric_mode). ‘fast’ is available on Apple GPUs only.
- Variables:
n_samples_fit_ (int) – Number of fitted samples.
n_features_in_ (int) – Number of features seen at
fit.used_query_tile_ (int or None) – Query batch size the last
kneighborscall ran with;Noneafter analgorithm='rbc'search.n_candidate_distances_ (int) – Set by an
algorithm='rbc'search: the number of distances the ball cover computed.
Examples
>>> import numpy as np, mojolearn >>> X = np.random.default_rng(0).random((1000, 8), dtype=np.float32) >>> nn = mojolearn.NearestNeighbors(n_neighbors=5).fit(X) >>> distances, indices = nn.kneighbors(X[:10])
Methods
fit(X[, y])Store the points to search.
get_params([deep])kneighbors(X[, n_neighbors, return_distance])Find the nearest fitted points to each query, nearest first.
load(path)Load a model written by
save.numeric_mode_used()The numeric mode this estimator runs in.
save(path)Save the fitted model to an
.npzfile.set_params(**params)Set constructor parameters.
vendor_used()The GPU backend this estimator runs on.
- save(path)[source]#
Save the fitted model to an
.npzfile.The file holds the float32 index as fitted and the parameters (
n_neighbors,query_tile,metric,p,algorithm, numeric mode). Equal models write identical files.mojolearn.host_model(path)can search the saved model on a CPU with no GPU (brute force, ‘euclidean’ and ‘sqeuclidean’).- Parameters:
path (str or path-like) – Destination file.
- Raises:
RuntimeError – If the model is not fitted.
- classmethod load(path)[source]#
Load a model written by
save.Arrays are read at their saved dtypes and never cast. A file naming a metric or algorithm this class refuses raises
ValueError, asfitwould.- Parameters:
path (str or path-like) – File written by
save.- Returns:
NearestNeighbors – A fitted model, ready for
kneighbors.
- fit(X, y=None)[source]#
Store the points to search.
Parameter checks run here, so an unsupported metric, algorithm or
praisesValueErrorbefore any search.- Parameters:
X (array-like of shape (n_samples, n_features)) – Points to search; converted to float32.
y (ignored) – Accepted for scikit-learn compatibility.
- Returns:
self
- kneighbors(X, n_neighbors=None, return_distance=True)[source]#
Find the nearest fitted points to each query, nearest first.
Distances are the chosen metric’s (‘euclidean’ returns true, not squared, distances). Ties in distance are broken by the lower index, matching scikit-learn’s layout and ordering.
On a GPU the fitted points are copied to the device at the first call after
fitand reused by later calls. Changing the array passed tofitin place after that is not seen; callfitagain instead (as with cuML, whosefitcopies the data to the device).- Parameters:
X (array-like of shape (n_queries, n_features)) – Query points; converted to float32.
n_neighbors (int, optional) – Neighbors per query; defaults to the constructor’s
n_neighbors. Must be between 1 andn_samples_fit_.return_distance (bool, default True) – Return the distances as well as the indices.
- Returns:
distances (Array of shape (n_queries, n_neighbors), float32) – Returned only when
return_distanceis True.indices (Array of shape (n_queries, n_neighbors), int64) – Row indices into the fitted data.
- Raises:
ValueError – If the model is not fitted,
Xhas the wrong number of features, orn_neighborsis out of range.