Fork me on GitHub

sklearn.neighbors.kneighbors_graph

sklearn.neighbors.kneighbors_graph(X, n_neighbors, mode='connectivity')

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

Parameters:

X : array-like or BallTree, shape = [n_samples, n_features]

Sample data, in the form of a numpy array or a precomputed BallTree.

n_neighbors : int

Number of neighbors for each sample.

mode : {‘connectivity’, ‘distance’}, optional

Type of returned matrix: ‘connectivity’ will return the connectivity matrix with ones and zeros, in ‘distance’ the edges are Euclidean distance between points.

Returns:

A : sparse matrix in CSR format, shape = [n_samples, n_samples]

A[i, j] is assigned the weight of edge that connects i to j.

Examples

>>> X = [[0], [3], [1]]
>>> from sklearn.neighbors import kneighbors_graph
>>> A = kneighbors_graph(X, 2)
>>> A.toarray()
array([[ 1.,  0.,  1.],
       [ 0.,  1.,  1.],
       [ 1.,  0.,  1.]])
Previous
Next