Skip to content

Instantly share code, notes, and snippets.

@karolzak
Last active April 9, 2021 12:28
Show Gist options
  • Save karolzak/d2f8a3b0f3c26c3f9ab4643e22bae5b0 to your computer and use it in GitHub Desktop.
Save karolzak/d2f8a3b0f3c26c3f9ab4643e22bae5b0 to your computer and use it in GitHub Desktop.
Nearest Neighbors algo implementation with FAISS
import numpy as np
import faiss
class FaissNearestNeighbors:
def __init__(self, k=5):
self.index = None
self.y = None
self.k = k
def fit(self, x, y=None):
self.index = faiss.IndexFlatL2(x.shape[1])
self.index.add(x.astype(np.float32))
if y is not None:
self.y = y
def predict(self, x, k=None):
distances, indices = self.index.search(
x.astype(np.float32),
k=self.k if k is None else k
)
if self.y is not None:
labels = self.y[indices]
return (distances, indices, labels)
return (distances, indices)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment