oodeel 0.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. oodeel/__init__.py +28 -0
  2. oodeel/aggregator/__init__.py +26 -0
  3. oodeel/aggregator/base.py +70 -0
  4. oodeel/aggregator/fisher.py +259 -0
  5. oodeel/aggregator/mean.py +72 -0
  6. oodeel/aggregator/std.py +86 -0
  7. oodeel/datasets/__init__.py +24 -0
  8. oodeel/datasets/data_handler.py +334 -0
  9. oodeel/datasets/deprecated/DEPRECATED_data_handler.py +236 -0
  10. oodeel/datasets/deprecated/DEPRECATED_ooddataset.py +330 -0
  11. oodeel/datasets/deprecated/DEPRECATED_tf_data_handler.py +671 -0
  12. oodeel/datasets/deprecated/DEPRECATED_torch_data_handler.py +769 -0
  13. oodeel/datasets/deprecated/__init__.py +31 -0
  14. oodeel/datasets/tf_data_handler.py +600 -0
  15. oodeel/datasets/torch_data_handler.py +672 -0
  16. oodeel/eval/__init__.py +22 -0
  17. oodeel/eval/metrics.py +218 -0
  18. oodeel/eval/plots/__init__.py +27 -0
  19. oodeel/eval/plots/features.py +345 -0
  20. oodeel/eval/plots/metrics.py +118 -0
  21. oodeel/eval/plots/plotly.py +162 -0
  22. oodeel/extractor/__init__.py +35 -0
  23. oodeel/extractor/feature_extractor.py +187 -0
  24. oodeel/extractor/hf_torch_feature_extractor.py +184 -0
  25. oodeel/extractor/keras_feature_extractor.py +409 -0
  26. oodeel/extractor/torch_feature_extractor.py +506 -0
  27. oodeel/methods/__init__.py +47 -0
  28. oodeel/methods/base.py +570 -0
  29. oodeel/methods/dknn.py +185 -0
  30. oodeel/methods/energy.py +119 -0
  31. oodeel/methods/entropy.py +113 -0
  32. oodeel/methods/gen.py +113 -0
  33. oodeel/methods/gram.py +274 -0
  34. oodeel/methods/mahalanobis.py +209 -0
  35. oodeel/methods/mls.py +113 -0
  36. oodeel/methods/odin.py +109 -0
  37. oodeel/methods/rmds.py +172 -0
  38. oodeel/methods/she.py +159 -0
  39. oodeel/methods/vim.py +273 -0
  40. oodeel/preprocess/__init__.py +31 -0
  41. oodeel/preprocess/tf_preprocess.py +95 -0
  42. oodeel/preprocess/torch_preprocess.py +97 -0
  43. oodeel/types/__init__.py +75 -0
  44. oodeel/utils/__init__.py +38 -0
  45. oodeel/utils/general_utils.py +97 -0
  46. oodeel/utils/operator.py +253 -0
  47. oodeel/utils/tf_operator.py +269 -0
  48. oodeel/utils/tf_training_tools.py +219 -0
  49. oodeel/utils/torch_operator.py +292 -0
  50. oodeel/utils/torch_training_tools.py +303 -0
  51. oodeel-0.4.0.dist-info/METADATA +409 -0
  52. oodeel-0.4.0.dist-info/RECORD +63 -0
  53. oodeel-0.4.0.dist-info/WHEEL +5 -0
  54. oodeel-0.4.0.dist-info/licenses/LICENSE +21 -0
  55. oodeel-0.4.0.dist-info/top_level.txt +2 -0
  56. tests/__init__.py +22 -0
  57. tests/tests_tensorflow/__init__.py +37 -0
  58. tests/tests_tensorflow/tf_methods_utils.py +140 -0
  59. tests/tests_tensorflow/tools_tf.py +86 -0
  60. tests/tests_torch/__init__.py +38 -0
  61. tests/tests_torch/tools_torch.py +151 -0
  62. tests/tests_torch/torch_methods_utils.py +148 -0
  63. tests/tools_operator.py +153 -0
