Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save cjnolet/b1e5cc7df9b5db727d263ccf2aaf0bdd to your computer and use it in GitHub Desktop.
Save cjnolet/b1e5cc7df9b5db727d263ccf2aaf0bdd to your computer and use it in GitHub Desktop.
Creating a Symmetrized K-Nearest Neighbors Graph on GPU with cuML

Brief Example of Building a KNN Graph from cuML's NearestNeighbors Output

Import cupy and cuML's NearestNeighbors estimator

import cupy
from cuml.neighbors import NearestNeighbors

Set up some variables and create some random data on GPU

k = 5
n_samples = 100
n_features = 100

X = cupy.random.random((n_samples, n_features))

Execute k-Nearest Neighbors to find neighborhoods

knn = NearestNeighbors(n_neighbors=k)
knn.fit(X)
distances, indices = knn.kneighbors(X)

Create symmetrized KNN graph from our output arrays

distances = distances.reshape(n_samples * k)
indices = indices.reshape(n_samples * k)

indptr = cupy.arange(0, (k*n_samples)+1, k)
knn_graph = cupy.sparse.csr_matrix((distances, indices, indptr), shape=(n_samples, n_samples)).get()
knn_graph_symmetrized = knn_graph.maximum(knn_graph.T)
@anirbankonar123
Copy link

7.7.0

@vdet
Copy link

vdet commented Nov 21, 2022

Hi,

Has the above issue been solved, I also encountered it with cupy 11.0.0.

All the best

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment