oodeel 0.1.1__py3-none-any.whl → 0.3.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.
Potentially problematic release.
This version of oodeel might be problematic. Click here for more details.
- oodeel/__init__.py +1 -1
- oodeel/datasets/__init__.py +2 -1
- oodeel/datasets/data_handler.py +162 -94
- oodeel/datasets/deprecated/DEPRECATED_data_handler.py +236 -0
- oodeel/datasets/{ooddataset.py → deprecated/DEPRECATED_ooddataset.py} +14 -13
- oodeel/datasets/deprecated/DEPRECATED_tf_data_handler.py +671 -0
- oodeel/datasets/deprecated/DEPRECATED_torch_data_handler.py +769 -0
- oodeel/datasets/deprecated/__init__.py +31 -0
- oodeel/datasets/tf_data_handler.py +105 -167
- oodeel/datasets/torch_data_handler.py +109 -181
- oodeel/eval/metrics.py +7 -2
- oodeel/eval/plots/features.py +2 -2
- oodeel/eval/plots/plotly.py +2 -2
- oodeel/extractor/feature_extractor.py +30 -9
- oodeel/extractor/keras_feature_extractor.py +70 -13
- oodeel/extractor/torch_feature_extractor.py +120 -33
- oodeel/methods/__init__.py +17 -1
- oodeel/methods/base.py +103 -17
- oodeel/methods/dknn.py +22 -9
- oodeel/methods/energy.py +8 -0
- oodeel/methods/entropy.py +8 -0
- oodeel/methods/gen.py +118 -0
- oodeel/methods/gram.py +307 -0
- oodeel/methods/mahalanobis.py +14 -12
- oodeel/methods/mls.py +8 -0
- oodeel/methods/odin.py +8 -0
- oodeel/methods/rmds.py +122 -0
- oodeel/methods/she.py +197 -0
- oodeel/methods/vim.py +5 -5
- oodeel/preprocess/__init__.py +31 -0
- oodeel/preprocess/tf_preprocess.py +95 -0
- oodeel/preprocess/torch_preprocess.py +97 -0
- oodeel/utils/operator.py +72 -2
- oodeel/utils/tf_operator.py +72 -4
- oodeel/utils/tf_training_tools.py +26 -3
- oodeel/utils/torch_operator.py +75 -4
- oodeel/utils/torch_training_tools.py +31 -2
- {oodeel-0.1.1.dist-info → oodeel-0.3.0.dist-info}/METADATA +141 -107
- oodeel-0.3.0.dist-info/RECORD +57 -0
- {oodeel-0.1.1.dist-info → oodeel-0.3.0.dist-info}/WHEEL +1 -1
- tests/tests_tensorflow/tf_methods_utils.py +2 -1
- tests/tests_torch/tools_torch.py +9 -9
- tests/tests_torch/torch_methods_utils.py +34 -27
- tests/tools_operator.py +10 -1
- oodeel-0.1.1.dist-info/RECORD +0 -46
- {oodeel-0.1.1.dist-info → oodeel-0.3.0.dist-info/licenses}/LICENSE +0 -0
- {oodeel-0.1.1.dist-info → oodeel-0.3.0.dist-info}/top_level.txt +0 -0
oodeel/methods/she.py
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
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 DatasetType
|
|
26
|
+
from ..types import TensorType
|
|
27
|
+
from ..types import Union
|
|
28
|
+
from .base import OODBaseDetector
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class SHE(OODBaseDetector):
|
|
32
|
+
"""
|
|
33
|
+
"Out-of-Distribution Detection based on In-Distribution Data Patterns Memorization
|
|
34
|
+
with Modern Hopfield Energy"
|
|
35
|
+
[link](https://openreview.net/forum?id=KkazG4lgKL)
|
|
36
|
+
|
|
37
|
+
This method first computes the mean of the internal layer representation of ID data
|
|
38
|
+
for each ID class. This mean is seen as the average of the ID activation patterns
|
|
39
|
+
as defined in the original paper.
|
|
40
|
+
The method then returns the maximum value of the dot product between the internal
|
|
41
|
+
layer representation of the input and the average patterns, which is a simplified
|
|
42
|
+
version of Hopfield energy as defined in the original paper.
|
|
43
|
+
|
|
44
|
+
Remarks:
|
|
45
|
+
* An input perturbation is applied in the same way as in Mahalanobis score
|
|
46
|
+
* The original paper only considers the penultimate layer of the neural
|
|
47
|
+
network, while we aggregate the results of multiple layers after normalizing by
|
|
48
|
+
the dimension of each vector (the activation vector for dense layers, and the
|
|
49
|
+
average pooling of the feature map for convolutional layers).
|
|
50
|
+
|
|
51
|
+
Args:
|
|
52
|
+
eps (float): magnitude for gradient based input perturbation.
|
|
53
|
+
Defaults to 0.0014.
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
def __init__(
|
|
57
|
+
self,
|
|
58
|
+
eps: float = 0.0014,
|
|
59
|
+
):
|
|
60
|
+
super().__init__()
|
|
61
|
+
self.eps = eps
|
|
62
|
+
self.postproc_fns = None
|
|
63
|
+
|
|
64
|
+
def _postproc_feature_maps(self, feature_map):
|
|
65
|
+
if len(feature_map.shape) > 2:
|
|
66
|
+
feature_map = self.op.avg_pool_2d(feature_map)
|
|
67
|
+
return self.op.flatten(feature_map)
|
|
68
|
+
|
|
69
|
+
def _fit_to_dataset(
|
|
70
|
+
self,
|
|
71
|
+
fit_dataset: Union[TensorType, DatasetType],
|
|
72
|
+
) -> None:
|
|
73
|
+
"""
|
|
74
|
+
Compute the means of the input dataset in the activation space of the selected
|
|
75
|
+
layers. The means are computed for each class in the dataset.
|
|
76
|
+
|
|
77
|
+
Args:
|
|
78
|
+
fit_dataset (Union[TensorType, DatasetType]): input dataset (ID) to
|
|
79
|
+
construct the index with.
|
|
80
|
+
ood_dataset (Union[TensorType, DatasetType]): OOD dataset to tune the
|
|
81
|
+
aggregation coefficients.
|
|
82
|
+
"""
|
|
83
|
+
self.postproc_fns = [
|
|
84
|
+
self._postproc_feature_maps
|
|
85
|
+
for i in range(len(self.feature_extractor.feature_layers_id))
|
|
86
|
+
]
|
|
87
|
+
|
|
88
|
+
features, infos = self.feature_extractor.predict(
|
|
89
|
+
fit_dataset, postproc_fns=self.postproc_fns
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
labels = infos["labels"]
|
|
93
|
+
preds = self.op.argmax(infos["logits"], dim=-1)
|
|
94
|
+
preds = self.op.convert_to_numpy(preds)
|
|
95
|
+
|
|
96
|
+
# unique sorted classes
|
|
97
|
+
self._classes = np.sort(np.unique(self.op.convert_to_numpy(labels)))
|
|
98
|
+
labels = self.op.convert_to_numpy(labels)
|
|
99
|
+
|
|
100
|
+
self._mus = list()
|
|
101
|
+
for feature in features:
|
|
102
|
+
mus_f = list()
|
|
103
|
+
for cls in self._classes:
|
|
104
|
+
indexes = np.equal(labels, cls) & np.equal(preds, cls)
|
|
105
|
+
_features_cls = feature[indexes]
|
|
106
|
+
mus_f.append(
|
|
107
|
+
self.op.unsqueeze(self.op.mean(_features_cls, dim=0), dim=0)
|
|
108
|
+
)
|
|
109
|
+
self._mus.append(self.op.permute(self.op.cat(mus_f), (1, 0)))
|
|
110
|
+
|
|
111
|
+
def _score_tensor(self, inputs: TensorType) -> np.ndarray:
|
|
112
|
+
"""
|
|
113
|
+
Computes an OOD score for input samples "inputs" based on
|
|
114
|
+
the aggregation of neural mean discrepancies from different layers.
|
|
115
|
+
|
|
116
|
+
Args:
|
|
117
|
+
inputs: input samples to score
|
|
118
|
+
|
|
119
|
+
Returns:
|
|
120
|
+
scores
|
|
121
|
+
"""
|
|
122
|
+
|
|
123
|
+
inputs_p = self._input_perturbation(inputs)
|
|
124
|
+
features, logits = self.feature_extractor.predict_tensor(
|
|
125
|
+
inputs_p, postproc_fns=self.postproc_fns
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
scores = self._get_she_output(features)
|
|
129
|
+
|
|
130
|
+
return -self.op.convert_to_numpy(scores)
|
|
131
|
+
|
|
132
|
+
def _get_she_output(self, features):
|
|
133
|
+
scores = None
|
|
134
|
+
for feature, mus_f in zip(features, self._mus):
|
|
135
|
+
she = self.op.matmul(self.op.squeeze(feature), mus_f) / feature.shape[1]
|
|
136
|
+
she = self.op.max(she, dim=1)
|
|
137
|
+
scores = she if scores is None else she + scores
|
|
138
|
+
return scores
|
|
139
|
+
|
|
140
|
+
def _input_perturbation(self, inputs: TensorType) -> TensorType:
|
|
141
|
+
"""
|
|
142
|
+
Apply small perturbation on inputs to make the in- and out- distribution
|
|
143
|
+
samples more separable.
|
|
144
|
+
|
|
145
|
+
Args:
|
|
146
|
+
inputs (TensorType): input samples
|
|
147
|
+
|
|
148
|
+
Returns:
|
|
149
|
+
TensorType: Perturbed inputs
|
|
150
|
+
"""
|
|
151
|
+
|
|
152
|
+
def __loss_fn(inputs: TensorType) -> TensorType:
|
|
153
|
+
"""
|
|
154
|
+
Loss function for the input perturbation.
|
|
155
|
+
|
|
156
|
+
Args:
|
|
157
|
+
inputs (TensorType): input samples
|
|
158
|
+
|
|
159
|
+
Returns:
|
|
160
|
+
TensorType: loss value
|
|
161
|
+
"""
|
|
162
|
+
# extract features
|
|
163
|
+
out_features, _ = self.feature_extractor.predict(
|
|
164
|
+
inputs, detach=False, postproc_fns=self.postproc_fns
|
|
165
|
+
)
|
|
166
|
+
# get mahalanobis score for the class maximizing it
|
|
167
|
+
she_score = self._get_she_output(out_features)
|
|
168
|
+
log_probs_f = self.op.log(she_score)
|
|
169
|
+
return self.op.mean(log_probs_f)
|
|
170
|
+
|
|
171
|
+
# compute gradient
|
|
172
|
+
gradient = self.op.gradient(__loss_fn, inputs)
|
|
173
|
+
gradient = self.op.sign(gradient)
|
|
174
|
+
|
|
175
|
+
inputs_p = inputs - self.eps * gradient
|
|
176
|
+
return inputs_p
|
|
177
|
+
|
|
178
|
+
@property
|
|
179
|
+
def requires_to_fit_dataset(self) -> bool:
|
|
180
|
+
"""
|
|
181
|
+
Whether an OOD detector needs a `fit_dataset` argument in the fit function.
|
|
182
|
+
|
|
183
|
+
Returns:
|
|
184
|
+
bool: True if `fit_dataset` is required else False.
|
|
185
|
+
"""
|
|
186
|
+
return True
|
|
187
|
+
|
|
188
|
+
@property
|
|
189
|
+
def requires_internal_features(self) -> bool:
|
|
190
|
+
"""
|
|
191
|
+
Whether an OOD detector acts on internal model features.
|
|
192
|
+
|
|
193
|
+
Returns:
|
|
194
|
+
bool: True if the detector perform computations on an intermediate layer
|
|
195
|
+
else False.
|
|
196
|
+
"""
|
|
197
|
+
return True
|
oodeel/methods/vim.py
CHANGED
|
@@ -61,7 +61,7 @@ class VIM(OODBaseDetector):
|
|
|
61
61
|
pca_origin (str): either "pseudo" for using $W^{-1}b$ where $W^{-1}$ is
|
|
62
62
|
the pseudo inverse of the final linear layer applied to bias term
|
|
63
63
|
(as in the VIM paper), or "center" for using the mean of the data in
|
|
64
|
-
feature space. Defaults to "
|
|
64
|
+
feature space. Defaults to "pseudo".
|
|
65
65
|
"""
|
|
66
66
|
|
|
67
67
|
def __init__(
|
|
@@ -86,7 +86,7 @@ class VIM(OODBaseDetector):
|
|
|
86
86
|
"""
|
|
87
87
|
# extract features from fit dataset
|
|
88
88
|
all_features_train, info = self.feature_extractor.predict(fit_dataset)
|
|
89
|
-
features_train = all_features_train
|
|
89
|
+
features_train = all_features_train[0]
|
|
90
90
|
logits_train = info["logits"]
|
|
91
91
|
features_train = self.op.flatten(features_train)
|
|
92
92
|
self.feature_dim = features_train.shape[1]
|
|
@@ -101,7 +101,7 @@ class VIM(OODBaseDetector):
|
|
|
101
101
|
# )
|
|
102
102
|
W, b = self.feature_extractor.get_weights(-1)
|
|
103
103
|
W, b = self.op.from_numpy(W), self.op.from_numpy(b.reshape(-1, 1))
|
|
104
|
-
_W = self.op.
|
|
104
|
+
_W = self.op.t(W) if self.backend == "tensorflow" else W
|
|
105
105
|
self.center = -self.op.reshape(self.op.matmul(self.op.pinv(_W), b), (-1,))
|
|
106
106
|
else:
|
|
107
107
|
raise NotImplementedError(
|
|
@@ -111,7 +111,7 @@ class VIM(OODBaseDetector):
|
|
|
111
111
|
# compute eigvalues and eigvectors of empirical covariance matrix
|
|
112
112
|
centered_features = features_train - self.center
|
|
113
113
|
emp_cov = (
|
|
114
|
-
self.op.matmul(self.op.
|
|
114
|
+
self.op.matmul(self.op.t(centered_features), centered_features)
|
|
115
115
|
/ centered_features.shape[0]
|
|
116
116
|
)
|
|
117
117
|
eig_vals, eigen_vectors = self.op.eigh(emp_cov)
|
|
@@ -174,7 +174,7 @@ class VIM(OODBaseDetector):
|
|
|
174
174
|
"""
|
|
175
175
|
# extract features
|
|
176
176
|
features, logits = self.feature_extractor.predict_tensor(inputs)
|
|
177
|
-
features = self.op.flatten(features)
|
|
177
|
+
features = self.op.flatten(features[0])
|
|
178
178
|
# vim score
|
|
179
179
|
res_scores = self._compute_residual_score_tensor(features)
|
|
180
180
|
logits = self.op.convert_to_numpy(logits)
|
|
@@ -0,0 +1,31 @@
|
|
|
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
|
+
try:
|
|
24
|
+
from .tf_preprocess import TFRandomPatchPermutation
|
|
25
|
+
except ImportError:
|
|
26
|
+
pass
|
|
27
|
+
|
|
28
|
+
try:
|
|
29
|
+
from .torch_preprocess import TorchRandomPatchPermutation
|
|
30
|
+
except ImportError:
|
|
31
|
+
pass
|
|
@@ -0,0 +1,95 @@
|
|
|
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
|
+
import tensorflow as tf
|
|
25
|
+
|
|
26
|
+
from ..types import Optional
|
|
27
|
+
from ..types import Tuple
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class TFRandomPatchPermutation:
|
|
31
|
+
def __init__(self, patch_size: Tuple[int] = (8, 8)):
|
|
32
|
+
"""Randomly permute the patches of an image. This transformation is used in NMD
|
|
33
|
+
paper to artificially craft OOD data from ID images.
|
|
34
|
+
|
|
35
|
+
Source (NMD paper):
|
|
36
|
+
"Neural Mean Discrepancy for Efficient Out-of-Distribution Detection"
|
|
37
|
+
[link](https://arxiv.org/pdf/2104.11408.pdf)
|
|
38
|
+
|
|
39
|
+
Args:
|
|
40
|
+
patch_size (Tuple[int], optional): Patch dimensions (h, w), should be
|
|
41
|
+
divisors of the image dimensions (H, W). Defaults to (8, 8).
|
|
42
|
+
"""
|
|
43
|
+
self.patch_size = patch_size
|
|
44
|
+
|
|
45
|
+
def __call__(self, tensor: tf.Tensor, seed: Optional[int] = None):
|
|
46
|
+
"""Apply random patch permutation.
|
|
47
|
+
|
|
48
|
+
Args:
|
|
49
|
+
tensor (tf.Tensor): Tensor of shape [H, W, C]
|
|
50
|
+
seed (Optinal[int]): Seed number to set for the permutation if not None.
|
|
51
|
+
|
|
52
|
+
Returns:
|
|
53
|
+
tf.Tensor: Transformed tensor.
|
|
54
|
+
"""
|
|
55
|
+
h, w = self.patch_size
|
|
56
|
+
H, W, C = tensor.shape
|
|
57
|
+
tensor_ = tensor
|
|
58
|
+
|
|
59
|
+
# raise warning if patch dimensions are not divisors of image dimensions
|
|
60
|
+
if H % h != 0:
|
|
61
|
+
print(
|
|
62
|
+
f"Warning! Patch height ({h}) should be a divisor of the image height"
|
|
63
|
+
+ f" ({H}). Zero padding will be added to get the correct output shape."
|
|
64
|
+
)
|
|
65
|
+
tensor_ = tensor[: -(H % h)]
|
|
66
|
+
if W % w != 0:
|
|
67
|
+
print(
|
|
68
|
+
f"Warning! Patch width ({w}) should be a divisor of the image width"
|
|
69
|
+
+ f" ({W}). Zero padding will be added to get the correct output shape."
|
|
70
|
+
)
|
|
71
|
+
tensor_ = tensor_[:, : -(W % w)]
|
|
72
|
+
|
|
73
|
+
# === patch permutation ===
|
|
74
|
+
# divide the batch of images into non-overlapping patches
|
|
75
|
+
# => [num_patches, h * w, C]
|
|
76
|
+
u = tf.transpose(
|
|
77
|
+
tf.reshape(tensor_, (H // h, h, W // w, w, C)), (0, 2, 1, 3, 4)
|
|
78
|
+
)
|
|
79
|
+
u = tf.reshape(u, (-1, h * w, C))
|
|
80
|
+
|
|
81
|
+
# permute the patches of each image in the batch
|
|
82
|
+
# => [num_patches, h * w, C]
|
|
83
|
+
# Note: we use numpy rng for deterministic index shuffling because
|
|
84
|
+
# `tf.stateless_shuffle` is still experimental
|
|
85
|
+
g = np.random.default_rng(seed=seed)
|
|
86
|
+
indices = np.arange(u.shape[0])
|
|
87
|
+
g.shuffle(indices)
|
|
88
|
+
pu = tf.gather(u, indices)
|
|
89
|
+
|
|
90
|
+
# fold the permuted patches back together
|
|
91
|
+
# => [H, W, C]
|
|
92
|
+
f = tf.transpose(tf.reshape(pu, (H // h, W // w, h, w, C)), (0, 2, 1, 3, 4))
|
|
93
|
+
f = tf.reshape(f, tensor_.shape)
|
|
94
|
+
f = tf.pad(f, tf.constant([[0, H % h], [0, W % w], [0, 0]]))
|
|
95
|
+
return f
|
|
@@ -0,0 +1,97 @@
|
|
|
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 torch
|
|
24
|
+
import torch.nn.functional as F
|
|
25
|
+
|
|
26
|
+
from ..types import Optional
|
|
27
|
+
from ..types import Tuple
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class TorchRandomPatchPermutation:
|
|
31
|
+
def __init__(self, patch_size: Tuple[int] = (8, 8)):
|
|
32
|
+
"""Randomly permute the patches of an image. This transformation is used in NMD
|
|
33
|
+
paper to artificially craft OOD data from ID images.
|
|
34
|
+
|
|
35
|
+
Source (NMD paper):
|
|
36
|
+
"Neural Mean Discrepancy for Efficient Out-of-Distribution Detection"
|
|
37
|
+
[link](https://arxiv.org/pdf/2104.11408.pdf)
|
|
38
|
+
|
|
39
|
+
Args:
|
|
40
|
+
patch_size (Tuple[int], optional): Patch dimensions (h, w), should be
|
|
41
|
+
divisors of the image dimensions (H, W). Defaults to (8, 8).
|
|
42
|
+
"""
|
|
43
|
+
self.patch_size = patch_size
|
|
44
|
+
|
|
45
|
+
def __call__(self, tensor: torch.Tensor, seed: Optional[int] = None):
|
|
46
|
+
"""Apply random patch permutation.
|
|
47
|
+
|
|
48
|
+
Args:
|
|
49
|
+
tensor (torch.Tensor): Tensor of shape [C, H, W]
|
|
50
|
+
seed (Optinal[int]): Seed number to set for the permutation if not None.
|
|
51
|
+
|
|
52
|
+
Returns:
|
|
53
|
+
torch.Tensor: Transformed tensor.
|
|
54
|
+
"""
|
|
55
|
+
h, w = self.patch_size
|
|
56
|
+
H, W, _ = tensor.shape
|
|
57
|
+
|
|
58
|
+
# set generator if seed is not None
|
|
59
|
+
g = None
|
|
60
|
+
if seed is not None:
|
|
61
|
+
g = torch.Generator(device=tensor.device)
|
|
62
|
+
g.manual_seed(seed)
|
|
63
|
+
|
|
64
|
+
# raise warning if patch dimensions are not divisors of image dimensions
|
|
65
|
+
if H % h != 0:
|
|
66
|
+
print(
|
|
67
|
+
f"Warning! Patch height ({h}) should be a divisor of the image height"
|
|
68
|
+
+ f" ({H}). Zero padding will be added to get the correct output shape."
|
|
69
|
+
)
|
|
70
|
+
if W % w != 0:
|
|
71
|
+
print(
|
|
72
|
+
f"Warning! Patch width ({w}) should be a divisor of the image width"
|
|
73
|
+
+ f" ({W}). Zero padding will be added to get the correct output shape."
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
# === patch permutation ===
|
|
77
|
+
# [C, H, W] => [1, C, H, W]
|
|
78
|
+
x = tensor.unsqueeze(0)
|
|
79
|
+
# divide the batch of images into non-overlapping patches
|
|
80
|
+
# => [1, h * w, num_patches]
|
|
81
|
+
u = F.unfold(x, kernel_size=self.patch_size, stride=self.patch_size, padding=0)
|
|
82
|
+
# permute the patches of each image in the batch
|
|
83
|
+
# => [1, h * w, num_patches]
|
|
84
|
+
pu = torch.cat(
|
|
85
|
+
[b_[:, torch.randperm(b_.shape[-1], generator=g)][None, ...] for b_ in u],
|
|
86
|
+
dim=0,
|
|
87
|
+
)
|
|
88
|
+
# fold the permuted patches back together
|
|
89
|
+
# => [1, C, H, W]
|
|
90
|
+
f = F.fold(
|
|
91
|
+
pu,
|
|
92
|
+
x.shape[-2:],
|
|
93
|
+
kernel_size=self.patch_size,
|
|
94
|
+
stride=self.patch_size,
|
|
95
|
+
padding=0,
|
|
96
|
+
)
|
|
97
|
+
return f.squeeze(0)
|
oodeel/utils/operator.py
CHANGED
|
@@ -49,10 +49,20 @@ class Operator(ABC):
|
|
|
49
49
|
|
|
50
50
|
@staticmethod
|
|
51
51
|
@abstractmethod
|
|
52
|
-
def max(
|
|
52
|
+
def max(
|
|
53
|
+
tensor: TensorType, dim: Optional[int] = None, keepdim: bool = False
|
|
54
|
+
) -> TensorType:
|
|
53
55
|
"""Max function"""
|
|
54
56
|
raise NotImplementedError()
|
|
55
57
|
|
|
58
|
+
@staticmethod
|
|
59
|
+
@abstractmethod
|
|
60
|
+
def min(
|
|
61
|
+
tensor: TensorType, dim: Optional[int] = None, keepdim: bool = False
|
|
62
|
+
) -> TensorType:
|
|
63
|
+
"""Min function"""
|
|
64
|
+
raise NotImplementedError()
|
|
65
|
+
|
|
56
66
|
@staticmethod
|
|
57
67
|
@abstractmethod
|
|
58
68
|
def one_hot(tensor: TensorType, num_classes: int) -> TensorType:
|
|
@@ -138,7 +148,13 @@ class Operator(ABC):
|
|
|
138
148
|
|
|
139
149
|
@staticmethod
|
|
140
150
|
@abstractmethod
|
|
141
|
-
def
|
|
151
|
+
def t(tensor: TensorType) -> TensorType:
|
|
152
|
+
"Transpose function for tensor of rank 2"
|
|
153
|
+
raise NotImplementedError()
|
|
154
|
+
|
|
155
|
+
@staticmethod
|
|
156
|
+
@abstractmethod
|
|
157
|
+
def permute(tensor: TensorType) -> TensorType:
|
|
142
158
|
"Transpose function for tensor of rank 2"
|
|
143
159
|
raise NotImplementedError()
|
|
144
160
|
|
|
@@ -181,3 +197,57 @@ class Operator(ABC):
|
|
|
181
197
|
def relu(tensor: TensorType) -> TensorType:
|
|
182
198
|
"Apply relu to a tensor"
|
|
183
199
|
raise NotImplementedError()
|
|
200
|
+
|
|
201
|
+
@staticmethod
|
|
202
|
+
@abstractmethod
|
|
203
|
+
def einsum(equation: str, *tensors: TensorType) -> TensorType:
|
|
204
|
+
"Computes the einsum between tensors following equation"
|
|
205
|
+
raise NotImplementedError()
|
|
206
|
+
|
|
207
|
+
@staticmethod
|
|
208
|
+
@abstractmethod
|
|
209
|
+
def tril(tensor: TensorType, diagonal: int = 0) -> TensorType:
|
|
210
|
+
"Set the upper triangle of the matrix formed by the last two dimensions of"
|
|
211
|
+
"tensor to zero"
|
|
212
|
+
raise NotImplementedError()
|
|
213
|
+
|
|
214
|
+
@staticmethod
|
|
215
|
+
def sum(tensor: TensorType, dim: Union[tuple, list, int] = None) -> TensorType:
|
|
216
|
+
"sum along dim"
|
|
217
|
+
raise NotImplementedError()
|
|
218
|
+
|
|
219
|
+
@staticmethod
|
|
220
|
+
def unsqueeze(tensor: TensorType, dim: int) -> TensorType:
|
|
221
|
+
"unsqueeze/expand_dim along dim"
|
|
222
|
+
raise NotImplementedError()
|
|
223
|
+
|
|
224
|
+
@staticmethod
|
|
225
|
+
def squeeze(tensor: TensorType, dim: int = None) -> TensorType:
|
|
226
|
+
"squeeze along dim"
|
|
227
|
+
raise NotImplementedError()
|
|
228
|
+
|
|
229
|
+
@staticmethod
|
|
230
|
+
def abs(tensor: TensorType) -> TensorType:
|
|
231
|
+
"compute absolute value"
|
|
232
|
+
raise NotImplementedError()
|
|
233
|
+
|
|
234
|
+
@staticmethod
|
|
235
|
+
def where(
|
|
236
|
+
condition: TensorType,
|
|
237
|
+
input: Union[TensorType, float],
|
|
238
|
+
other: Union[TensorType, float],
|
|
239
|
+
) -> TensorType:
|
|
240
|
+
"Applies where function to condition"
|
|
241
|
+
raise NotImplementedError()
|
|
242
|
+
|
|
243
|
+
@staticmethod
|
|
244
|
+
@abstractmethod
|
|
245
|
+
def avg_pool_2d(tensor: TensorType) -> TensorType:
|
|
246
|
+
"""Perform avg pool in 2d as in torch.nn.functional.adaptive_avg_pool2d"""
|
|
247
|
+
raise NotImplementedError()
|
|
248
|
+
|
|
249
|
+
@staticmethod
|
|
250
|
+
@abstractmethod
|
|
251
|
+
def log(tensor: TensorType) -> TensorType:
|
|
252
|
+
"""Perform log"""
|
|
253
|
+
raise NotImplementedError()
|
oodeel/utils/tf_operator.py
CHANGED
|
@@ -65,9 +65,18 @@ class TFOperator(Operator):
|
|
|
65
65
|
return tf.argmax(tensor, axis=dim)
|
|
66
66
|
|
|
67
67
|
@staticmethod
|
|
68
|
-
def max(
|
|
68
|
+
def max(
|
|
69
|
+
tensor: TensorType, dim: Optional[int] = None, keepdim: bool = False
|
|
70
|
+
) -> tf.Tensor:
|
|
69
71
|
"""Max function"""
|
|
70
|
-
return tf.reduce_max(tensor, axis=dim)
|
|
72
|
+
return tf.reduce_max(tensor, axis=dim, keepdims=keepdim)
|
|
73
|
+
|
|
74
|
+
@staticmethod
|
|
75
|
+
def min(
|
|
76
|
+
tensor: TensorType, dim: Optional[int] = None, keepdim: bool = False
|
|
77
|
+
) -> tf.Tensor:
|
|
78
|
+
"""Min function"""
|
|
79
|
+
return tf.reduce_min(tensor, axis=dim, keepdims=keepdim)
|
|
71
80
|
|
|
72
81
|
@staticmethod
|
|
73
82
|
def one_hot(tensor: TensorType, num_classes: int) -> tf.Tensor:
|
|
@@ -152,13 +161,18 @@ class TFOperator(Operator):
|
|
|
152
161
|
def from_numpy(arr: np.ndarray) -> tf.Tensor:
|
|
153
162
|
"Convert a NumPy array to a tensor"
|
|
154
163
|
# TODO change dtype
|
|
155
|
-
return tf.
|
|
164
|
+
return tf.convert_to_tensor(arr)
|
|
156
165
|
|
|
157
166
|
@staticmethod
|
|
158
|
-
def
|
|
167
|
+
def t(tensor: TensorType) -> tf.Tensor:
|
|
159
168
|
"Transpose function for tensor of rank 2"
|
|
160
169
|
return tf.transpose(tensor)
|
|
161
170
|
|
|
171
|
+
@staticmethod
|
|
172
|
+
def permute(tensor: TensorType, dims) -> tf.Tensor:
|
|
173
|
+
"Transpose function for tensor of rank 2"
|
|
174
|
+
return tf.transpose(tensor, dims)
|
|
175
|
+
|
|
162
176
|
@staticmethod
|
|
163
177
|
def diag(tensor: TensorType) -> tf.Tensor:
|
|
164
178
|
"Diagonal function: return the diagonal of a 2D tensor"
|
|
@@ -195,3 +209,57 @@ class TFOperator(Operator):
|
|
|
195
209
|
def relu(tensor: TensorType) -> tf.Tensor:
|
|
196
210
|
"Apply relu to a tensor"
|
|
197
211
|
return tf.nn.relu(tensor)
|
|
212
|
+
|
|
213
|
+
@staticmethod
|
|
214
|
+
def einsum(equation: str, *tensors: TensorType) -> tf.Tensor:
|
|
215
|
+
"Computes the einsum between tensors following equation"
|
|
216
|
+
return tf.einsum(equation, *tensors)
|
|
217
|
+
|
|
218
|
+
@staticmethod
|
|
219
|
+
def tril(tensor: TensorType, diagonal: int = 0) -> tf.Tensor:
|
|
220
|
+
"Set the upper triangle of the matrix formed by the last two dimensions of"
|
|
221
|
+
"tensor to zero"
|
|
222
|
+
return tf.experimental.numpy.tril(tensor, k=diagonal)
|
|
223
|
+
|
|
224
|
+
@staticmethod
|
|
225
|
+
def sum(tensor: TensorType, dim: Union[tuple, list, int] = None) -> tf.Tensor:
|
|
226
|
+
"sum along dim"
|
|
227
|
+
return tf.reduce_sum(tensor, axis=dim)
|
|
228
|
+
|
|
229
|
+
@staticmethod
|
|
230
|
+
def unsqueeze(tensor: TensorType, dim: int) -> tf.Tensor:
|
|
231
|
+
"expand_dim along dim"
|
|
232
|
+
return tf.expand_dims(tensor, dim)
|
|
233
|
+
|
|
234
|
+
@staticmethod
|
|
235
|
+
def squeeze(tensor: TensorType, dim: int = None) -> tf.Tensor:
|
|
236
|
+
"expand_dim along dim"
|
|
237
|
+
return tf.squeeze(tensor, dim)
|
|
238
|
+
|
|
239
|
+
@staticmethod
|
|
240
|
+
def abs(tensor: TensorType) -> tf.Tensor:
|
|
241
|
+
"compute absolute value"
|
|
242
|
+
return tf.abs(tensor)
|
|
243
|
+
|
|
244
|
+
@staticmethod
|
|
245
|
+
def where(
|
|
246
|
+
condition: TensorType,
|
|
247
|
+
input: Union[TensorType, float],
|
|
248
|
+
other: Union[TensorType, float],
|
|
249
|
+
) -> tf.Tensor:
|
|
250
|
+
"Applies where function to condition"
|
|
251
|
+
return tf.where(condition, input, other)
|
|
252
|
+
|
|
253
|
+
@staticmethod
|
|
254
|
+
def percentile(x, q):
|
|
255
|
+
return tfp.stats.percentile(x, q)
|
|
256
|
+
|
|
257
|
+
@staticmethod
|
|
258
|
+
def avg_pool_2d(tensor: TensorType) -> tf.Tensor:
|
|
259
|
+
"""Perform avg pool in 2d as in torch.nn.functional.adaptive_avg_pool2d"""
|
|
260
|
+
return tf.reduce_mean(tensor, axis=(-3, -2))
|
|
261
|
+
|
|
262
|
+
@staticmethod
|
|
263
|
+
def log(tensor: TensorType) -> tf.Tensor:
|
|
264
|
+
"""Perform log"""
|
|
265
|
+
return tf.math.log(tensor)
|