NearestNeighbors#

class skfda.ml.clustering.NearestNeighbors(*, n_neighbors: int = 5, radius: float = 1.0, algorithm: Literal['auto', 'ball_tree', 'kd_tree', 'brute'] = 'auto', leaf_size: int = 30, metric: Literal['precomputed'], n_jobs: int | None = None)[source]#
class skfda.ml.clustering.NearestNeighbors(*, n_neighbors: int = 5, radius: float = 1.0, algorithm: Literal['auto', 'ball_tree', 'kd_tree', 'brute'] = 'auto', leaf_size: int = 30, metric: Metric[Input] = l2_distance, n_jobs: int | None = None)
class skfda.ml.clustering.NearestNeighbors(*, n_neighbors: int = 5, radius: float = 1.0, algorithm: Literal['auto', 'ball_tree', 'kd_tree', 'brute'] = 'auto', leaf_size: int = 30, metric: Metric[Input] = l2_distance, n_jobs: int | None = None)

Unsupervised learner for implementing neighbor searches.

Parameters:
  • n_neighbors (int) – Number of neighbors to use by default for kneighbors() queries.

  • radius (float) – Range of parameter space to use by default for radius_neighbors() queries.

  • algorithm (AlgorithmType) –

    Algorithm used to compute the nearest neighbors:

    • ’ball_tree’ will use sklearn.neighbors.BallTree.

    • ’brute’ will use a brute-force search.

    • ’auto’ will attempt to decide the most appropriate algorithm based on the values passed to fit() method.

  • leaf_size (int) – Leaf size passed to BallTree or KDTree. This can affect the speed of the construction and query, as well as the memory required to store the tree. The optimal value depends on the nature of the problem.

  • metric (Literal['precomputed'] | Metric[Input]) – The distance metric to use for the tree. The default metric is the L2 distance. See the documentation of the metrics module for a list of available metrics.

  • n_jobs (int | None) – The number of parallel jobs to run for neighbors search. None means 1 unless in a joblib.parallel_backend context. -1 means using all processors. Doesn’t affect fit() method.

Examples

Firstly, we will create a toy dataset

>>> from skfda.datasets import make_gaussian_process
>>> X = make_gaussian_process(
...    n_samples=30,
...    random_state=0,
... )

We will fit a Nearest Neighbors estimator

>>> from skfda.ml.clustering import NearestNeighbors
>>> neigh = NearestNeighbors(n_neighbors=3, radius=0.7)
>>> neigh.fit(X)
NearestNeighbors(...)

Now we can query the k-nearest neighbors.

