Last active
April 9, 2021 12:28
-
-
Save karolzak/d2f8a3b0f3c26c3f9ab4643e22bae5b0 to your computer and use it in GitHub Desktop.
Nearest Neighbors algo implementation with FAISS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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