distance-explainer 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.
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "{}"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
203
|
+
|
|
204
|
+
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: distance_explainer
|
|
3
|
+
Version: 0.4.0
|
|
4
|
+
Summary: XAI method to explain distances in embedded spaces
|
|
5
|
+
Home-page: https://github.com/dianna-ai/distance_explainer
|
|
6
|
+
Author: Christiaan Meijer
|
|
7
|
+
Author-email: c.meijer@esciencecenter.nl
|
|
8
|
+
Project-URL: Bug Tracker, https://github.com/dianna-ai/distance_explainer/issues
|
|
9
|
+
Keywords: XAI,embedded spaces
|
|
10
|
+
Classifier: Development Status :: 2 - Pre-Alpha
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
13
|
+
Classifier: Natural Language :: English
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Requires-Python: >=3.9
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
Requires-Dist: dianna>=1.4
|
|
23
|
+
Requires-Dist: numpy
|
|
24
|
+
Requires-Dist: pytest
|
|
25
|
+
Requires-Dist: tqdm
|
|
26
|
+
Requires-Dist: scikit-learn
|
|
27
|
+
Requires-Dist: pyyaml
|
|
28
|
+
Requires-Dist: dataclass-wizard
|
|
29
|
+
Provides-Extra: dev
|
|
30
|
+
Requires-Dist: build; extra == "dev"
|
|
31
|
+
Requires-Dist: bump2version; extra == "dev"
|
|
32
|
+
Requires-Dist: coverage[toml]; extra == "dev"
|
|
33
|
+
Requires-Dist: ruff; extra == "dev"
|
|
34
|
+
Requires-Dist: pytest; extra == "dev"
|
|
35
|
+
Requires-Dist: pytest-cov; extra == "dev"
|
|
36
|
+
Requires-Dist: sphinx; extra == "dev"
|
|
37
|
+
Requires-Dist: sphinx-rtd-theme; extra == "dev"
|
|
38
|
+
Requires-Dist: sphinx-autoapi; extra == "dev"
|
|
39
|
+
Requires-Dist: tox; extra == "dev"
|
|
40
|
+
Requires-Dist: myst-parser; extra == "dev"
|
|
41
|
+
Provides-Extra: publishing
|
|
42
|
+
Requires-Dist: twine; extra == "publishing"
|
|
43
|
+
Requires-Dist: wheel; extra == "publishing"
|
|
44
|
+
|
|
45
|
+
[](https://doi.org/10.5281/zenodo.10018768) [](https://pypi.python.org/project/distance_explainer/)
|
|
46
|
+
|
|
47
|
+
# `distance_explainer`
|
|
48
|
+
|
|
49
|
+
XAI method to explain distances in embedded spaces.
|
|
50
|
+
|
|
51
|
+

|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
## Installation
|
|
55
|
+
|
|
56
|
+
To install distance_explainer from GitHub repository, do:
|
|
57
|
+
|
|
58
|
+
```console
|
|
59
|
+
git clone git@github.com:dianna-ai/distance_explainer.git
|
|
60
|
+
cd distance_explainer
|
|
61
|
+
python3 -m pip install .
|
|
62
|
+
```
|
|
63
|
+
## How to use
|
|
64
|
+
|
|
65
|
+
See our [tutorial](tutorial.ipynb) how to use this package.
|
|
66
|
+
In short:
|
|
67
|
+
```python
|
|
68
|
+
image1 = np.random.random((100, 100, 3))
|
|
69
|
+
image2 = np.random.random((100, 100, 3))
|
|
70
|
+
|
|
71
|
+
image2_embedded = model(image2)
|
|
72
|
+
explainer = DistanceExplainer(axis_labels={2: 'channels'})
|
|
73
|
+
attribution_map = explainer.explain_image_distance(model, image1, image2_embedded)
|
|
74
|
+
```
|
|
75
|
+
## Contributing
|
|
76
|
+
|
|
77
|
+
If you want to contribute to the development of distance_explainer,
|
|
78
|
+
have a look at the [contribution guidelines](docs/CONTRIBUTING.md).
|
|
79
|
+
|
|
80
|
+
## Credits
|
|
81
|
+
|
|
82
|
+
This package was created with [Cookiecutter](https://github.com/audreyr/cookiecutter) and the [NLeSC/python-template](https://github.com/NLeSC/python-template).
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
distance_explainer.py,sha256=BAkMo621YLdX9Ox_MOFw5qQ0uPSJBM0IpC1lauxbAc8,10285
|
|
2
|
+
distance_explainer-0.4.0.dist-info/LICENSE,sha256=OPzV6bHGPCXFylyiCR3GYAK-EP8seLDbcbgO87DYM1o,11359
|
|
3
|
+
distance_explainer-0.4.0.dist-info/METADATA,sha256=AKFPmnjXNYWDviNQ0M9AFx_yi6FQsk7RO0bQXclXBkM,2962
|
|
4
|
+
distance_explainer-0.4.0.dist-info/WHEEL,sha256=P9jw-gEje8ByB7_hXoICnHtVCrEwMQh-630tKvQWehc,91
|
|
5
|
+
distance_explainer-0.4.0.dist-info/top_level.txt,sha256=Eb2RZ72DZmJ--Xbug_-bZ_zQGOlqmhZp_XZs0Vj9FEc,19
|
|
6
|
+
distance_explainer-0.4.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
distance_explainer
|
distance_explainer.py
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
"""Documentation about distance_explainer."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
import dianna.utils
|
|
5
|
+
import numpy as np
|
|
6
|
+
import numpy.typing
|
|
7
|
+
from dianna.utils.maskers import generate_interpolated_float_masks_for_image
|
|
8
|
+
from sklearn.metrics import pairwise_distances
|
|
9
|
+
from tqdm import tqdm
|
|
10
|
+
|
|
11
|
+
logging.getLogger(__name__).addHandler(logging.NullHandler())
|
|
12
|
+
|
|
13
|
+
__author__ = "Christiaan Meijer"
|
|
14
|
+
__email__ = "c.meijer@esciencecenter.nl"
|
|
15
|
+
__version__ = "0.4.0"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class DistanceExplainer:
|
|
19
|
+
"""Explainer object to explain an image with respect to a reference point in an embedded space."""
|
|
20
|
+
# axis labels required to be present in input image data
|
|
21
|
+
required_labels = ('channels',)
|
|
22
|
+
|
|
23
|
+
def __init__(self, n_masks=1000, feature_res=8, p_keep=.5, # pylint: disable=too-many-arguments
|
|
24
|
+
mask_selection_range_max=0.2, mask_selection_range_min=0, mask_selection_negative_range_max=1,
|
|
25
|
+
mask_selection_negative_range_min=0.8, axis_labels=None, batch_size=10,
|
|
26
|
+
preprocess_function=None):
|
|
27
|
+
"""Creates an explainer object to explain an image with respect to a reference point in an embedded space.
|
|
28
|
+
|
|
29
|
+
Args:
|
|
30
|
+
n_masks: Number of masks to use to mask the input image. More increases reliability and computation.
|
|
31
|
+
feature_res: Number of features per dimension in the image. Determines the super pixel size in the masks.
|
|
32
|
+
p_keep: Probability of keeping features unmasked. Higher means less masked input.
|
|
33
|
+
batch_size: Number of masked inputs to process in a single batch by the model
|
|
34
|
+
axis_labels: Axis labels
|
|
35
|
+
preprocess_function: Preprocess function
|
|
36
|
+
mask_selection_range_max: Top end of range of outcomes that will be selected.
|
|
37
|
+
mask_selection_range_min: Lower end of range of outcomes that will be selected.
|
|
38
|
+
mask_selection_negative_range_max: Top end of range of outcomes that will be selected and weighted -1.
|
|
39
|
+
mask_selection_negative_range_min: Lower end of range of outcomes that will be selected and weighted -1.
|
|
40
|
+
"""
|
|
41
|
+
self.n_masks = n_masks
|
|
42
|
+
self.feature_res = feature_res
|
|
43
|
+
self.p_keep = p_keep
|
|
44
|
+
self.preprocess_function = preprocess_function
|
|
45
|
+
self.masks = None
|
|
46
|
+
self.predictions = None
|
|
47
|
+
self.axis_labels = axis_labels if axis_labels is not None else []
|
|
48
|
+
self.mask_selection_range_max = mask_selection_range_max
|
|
49
|
+
self.mask_selection_range_min = mask_selection_range_min
|
|
50
|
+
self.mask_selection_negative_range_max = mask_selection_negative_range_max
|
|
51
|
+
self.mask_selection_negative_range_min = mask_selection_negative_range_min
|
|
52
|
+
self.batch_size = batch_size
|
|
53
|
+
|
|
54
|
+
def explain_image_distance(self, model_or_function, input_data, embedded_reference, masks=None) -> tuple[
|
|
55
|
+
numpy.typing.NDArray, float]:
|
|
56
|
+
"""Explain an image with respect to a reference point in an embedded space.
|
|
57
|
+
|
|
58
|
+
Args:
|
|
59
|
+
model_or_function: Model that will encode the input_data into an embedded space
|
|
60
|
+
input_data: Input data to be explained, by exploring what parts make it closer to the reference point.
|
|
61
|
+
embedded_reference: Reference point in the embedded space
|
|
62
|
+
masks: User specified masks, in case no autogenerated masks should be used.
|
|
63
|
+
|
|
64
|
+
Returns:
|
|
65
|
+
attribution_map map
|
|
66
|
+
"""
|
|
67
|
+
full_preprocess_function, input_data = self._prepare_input_data(input_data)
|
|
68
|
+
runner = dianna.utils.get_function(model_or_function, preprocess_function=full_preprocess_function)
|
|
69
|
+
active_p_keep = 0.5 if self.p_keep is None else self.p_keep # Could autotune here (See #319)
|
|
70
|
+
|
|
71
|
+
# data shape without batch axis and channel axis
|
|
72
|
+
img_shape = input_data.shape[1:3]
|
|
73
|
+
# Expose masks for to make user inspection possible
|
|
74
|
+
if masks is None:
|
|
75
|
+
self.masks = generate_interpolated_float_masks_for_image(img_shape, active_p_keep, self.n_masks,
|
|
76
|
+
self.feature_res)
|
|
77
|
+
else:
|
|
78
|
+
self.masks = masks
|
|
79
|
+
if self.masks.shape[0] != self.n_masks:
|
|
80
|
+
raise ValueError(f"Configured n_masks ({self.n_masks}) is not equal to the number of masks passed "
|
|
81
|
+
f"({self.masks.shape[0]}).")
|
|
82
|
+
|
|
83
|
+
# Make sure multiplication is being done for correct axes
|
|
84
|
+
masked = input_data * self.masks
|
|
85
|
+
|
|
86
|
+
batch_predictions = []
|
|
87
|
+
|
|
88
|
+
for i in tqdm(range(0, self.n_masks, self.batch_size), desc='Explaining'):
|
|
89
|
+
new_predictions = runner(masked[i:i + self.batch_size])
|
|
90
|
+
batch_predictions.append(new_predictions)
|
|
91
|
+
|
|
92
|
+
self.predictions = np.concatenate(batch_predictions)
|
|
93
|
+
|
|
94
|
+
def describe(x, name):
|
|
95
|
+
return f'Description of {name}\nmean:{np.mean(x)}\nstd:{np.std(x)}\nmin:{np.min(x)}\nmax:{np.max(x)}'
|
|
96
|
+
|
|
97
|
+
statistics = []
|
|
98
|
+
|
|
99
|
+
highest_distances_masks, highest_mask_weights = self._get_lowest_distance_masks_and_weights(
|
|
100
|
+
embedded_reference,
|
|
101
|
+
self.predictions, self.masks,
|
|
102
|
+
self.mask_selection_negative_range_min,
|
|
103
|
+
self.mask_selection_negative_range_max)
|
|
104
|
+
|
|
105
|
+
if len(highest_mask_weights) > 0:
|
|
106
|
+
statistics.append(describe(highest_mask_weights, 'highest_mask_weights'))
|
|
107
|
+
unnormalized_sal_highest = np.mean(highest_distances_masks, axis=0)
|
|
108
|
+
else:
|
|
109
|
+
unnormalized_sal_highest = 0
|
|
110
|
+
|
|
111
|
+
lowest_distances_masks, lowest_mask_weights = self._get_lowest_distance_masks_and_weights(
|
|
112
|
+
embedded_reference,
|
|
113
|
+
self.predictions, self.masks,
|
|
114
|
+
self.mask_selection_range_min,
|
|
115
|
+
self.mask_selection_range_max)
|
|
116
|
+
|
|
117
|
+
if len(lowest_mask_weights) > 0:
|
|
118
|
+
statistics.append(describe(lowest_mask_weights, 'lowest_mask_weights'))
|
|
119
|
+
unnormalized_sal_lowest = np.mean(lowest_distances_masks, axis=0)
|
|
120
|
+
else:
|
|
121
|
+
unnormalized_sal_lowest = 0
|
|
122
|
+
|
|
123
|
+
self.statistics = '\n'.join(statistics)
|
|
124
|
+
unnormalized_sal = unnormalized_sal_lowest - unnormalized_sal_highest
|
|
125
|
+
|
|
126
|
+
attribution_map = unnormalized_sal
|
|
127
|
+
|
|
128
|
+
return attribution_map
|
|
129
|
+
|
|
130
|
+
@staticmethod
|
|
131
|
+
def _get_lowest_distance_masks_and_weights(embedded_reference, predictions, masks, mask_selection_range_min,
|
|
132
|
+
mask_selection_range_max):
|
|
133
|
+
distances = DistanceExplainer.calculate_distances(predictions, embedded_reference[None, ...])
|
|
134
|
+
|
|
135
|
+
lowest_distances_indices = np.argsort(distances, axis=0)[
|
|
136
|
+
int(len(predictions) * mask_selection_range_min)
|
|
137
|
+
:int(len(predictions) * mask_selection_range_max)]
|
|
138
|
+
mask_weights = np.exp(-distances[lowest_distances_indices])
|
|
139
|
+
lowest_distances_masks = masks[lowest_distances_indices]
|
|
140
|
+
return lowest_distances_masks, mask_weights
|
|
141
|
+
|
|
142
|
+
@staticmethod
|
|
143
|
+
def calculate_distances(predictions: np.ndarray, embedded_reference: np.ndarray) -> np.ndarray:
|
|
144
|
+
"""Calculate the distances to the reference point in an embedded space using cosine distance with range [0,1].
|
|
145
|
+
|
|
146
|
+
Args:
|
|
147
|
+
predictions: Batch of points in the embedded space for with distances are calculated
|
|
148
|
+
embedded_reference: Point to calculate the distance to
|
|
149
|
+
|
|
150
|
+
Returns:
|
|
151
|
+
Distances from each point to the reference point
|
|
152
|
+
"""
|
|
153
|
+
distances = pairwise_distances(predictions, embedded_reference,
|
|
154
|
+
metric='cosine') / 2 # divide by 2 to have [0.1] output range
|
|
155
|
+
return distances
|
|
156
|
+
|
|
157
|
+
def _prepare_input_data(self, input_data):
|
|
158
|
+
input_data_xarray = dianna.utils.to_xarray(input_data, self.axis_labels, DistanceExplainer.required_labels)
|
|
159
|
+
input_data_xarray_expanded = input_data_xarray.expand_dims('batch', 0)
|
|
160
|
+
# ensure channels axis is last and keep track of where it was so we can move it back
|
|
161
|
+
channels_axis_index = input_data_xarray_expanded.dims.index('channels')
|
|
162
|
+
prepared_input_data = dianna.utils.move_axis(input_data_xarray_expanded, 'channels', -1)
|
|
163
|
+
# create preprocessing function that puts model input generated by RISE into the right shape and dtype,
|
|
164
|
+
# followed by running the user's preprocessing function
|
|
165
|
+
full_preprocess_function = self._get_full_preprocess_function(channels_axis_index, prepared_input_data.dtype)
|
|
166
|
+
return full_preprocess_function, prepared_input_data
|
|
167
|
+
|
|
168
|
+
def _prepare_image_data(self, input_data):
|
|
169
|
+
"""Transforms the data to be of the shape and type RISE expects.
|
|
170
|
+
|
|
171
|
+
Args:
|
|
172
|
+
input_data (xarray): Data to be explained
|
|
173
|
+
|
|
174
|
+
Returns:
|
|
175
|
+
transformed input data, preprocessing function to use with dianna.utils.get_function()
|
|
176
|
+
"""
|
|
177
|
+
# ensure channels axis is last and keep track of where it was so we can move it back
|
|
178
|
+
channels_axis_index = input_data.dims.index('channels')
|
|
179
|
+
input_data = dianna.utils.move_axis(input_data, 'channels', -1)
|
|
180
|
+
# create preprocessing function that puts model input generated by RISE into the right shape and dtype,
|
|
181
|
+
# followed by running the user's preprocessing function
|
|
182
|
+
full_preprocess_function = self._get_full_preprocess_function(channels_axis_index, input_data.dtype)
|
|
183
|
+
return input_data, full_preprocess_function
|
|
184
|
+
|
|
185
|
+
def _get_full_preprocess_function(self, channel_axis_index, dtype):
|
|
186
|
+
"""Creates a full preprocessing function.
|
|
187
|
+
|
|
188
|
+
Creates a preprocessing function that incorporates both the (optional) user's
|
|
189
|
+
preprocessing function, as well as any needed dtype and shape conversions
|
|
190
|
+
|
|
191
|
+
Args:
|
|
192
|
+
channel_axis_index (int): Axis index of the channels in the input data
|
|
193
|
+
dtype (type): Data type of the input data (e.g. np.float32)
|
|
194
|
+
|
|
195
|
+
Returns:
|
|
196
|
+
Function that first ensures the data has the same shape and type as the input data,
|
|
197
|
+
then runs the users' preprocessing function
|
|
198
|
+
"""
|
|
199
|
+
|
|
200
|
+
def moveaxis_function(data):
|
|
201
|
+
return dianna.utils.move_axis(data, 'channels', channel_axis_index).astype(dtype).values
|
|
202
|
+
|
|
203
|
+
if self.preprocess_function is None:
|
|
204
|
+
return moveaxis_function
|
|
205
|
+
return lambda data: self.preprocess_function(moveaxis_function(data))
|