>>> distances, index = neigh.kneighbors(X)
>>> index
array([[ 0, 8, 1], ...)
>>> distances.round(2)
array([[ 0.  ,  0.41,  0.58], ...])

We can query the neighbors in a given radius too.

>>> distances, index = neigh.radius_neighbors(X)
>>> index[0]
array([ 0,  1,  8, 18]...)
>>> distances[0].round(2)
array([ 0.  ,  0.58,  0.41,  0.68])

Notes

See Nearest Neighbors in the sklearn online documentation for a discussion of the choice of algorithm and leaf_size.

This class wraps the sklearn classifier sklearn.neighbors.KNeighborsClassifier.

https://en.wikipedia.org/wiki/K-nearest_neighbor_algorithm

Methods

fit(X[, y])

Fit the model using X as training data and y as target values.

get_metadata_routing()

Get metadata routing of this object.

get_params([deep])

Get parameters for this estimator.

kneighbors([X, n_neighbors, return_distance])

Find the K-neighbors of a point.

kneighbors_graph([X, n_neighbors, mode])

Compute the (weighted) graph of k-Neighbors for points in X.

radius_neighbors([X, radius, return_distance])

Find the neighbors within a given radius of a fdatagrid.

radius_neighbors_graph([X, radius, mode])

Compute the (weighted) graph of Neighbors for points in X.

set_params(**params)

Set the parameters of this estimator.

fit(X, y=None)[source]#

Fit the model using X as training data and y as target values.

Parameters:
  • X (Input) – Training data. FDataGrid with the training data or array matrix with shape [n_samples, n_samples] if metric=’precomputed’.

  • y (None) – Target values of shape = [n_samples] or [n_samples, n_outputs]. In the case of unsupervised search, this parameter is ignored.

  • self (SelfType) –

Returns:

Self.

Return type:

SelfType

Note

This method wraps the corresponding sklearn routine in the module sklearn.neighbors.

get_metadata_routing()#

Get metadata routing of this object.

Please check User Guide on how the routing mechanism works.

Returns:

routing – A MetadataRequest encapsulating routing information.

Return type:

MetadataRequest

get_params(deep=True)#

Get parameters for this estimator.

Parameters:

deep (bool, default=True) – If True, will return the parameters for this estimator and contained subobjects that are estimators.

Returns:

params – Parameter names mapped to their values.

Return type:

dict

kneighbors(X=None, n_neighbors=None, *, return_distance=True)[source]#

Find the K-neighbors of a point.

Returns indices of and distances to the neighbors of each point.

Parameters:
  • X (Input | None) – FDatagrid with the query functions or matrix (n_query, n_indexed) if metric == ‘precomputed’. If not provided, neighbors of each indexed point are returned. In this case, the query point is not considered its own neighbor.

  • n_neighbors (int | None) – Number of neighbors to get (default is the value passed to the constructor).

  • return_distance (bool) – Defaults to True. If False, distances will not be returned.

Returns:

array

Array representing the lengths to points, only present if return_distance=True

indarray

Indices of the nearest points in the population matrix.

Return type:

dist

Examples

Firstly, we will create a toy dataset

>>> from skfda.datasets import make_gaussian_process
>>> X = make_gaussian_process(
...    n_samples=30,
...    random_state=0,
... )

We will fit a Nearest Neighbors estimator

>>> from skfda.ml.clustering import NearestNeighbors
>>> neigh = NearestNeighbors(n_neighbors=3)
>>> neigh.fit(X)
NearestNeighbors(...)

Now we can query the k-nearest neighbors.

>>> distances, index = neigh.kneighbors(X)
>>> index
array([[ 0, 8, 1], ...)
>>> distances.round(2)
array([[ 0.  ,  0.41,  0.58], ...])

Notes

This method wraps the corresponding sklearn routine in the module sklearn.neighbors.

kneighbors_graph(X=None, n_neighbors=None, mode='connectivity')[source]#

Compute the (weighted) graph of k-Neighbors for points in X.

Parameters:
  • X (Input | None) – FDatagrid with the query functions or matrix (n_query, n_indexed) if metric == ‘precomputed’. If not provided, neighbors of each indexed point are returned. In this case, the query point is not considered its own neighbor.

  • n_neighbors (int | None) – Number of neighbors to get (default is the value passed to the constructor).

  • mode (Literal['connectivity', 'distance']) – Type of returned matrix: ‘connectivity’ will return the connectivity matrix with ones and zeros, in ‘distance’ the edges are distance between points.

Returns:

Sparse matrix in CSR format, shape = [n_samples, n_samples_fit] n_samples_fit is the number of samples in the fitted data A[i, j] is assigned the weight of edge that connects i to j.

Return type:

csr_matrix

Examples

Firstly, we will create a toy dataset

>>> from skfda.datasets import make_gaussian_process
>>> X = make_gaussian_process(
...    n_samples=30,
...    random_state=0,
... )

We will fit a Nearest Neighbors estimator.

>>> from skfda.ml.clustering import NearestNeighbors
>>> neigh = NearestNeighbors(n_neighbors=3)
>>> neigh.fit(X)
NearestNeighbors(...)

Now we can obtain the graph of k-neighbors of a sample.

>>> graph = neigh.kneighbors_graph(X[0])
>>> print(graph)
    (0, 0)    1.0
    (0, 8)    1.0
    (0, 1)    1.0

Notes

This method wraps the corresponding sklearn routine in the module sklearn.neighbors.

radius_neighbors(X=None, radius=None, *, return_distance=True)[source]#

Find the neighbors within a given radius of a fdatagrid.

Return the indices and distances of each point from the dataset lying in a ball with size radius around the points of the query array. Points lying on the boundary are included in the results. The result points are not necessarily sorted by distance to their query point.

Parameters:
  • X (Input | None) – Sample or samples whose neighbors will be returned. If not provided, neighbors of each indexed point are returned. In this case, the query point is not considered its own neighbor.

  • radius (float | None) – Limiting distance of neighbors to return. (default is the value passed to the constructor).

  • return_distance (bool) – Defaults to True. If False, distances will not be returned.

Returns:

distarray of arrays representing the

distances to each point, only present if return_distance=True. The distance values are computed according to the metric constructor parameter.

(array, shape (n_samples,): An array of arrays of indices of the

approximate nearest points from the population matrix that lie within a ball of size radius around the query points.

Return type:

(array, shape (n_samples)

Examples

Firstly, we will create a toy dataset

>>> from skfda.datasets import make_gaussian_process
>>> X = make_gaussian_process(
...    n_samples=30,
...    random_state=0,
... )

We will fit a Nearest Neighbors estimator.

>>> from skfda.ml.clustering import NearestNeighbors
>>> neigh = NearestNeighbors(radius=0.7)
>>> neigh.fit(X)
NearestNeighbors(...)

Now we can query the neighbors in a given radius.

>>> distances, index = neigh.radius_neighbors(X)
>>> index[0]
array([ 0,  1,  8, 18]...)
>>> distances[0].round(2)
array([ 0.  ,  0.58,  0.41,  0.68])

See also

kneighbors

Notes

Because the number of neighbors of each point is not necessarily equal, the results for multiple query points cannot be fit in a standard data array. For efficiency, radius_neighbors returns arrays of objects, where each object is a 1D array of indices or distances.

This method wraps the corresponding sklearn routine in the module sklearn.neighbors.

radius_neighbors_graph(X=None, radius=None, mode='connectivity')[source]#

Compute the (weighted) graph of Neighbors for points in X.

Neighborhoods are restricted the points at a distance lower than radius.

Parameters:
  • X (Input | None) – The query sample or samples. If not provided, neighbors of each indexed point are returned. In this case, the query point is not considered its own neighbor.

  • radius (float | None) – Radius of neighborhoods. (default is the value passed to the constructor).

  • mode (Literal['connectivity', 'distance']) – Type of returned matrix: ‘connectivity’ will return the connectivity matrix with ones and zeros, in ‘distance’ the edges are distance between points.

Returns:

sparse matrix in CSR format, shape = [n_samples, n_samples] A[i, j] is assigned the weight of edge that connects i to j.

Return type:

csr_matrix

Notes

This method wraps the corresponding sklearn routine in the module sklearn.neighbors.

set_params(**params)#

Set the parameters of this estimator.

The method works on simple estimators as well as on nested objects (such as Pipeline). The latter have parameters of the form <component>__<parameter> so that it’s possible to update each component of a nested object.

Parameters:

**params (dict) – Estimator parameters.

Returns:

self – Estimator instance.

Return type:

estimator instance