|
| 1 | +# =============================================================================== |
| 2 | +# Copyright 2024 Intel Corporation |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | +# =============================================================================== |
| 16 | + |
| 17 | +import warnings |
| 18 | + |
| 19 | +import numpy as np |
| 20 | +from sklearn.neighbors import LocalOutlierFactor as sklearn_LocalOutlierFactor |
| 21 | +from sklearn.utils.metaestimators import available_if |
| 22 | +from sklearn.utils.validation import check_is_fitted |
| 23 | + |
| 24 | +from daal4py.sklearn._n_jobs_support import control_n_jobs |
| 25 | +from daal4py.sklearn._utils import sklearn_check_version |
| 26 | + |
| 27 | +from .._device_offload import dispatch, wrap_output_data |
| 28 | +from .common import KNeighborsDispatchingBase |
| 29 | +from .knn_unsupervised import NearestNeighbors |
| 30 | + |
| 31 | + |
| 32 | +@control_n_jobs(decorated_methods=["fit", "kneighbors"]) |
| 33 | +class LocalOutlierFactor(KNeighborsDispatchingBase, sklearn_LocalOutlierFactor): |
| 34 | + __doc__ = ( |
| 35 | + sklearn_LocalOutlierFactor.__doc__ |
| 36 | + + "\n NOTE: When X=None, methods kneighbors, kneighbors_graph, and predict will" |
| 37 | + + "\n only output numpy arrays. In that case, the only way to offload to gpu" |
| 38 | + + "\n is to use a global queue (e.g. using config_context)" |
| 39 | + ) |
| 40 | + if sklearn_check_version("1.2"): |
| 41 | + _parameter_constraints: dict = { |
| 42 | + **sklearn_LocalOutlierFactor._parameter_constraints |
| 43 | + } |
| 44 | + |
| 45 | + # Only certain methods should be taken from knn to prevent code |
| 46 | + # duplication. Inheriting would yield a complicated inheritance |
| 47 | + # structure and violate the sklearn inheritance path. |
| 48 | + _save_attributes = NearestNeighbors._save_attributes |
| 49 | + _onedal_knn_fit = NearestNeighbors._onedal_fit |
| 50 | + _onedal_kneighbors = NearestNeighbors._onedal_kneighbors |
| 51 | + |
| 52 | + def _onedal_fit(self, X, y, queue=None): |
| 53 | + if sklearn_check_version("1.2"): |
| 54 | + self._validate_params() |
| 55 | + |
| 56 | + self._onedal_knn_fit(X, y, queue) |
| 57 | + |
| 58 | + if self.contamination != "auto": |
| 59 | + if not (0.0 < self.contamination <= 0.5): |
| 60 | + raise ValueError( |
| 61 | + "contamination must be in (0, 0.5], " "got: %f" % self.contamination |
| 62 | + ) |
| 63 | + |
| 64 | + n_samples = self.n_samples_fit_ |
| 65 | + |
| 66 | + if self.n_neighbors > n_samples: |
| 67 | + warnings.warn( |
| 68 | + "n_neighbors (%s) is greater than the " |
| 69 | + "total number of samples (%s). n_neighbors " |
| 70 | + "will be set to (n_samples - 1) for estimation." |
| 71 | + % (self.n_neighbors, n_samples) |
| 72 | + ) |
| 73 | + self.n_neighbors_ = max(1, min(self.n_neighbors, n_samples - 1)) |
| 74 | + |
| 75 | + ( |
| 76 | + self._distances_fit_X_, |
| 77 | + _neighbors_indices_fit_X_, |
| 78 | + ) = self._onedal_kneighbors(n_neighbors=self.n_neighbors_, queue=queue) |
| 79 | + |
| 80 | + # Sklearn includes a check for float32 at this point which may not be |
| 81 | + # necessary for onedal |
| 82 | + |
| 83 | + self._lrd = self._local_reachability_density( |
| 84 | + self._distances_fit_X_, _neighbors_indices_fit_X_ |
| 85 | + ) |
| 86 | + |
| 87 | + # Compute lof score over training samples to define offset_: |
| 88 | + lrd_ratios_array = self._lrd[_neighbors_indices_fit_X_] / self._lrd[:, np.newaxis] |
| 89 | + |
| 90 | + self.negative_outlier_factor_ = -np.mean(lrd_ratios_array, axis=1) |
| 91 | + |
| 92 | + if self.contamination == "auto": |
| 93 | + # inliers score around -1 (the higher, the less abnormal). |
| 94 | + self.offset_ = -1.5 |
| 95 | + else: |
| 96 | + self.offset_ = np.percentile( |
| 97 | + self.negative_outlier_factor_, 100.0 * self.contamination |
| 98 | + ) |
| 99 | + |
| 100 | + return self |
| 101 | + |
| 102 | + def fit(self, X, y=None): |
| 103 | + self._fit_validation(X, y) |
| 104 | + result = dispatch( |
| 105 | + self, |
| 106 | + "fit", |
| 107 | + { |
| 108 | + "onedal": self.__class__._onedal_fit, |
| 109 | + "sklearn": sklearn_LocalOutlierFactor.fit, |
| 110 | + }, |
| 111 | + X, |
| 112 | + None, |
| 113 | + ) |
| 114 | + return result |
| 115 | + |
| 116 | + # Subtle order change to remove check_array and preserve dpnp and |
| 117 | + # dpctl conformance. decision_function will return a dpnp or dpctl |
| 118 | + # instance via kneighbors and an equivalent check_array exists in |
| 119 | + # that call already in sklearn so no loss of functionality occurs |
| 120 | + def _predict(self, X=None): |
| 121 | + check_is_fitted(self) |
| 122 | + |
| 123 | + if X is not None: |
| 124 | + output = self.decision_function(X) < 0 |
| 125 | + is_inlier = np.ones(output.shape[0], dtype=int) |
| 126 | + is_inlier[output] = -1 |
| 127 | + else: |
| 128 | + is_inlier = np.ones(self.n_samples_fit_, dtype=int) |
| 129 | + is_inlier[self.negative_outlier_factor_ < self.offset_] = -1 |
| 130 | + |
| 131 | + return is_inlier |
| 132 | + |
| 133 | + # This had to be done because predict loses the queue when no |
| 134 | + # argument is given and it is a dpctl tensor or dpnp array. |
| 135 | + # This would cause issues in fit_predict. Also, available_if |
| 136 | + # is hard to unwrap, and this is the most straighforward way. |
| 137 | + @available_if(sklearn_LocalOutlierFactor._check_novelty_fit_predict) |
| 138 | + @wrap_output_data |
| 139 | + def fit_predict(self, X, y=None): |
| 140 | + return self.fit(X)._predict() |
| 141 | + |
| 142 | + @available_if(sklearn_LocalOutlierFactor._check_novelty_predict) |
| 143 | + @wrap_output_data |
| 144 | + def predict(self, X=None): |
| 145 | + return self._predict(X) |
| 146 | + |
| 147 | + @wrap_output_data |
| 148 | + def kneighbors(self, X=None, n_neighbors=None, return_distance=True): |
| 149 | + check_is_fitted(self) |
| 150 | + if sklearn_check_version("1.0") and X is not None: |
| 151 | + self._check_feature_names(X, reset=False) |
| 152 | + return dispatch( |
| 153 | + self, |
| 154 | + "kneighbors", |
| 155 | + { |
| 156 | + "onedal": self.__class__._onedal_kneighbors, |
| 157 | + "sklearn": sklearn_LocalOutlierFactor.kneighbors, |
| 158 | + }, |
| 159 | + X, |
| 160 | + n_neighbors=n_neighbors, |
| 161 | + return_distance=return_distance, |
| 162 | + ) |
| 163 | + |
| 164 | + fit.__doc__ = sklearn_LocalOutlierFactor.fit.__doc__ |
| 165 | + fit_predict.__doc__ = sklearn_LocalOutlierFactor.fit_predict.__doc__ |
| 166 | + predict.__doc__ = sklearn_LocalOutlierFactor.predict.__doc__ |
| 167 | + kneighbors.__doc__ = sklearn_LocalOutlierFactor.kneighbors.__doc__ |
0 commit comments