|
| 1 | +# (C) Copyright 2021 IBM Corp. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import numpy as np |
| 16 | +import faiss |
| 17 | + |
| 18 | + |
| 19 | +class FaissNearestNeighbors: |
| 20 | + |
| 21 | + def __init__(self, |
| 22 | + metric="mahalanobis", |
| 23 | + index_type="flatl2", n_cells=100, n_probes=10): |
| 24 | + """NearestNeighbors object utilizing the faiss library for speed |
| 25 | +
|
| 26 | + Implements the same API as sklearn but runs 5-10x faster. Utilizes the |
| 27 | + `faiss` library https://github.com/facebookresearch/faiss . Tested with |
| 28 | + version 1.7.0. If `faiss-gpu` is installed from pypi, GPU acceleration |
| 29 | + will be used if available. |
| 30 | +
|
| 31 | + Args: |
| 32 | + metric (str) : Distance metric for finding nearest neighbors |
| 33 | + (default: "mahalanobis") |
| 34 | + index_type (str) : Index type within faiss to use |
| 35 | + (supported: "flatl2" and "ivfflat") |
| 36 | + n_cells (int) : Number of voronoi cells (only used for "ivfflat", |
| 37 | + default: 100) |
| 38 | + n_probes (int) : Number of voronoi cells to search in |
| 39 | + (only used for "ivfflat", default: 10) |
| 40 | + Attributes (after running `fit`): |
| 41 | + index_ : the faiss index fit from the data. For details about |
| 42 | + faiss indices, see the faiss documentation at |
| 43 | + https://github.com/facebookresearch/faiss/wiki/Faiss-indexes . |
| 44 | + """ |
| 45 | + self.metric = metric |
| 46 | + self.n_cells = n_cells |
| 47 | + self.n_probes = n_probes |
| 48 | + self.index_type = index_type |
| 49 | + |
| 50 | + def fit(self, X): |
| 51 | + """Create faiss index and train with data. |
| 52 | +
|
| 53 | + Args: |
| 54 | + X (np.array): Array of N samples of shape (NxM) |
| 55 | +
|
| 56 | + Returns: |
| 57 | + self: Fitted object |
| 58 | + """ |
| 59 | + X = self._transform_covariates(X) |
| 60 | + if self.index_type == "flatl2": |
| 61 | + self.index_ = faiss.IndexFlatL2(X.shape[1]) |
| 62 | + self.index_.add(X) |
| 63 | + elif self.index_type == "ivfflat": |
| 64 | + quantizer = faiss.IndexFlatL2(X.shape[1]) |
| 65 | + n_cells = max(1, min(self.n_cells, X.shape[0]//200)) |
| 66 | + n_probes = min(self.n_probes, n_cells) |
| 67 | + self.index_ = faiss.IndexIVFFlat( |
| 68 | + quantizer, X.shape[1], n_cells) |
| 69 | + self.index_.train(X) |
| 70 | + self.index_.nprobe = n_probes |
| 71 | + self.index_.add(X) |
| 72 | + else: |
| 73 | + raise NotImplementedError( |
| 74 | + "Index type {} not implemented. Please select" |
| 75 | + "one of [\"flatl2\", \"ivfflat\"]".format(self.index_type)) |
| 76 | + return self |
| 77 | + |
| 78 | + def kneighbors(self, X, n_neighbors=1): |
| 79 | + """Find the k nearest neighbors of each sample in X |
| 80 | +
|
| 81 | + Args: |
| 82 | + X (np.array): Array of shape (N,M) of samples to search |
| 83 | + for neighbors of. M must be the same as the fit data. |
| 84 | + n_neighbors (int, optional): Number of neighbors to find. |
| 85 | + Defaults to 1. |
| 86 | +
|
| 87 | + Returns: |
| 88 | + (distances, indices): Two np.array objects of shape (N,n_neighbors) |
| 89 | + containing the distances and indices of the closest neighbors. |
| 90 | + """ |
| 91 | + X = self._transform_covariates(X) |
| 92 | + distances, indices = self.index_.search(X, n_neighbors) |
| 93 | + # faiss returns euclidean distance squared |
| 94 | + return np.sqrt(distances), indices |
| 95 | + |
| 96 | + def _transform_covariates(self, X): |
| 97 | + if self.metric == "mahalanobis": |
| 98 | + if not hasattr(self, "VI"): |
| 99 | + raise AttributeError("Set inverse covariance VI first.") |
| 100 | + X = np.dot(X, self.VI.T) |
| 101 | + return np.ascontiguousarray(X).astype("float32") |
| 102 | + |
| 103 | + def set_params(self, **parameters): |
| 104 | + for parameter, value in parameters.items(): |
| 105 | + if parameter == "metric_params": |
| 106 | + self.set_params(**value) |
| 107 | + else: |
| 108 | + self._setattr(parameter, value) |
| 109 | + return self |
| 110 | + |
| 111 | + def get_params(self, deep=True): |
| 112 | + # `deep` plays no role because there are no sublearners |
| 113 | + params_to_return = ["metric", "n_cells", "n_probes", "index_type"] |
| 114 | + return {i: self.__getattribute__(i) for i in params_to_return} |
| 115 | + |
| 116 | + def _setattr(self, parameter, value): |
| 117 | + # based on faiss docs https://github.com/facebookresearch/faiss/wiki/MetricType-and-distances |
| 118 | + if parameter == "VI": |
| 119 | + value = np.linalg.inv(value) |
| 120 | + chol = np.linalg.cholesky(value) |
| 121 | + cholvi = np.linalg.inv(chol) |
| 122 | + value = cholvi |
| 123 | + setattr(self, parameter, value) |
0 commit comments