oodeel/methods/dknn.py ADDED
@@ -0,0 +1,185 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright IRT Antoine de Saint Exupéry et Université Paul Sabatier Toulouse III - All
3
+ # rights reserved. DEEL is a research program operated by IVADO, IRT Saint Exupéry,
4
+ # CRIAQ and ANITI - https://www.deel.ai/
5
+ #
6
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ # of this software and associated documentation files (the "Software"), to deal
8
+ # in the Software without restriction, including without limitation the rights
9
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ # copies of the Software, and to permit persons to whom the Software is
11
+ # furnished to do so, subject to the following conditions:
12
+ #
13
+ # The above copyright notice and this permission notice shall be included in all
14
+ # copies or substantial portions of the Software.
15
+ #
16
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ # SOFTWARE.
23
+ import faiss
24
+ import numpy as np
25
+
26
+ from ..aggregator import BaseAggregator
27
+ from ..types import TensorType
28
+ from .base import FeatureBasedDetector
29
+
30
+
31
+ class DKNN(FeatureBasedDetector):
32
+ """
33
+ "Out-of-Distribution Detection with Deep Nearest Neighbors"
34
+ https://arxiv.org/abs/2204.06507
35
+
36
+ Args:
37
+ nearest: number of nearest neighbors to consider.
38
+ Defaults to 50.
39
+ use_gpu (bool): Whether to enable GPU acceleration for FAISS. Defaults to False.
40
+ aggregator (Optional[BaseAggregator]): Aggregator to combine scores from
41
+ multiple feature layers. If not provided and multiple layers are used, a
42
+ StdNormalizedAggregator will be employed.
43
+ **kwargs: Additional keyword arguments for the base class.
44
+ """
45
+
46
+ def __init__(
47
+ self,
48
+ nearest: int = 50,
49
+ use_gpu: bool = False,
50
+ aggregator: BaseAggregator = None,
51
+ **kwargs,
52
+ ):
53
+ super().__init__(aggregator=aggregator, **kwargs)
54
+ self.nearest = nearest
55
+ self.use_gpu = use_gpu
56
+ self.indexes: list[faiss.IndexFlatL2] = []
57
+
58
+ if self.use_gpu:
59
+ try:
60
+ self.res = faiss.StandardGpuResources()
61
+ except AttributeError as e:
62
+ raise ImportError(
63
+ "faiss-gpu is not installed, but use_gpu was set to True."
64
+ + "Please install faiss-gpu or set use_gpu to False."
65
+ ) from e
66
+
67
+ # === Per-layer logic ===
68
+ def _fit_layer(
69
+ self,
70
+ layer_id: int,
71
+ layer_features: np.ndarray,
72
+ info: dict,
73
+ **kwargs,
74
+ ) -> None:
75
+ """Fit one FAISS index for a single layer.
76
+
77
+ The extracted features are L2-normalized and stored into a FAISS index
78
+ dedicated to the current layer. Aggregator scores, if needed, are
79
+ computed separately via :func:`_score_layer` with `fit=True`.
80
+
81
+ Args:
82
+ layer_id: Index of the processed layer.
83
+ layer_features: Feature tensor corresponding to that layer.
84
+ info: Dictionary of auxiliary data (unused).
85
+ """
86
+ norm_features = self._prepare_layer_features(layer_features)
87
+ index = self._create_index(norm_features.shape[1])
88
+ index.add(norm_features)
89
+
90
+ self.indexes.append(index)
91
+
92
+ def _score_layer(
93
+ self,
94
+ layer_id: int,
95
+ layer_features: TensorType,
96
+ info: dict,
97
+ fit: bool = False,
98
+ **kwargs,
99
+ ) -> np.ndarray:
100
+ """Compute KNN scores for a single feature layer.
101
+
102
+ Args:
103
+ layer_id: Index of the processed layer.
104
+ layer_features: Feature tensor associated with this layer.
105
+ info: Dictionary of auxiliary data (unused).
106
+ fit: If `True`, scoring is performed as part of the fitting routine (for
107
+ the aggregator) and uses `max(nearest, 2)` neighbours. This avoids the
108
+ trivial zero distance obtained when `nearest` equals one. In inference
109
+ mode (`fit=False`), `nearest` neighbours are used.
110
+
111
+ Returns:
112
+ np.ndarray: Distance to the :math:`k`-th nearest neighbour.
113
+ """
114
+ index = self.indexes[layer_id]
115
+ layer_features = self.op.convert_to_numpy(layer_features)
116
+ norm_features = self._prepare_layer_features(layer_features)
117
+ k = max(self.nearest, 2) if fit else self.nearest
118
+ scores, _ = index.search(norm_features, k)
119
+ return scores[:, -1]
120
+
121
+ # === Internal utilities ===
122
+ def _prepare_layer_features(self, features: np.ndarray) -> np.ndarray:
123
+ """
124
+ Convert a feature tensor to a 2D numpy array and apply L2 normalization.
125
+
126
+ Args:
127
+ features (np.ndarray): Feature tensor to be processed.
128
+
129
+ Returns:
130
+ np.ndarray: Processed feature array with shape (num_samples, feature_dim)
131
+ and L2 normalized.
132
+ """
133
+ features = features.reshape(features.shape[0], -1)
134
+ return self._l2_normalization(features)
135
+
136
+ def _create_index(self, dim: int) -> faiss.IndexFlatL2:
137
+ """
138
+ Create a FAISS index for features of a given dimensionality.
139
+
140
+ Args:
141
+ dim (int): Dimensionality of the feature vectors.
142
+
143
+ Returns:
144
+ faiss.IndexFlatL2: A FAISS index instance, using GPU acceleration if
145
+ enabled.
146
+ """
147
+ if self.use_gpu:
148
+ cpu_index = faiss.IndexFlatL2(dim)
149
+ return faiss.index_cpu_to_gpu(self.res, 0, cpu_index)
150
+ else:
151
+ return faiss.IndexFlatL2(dim)
152
+
153
+ def _l2_normalization(self, feat: np.ndarray) -> np.ndarray:
154
+ """
155
+ Apply L2 normalization to an array of feature vectors along the last dimension.
156
+
157
+ Args:
158
+ feat (np.ndarray): Input array of features.
159
+
160
+ Returns:
161
+ np.ndarray: L2-normalized feature array.
162
+ """
163
+ return feat / (np.linalg.norm(feat, ord=2, axis=-1, keepdims=True) + 1e-10)
164
+
165
+ # === Properties ===
166
+ @property
167
+ def requires_to_fit_dataset(self) -> bool:
168
+ """
169
+ Whether an OOD detector needs a `fit_dataset` argument in the fit function.
170
+
171
+ Returns:
172
+ bool: True if `fit_dataset` is required else False.
173
+ """
174
+ return True
175
+
176
+ @property
177
+ def requires_internal_features(self) -> bool:
178
+ """
179
+ Whether an OOD detector acts on internal model features.
180
+
181
+ Returns:
182
+ bool: True if the detector perform computations on an intermediate layer
183
+ else False.
184
+ """
185
+ return True
@@ -0,0 +1,119 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright IRT Antoine de Saint Exupéry et Université Paul Sabatier Toulouse III - All
3
+ # rights reserved. DEEL is a research program operated by IVADO, IRT Saint Exupéry,
4
+ # CRIAQ and ANITI - https://www.deel.ai/
5
+ #
6
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ # of this software and associated documentation files (the "Software"), to deal
8
+ # in the Software without restriction, including without limitation the rights
9
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ # copies of the Software, and to permit persons to whom the Software is
11
+ # furnished to do so, subject to the following conditions:
12
+ #
13
+ # The above copyright notice and this permission notice shall be included in all
14
+ # copies or substantial portions of the Software.
15
+ #
16
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ # SOFTWARE.
23
+ import numpy as np
24
+ from scipy.special import logsumexp
25
+
26
+ from ..types import TensorType
27
+ from ..types import Tuple
28
+ from .base import OODBaseDetector
29
+
30
+
31
+ class Energy(OODBaseDetector):
32
+ r"""
33
+ Energy Score method for OOD detection.
34
+ "Energy-based Out-of-distribution Detection"
35
+ https://arxiv.org/abs/2010.03759
36
+
37
+ This method assumes that the model has been trained with cross entropy loss
38
+ $CE(model(x))$ where $model(x)=(l_{c})_{c=1}^{C}$ are the logits
39
+ predicted for input $x$.
40
+ The implementation assumes that the logits are retreieved using the output with
41
+ linear activation.
42
+
43
+ The energy score for input $x$ is given by
44
+ $$ -\log \sum_{c=0}^C \exp(l_c)$$
45
+
46
+ where $model(x)=(l_{c})_{c=1}^{C}$ are the logits predicted by the model on
47
+ $x$.
48
+ As always, training data is expected to have lower score than OOD data.
49
+
50
+ Args:
51
+ use_react (bool): if true, apply ReAct method by clipping penultimate
52
+ activations under a threshold value.
53
+ react_quantile (Optional[float]): q value in the range [0, 1] used to compute
54
+ the react clipping threshold defined as the q-th quantile penultimate layer
55
+ activations. Defaults to 0.8.
56
+ """
57
+
58
+ def __init__(
59
+ self,
60
+ use_react: bool = False,
61
+ use_scale: bool = False,
62
+ use_ash: bool = False,
63
+ react_quantile: float = 0.8,
64
+ scale_percentile: float = 0.85,
65
+ ash_percentile: float = 0.90,
66
+ **kwargs,
67
+ ):
68
+ super().__init__(
69
+ use_react=use_react,
70
+ use_scale=use_scale,
71
+ use_ash=use_ash,
72
+ react_quantile=react_quantile,
73
+ scale_percentile=scale_percentile,
74
+ ash_percentile=ash_percentile,
75
+ **kwargs,
76
+ )
77
+
78
+ def _score_tensor(self, inputs: TensorType) -> Tuple[np.ndarray]:
79
+ """
80
+ Computes an OOD score for input samples "inputs" based on
81
+ energy, namey $-logsumexp(logits(inputs))$.
82
+
83
+ Args:
84
+ inputs: input samples to score
85
+
86
+ Returns:
87
+ Tuple[np.ndarray]: scores, logits
88
+ """
89
+ # optional: apply input perturbation
90
+ if self.eps > 0:
91
+ inputs = self._input_perturbation(inputs, self.eps, self.temperature)
92
+
93
+ # compute logits (softmax(logits,axis=1) is the actual softmax
94
+ # output minimized using binary cross entropy)
95
+ _, logits = self.feature_extractor.predict_tensor(inputs)
96
+ logits = self.op.convert_to_numpy(logits)
97
+ scores = -logsumexp(logits, axis=1)
98
+ return scores
99
+
100
+ @property
101
+ def requires_to_fit_dataset(self) -> bool:
102
+ """
103
+ Whether an OOD detector needs a `fit_dataset` argument in the fit function.
104
+
105
+ Returns:
106
+ bool: True if `fit_dataset` is required else False.
107
+ """
108
+ return False
109
+
110
+ @property
111
+ def requires_internal_features(self) -> bool:
112
+ """
113
+ Whether an OOD detector acts on internal model features.
114
+
115
+ Returns:
116
+ bool: True if the detector perform computations on an intermediate layer
117
+ else False.
118
+ """
119
+ return False
@@ -0,0 +1,113 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright IRT Antoine de Saint Exupéry et Université Paul Sabatier Toulouse III - All
3
+ # rights reserved. DEEL is a research program operated by IVADO, IRT Saint Exupéry,
4
+ # CRIAQ and ANITI - https://www.deel.ai/
5
+ #
6
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ # of this software and associated documentation files (the "Software"), to deal
8
+ # in the Software without restriction, including without limitation the rights
9
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ # copies of the Software, and to permit persons to whom the Software is
11
+ # furnished to do so, subject to the following conditions:
12
+ #
13
+ # The above copyright notice and this permission notice shall be included in all
14
+ # copies or substantial portions of the Software.
15
+ #
16
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ # SOFTWARE.
23
+ import numpy as np
24
+
25
+ from ..types import TensorType
26
+ from ..types import Tuple
27
+ from .base import OODBaseDetector
28
+
29
+
30
+ class Entropy(OODBaseDetector):
31
+ r"""
32
+ Entropy OOD score
33
+
34
+
35
+ The method consists in using the Entropy of the input data computed using the
36
+ Entropy $\sum_{c=0}^C p(y=c| x) \times log(p(y=c | x))$ where
37
+ $p(y=c| x) = \text{model}(x)$.
38
+
39
+ **Reference**
40
+ https://proceedings.neurips.cc/paper/2019/hash/1e79596878b2320cac26dd792a6c51c9-Abstract.html,
41
+ Neurips 2019.
42
+
43
+ Args:
44
+ use_react (bool): if true, apply ReAct method by clipping penultimate
45
+ activations under a threshold value.
46
+ react_quantile (Optional[float]): q value in the range [0, 1] used to compute
47
+ the react clipping threshold defined as the q-th quantile penultimate layer
48
+ activations. Defaults to 0.8.
49
+ """
50
+
51
+ def __init__(
52
+ self,
53
+ use_react: bool = False,
54
+ use_scale: bool = False,
55
+ use_ash: bool = False,
56
+ react_quantile: float = 0.8,
57
+ scale_percentile: float = 0.85,
58
+ ash_percentile: float = 0.90,
59
+ **kwargs,
60
+ ):
61
+ super().__init__(
62
+ use_react=use_react,
63
+ use_scale=use_scale,
64
+ use_ash=use_ash,
65
+ react_quantile=react_quantile,
66
+ scale_percentile=scale_percentile,
67
+ ash_percentile=ash_percentile,
68
+ **kwargs,
69
+ )
70
+
71
+ def _score_tensor(self, inputs: TensorType) -> Tuple[np.ndarray]:
72
+ """
73
+ Computes an OOD score for input samples "inputs" based on
74
+ entropy.
75
+
76
+ Args:
77
+ inputs: input samples to score
78
+
79
+ Returns:
80
+ Tuple[np.ndarray]: scores, logits
81
+ """
82
+ # optional: apply input perturbation
83
+ if self.eps > 0:
84
+ inputs = self._input_perturbation(inputs, self.eps, self.temperature)
85
+
86
+ # compute logits (softmax(logits,axis=1) is the actual softmax
87
+ # output minimized using binary cross entropy)
88
+ _, logits = self.feature_extractor.predict_tensor(inputs)
89
+ probits = self.op.softmax(logits)
90
+ probits = self.op.convert_to_numpy(probits)
91
+ scores = np.sum(probits * np.log(probits), axis=1)
92
+ return -scores
93
+
94
+ @property
95
+ def requires_to_fit_dataset(self) -> bool:
96
+ """
97
+ Whether an OOD detector needs a `fit_dataset` argument in the fit function.
98
+
99
+ Returns:
100
+ bool: True if `fit_dataset` is required else False.
101
+ """
102
+ return False
103
+
104
+ @property
105
+ def requires_internal_features(self) -> bool:
106
+ """
107
+ Whether an OOD detector acts on internal model features.
108
+
109
+ Returns:
110
+ bool: True if the detector perform computations on an intermediate layer
111
+ else False.
112
+ """
113
+ return False
oodeel/methods/gen.py ADDED
@@ -0,0 +1,113 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright IRT Antoine de Saint Exupéry et Université Paul Sabatier Toulouse III - All
3
+ # rights reserved. DEEL is a research program operated by IVADO, IRT Saint Exupéry,
4
+ # CRIAQ and ANITI - https://www.deel.ai/
5
+ #
6
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ # of this software and associated documentation files (the "Software"), to deal
8
+ # in the Software without restriction, including without limitation the rights
9
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ # copies of the Software, and to permit persons to whom the Software is
11
+ # furnished to do so, subject to the following conditions:
12
+ #
13
+ # The above copyright notice and this permission notice shall be included in all
14
+ # copies or substantial portions of the Software.
15
+ #
16
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ # SOFTWARE.
23
+ import numpy as np
24
+
25
+ from ..types import TensorType
26
+ from ..types import Tuple
27
+ from .base import OODBaseDetector
28
+
29
+
30
+ class GEN(OODBaseDetector):
31
+ """
32
+ Generalized Entropy method for OOD detection.
33
+ "GEN: Pushing the Limits of Softmax-Based Out-of-Distribution Detection"
34
+ https://openaccess.thecvf.com/content/CVPR2023/html/Liu_GEN_Pushing_the_Limits_of_Softmax-Based_Out-of-Distribution_Detection_CVPR_2023_paper.html,
35
+
36
+ Args:
37
+ gamma (float): parameter for the generalized entropy. Must be between 0 and 1.
38
+ Defaults to 0.1.
39
+ k (int): number of softmax values to keep for the entropy computation. Only the
40
+ top-k softmax probabilities will be used. Defaults to 100.
41
+ use_react (bool): if true, apply ReAct method by clipping penultimate
42
+ activations under a threshold value.
43
+ react_quantile (Optional[float]): q value in the range [0, 1] used to compute
44
+ the react clipping threshold defined as the q-th quantile penultimate layer
45
+ activations. Defaults to 0.8.
46
+ """
47
+
48
+ def __init__(
49
+ self,
50
+ gamma: float = 0.1,
51
+ k: int = 100,
52
+ use_react: bool = False,
53
+ use_scale: bool = False,
54
+ use_ash: bool = False,
55
+ react_quantile: float = 0.8,
56
+ scale_percentile: float = 0.85,
57
+ ash_percentile: float = 0.90,
58
+ **kwargs,
59
+ ):
60
+ super().__init__(
61
+ use_react=use_react,
62
+ use_scale=use_scale,
63
+ use_ash=use_ash,
64
+ react_quantile=react_quantile,
65
+ scale_percentile=scale_percentile,
66
+ ash_percentile=ash_percentile,
67
+ **kwargs,
68
+ )
69
+ self.gamma = gamma
70
+ self.k = k
71
+
72
+ def _score_tensor(self, inputs: TensorType) -> Tuple[np.ndarray]:
73
+ """
74
+ Computes an OOD score for input samples "inputs" based on
75
+ the distance to nearest neighbors in the feature space of self.model
76
+
77
+ Args:
78
+ inputs: input samples to score
79
+
80
+ Returns:
81
+ Tuple[np.ndarray]: scores, logits
82
+ """
83
+ # optional: apply input perturbation
84
+ if self.eps > 0:
85
+ inputs = self._input_perturbation(inputs, self.eps, self.temperature)
86
+
87
+ _, logits = self.feature_extractor.predict_tensor(inputs)
88
+ probs = self.op.softmax(logits)
89
+ probs = self.op.convert_to_numpy(probs)
90
+ probs = np.sort(probs)[:, -self.k :] # Keep the k largest probabilities
91
+ scores = np.sum(probs**self.gamma * (1 - probs) ** (self.gamma), axis=-1)
92
+ return scores
93
+
94
+ @property
95
+ def requires_to_fit_dataset(self) -> bool:
96
+ """
97
+ Whether an OOD detector needs a `fit_dataset` argument in the fit function.
98
+
99
+ Returns:
100
+ bool: True if `fit_dataset` is required else False.
101
+ """
102
+ return False
103
+
104
+ @property
105
+ def requires_internal_features(self) -> bool:
106
+ """
107
+ Whether an OOD detector acts on internal model features.
108
+
109
+ Returns:
110
+ bool: True if the detector perform computations on an intermediate layer
111
+ else False.
112
+ """
113
+ return False