distance-explainer 0.4.0__tar.gz

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,23 @@
1
+ # YAML 1.2
2
+ ---
3
+ cff-version: "1.2.0"
4
+ title: "distance_explainer"
5
+ authors:
6
+ -
7
+ family-names: Meijer
8
+ given-names: Christiaan
9
+ orcid: "https://orcid.org/0000-0002-5529-5761"
10
+ -
11
+ family-names: Bos
12
+ given-names: Patrick
13
+ orcid: "https://orcid.org/0000-0002-6033-960X"
14
+
15
+ date-released: 2023-10-19
16
+ doi: 10.5281/zenodo.10018768.
17
+ version: "0.4.0"
18
+ repository-code: "git@github.com:dianna-ai/distance_explainer"
19
+ keywords:
20
+ - XAI
21
+ - embedded spaces
22
+ message: "If you use this software, please cite it using these metadata."
23
+ license: Apache-2.0
@@ -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,3 @@
1
+ include CITATION.cff
2
+ include LICENSE
3
+ include README.md
@@ -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
+ [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.10018768.svg)](https://doi.org/10.5281/zenodo.10018768) [![workflow pypi badge](https://img.shields.io/pypi/v/distance_explainer.svg?colorB=blue)](https://pypi.python.org/project/distance_explainer/)
46
+
47
+ # `distance_explainer`
48
+
49
+ XAI method to explain distances in embedded spaces.
50
+
51
+ ![overview schema](https://github.com/user-attachments/assets/bbd5a79c-c50b-47a2-89fc-d8ed3053c845)
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,38 @@
1
+ [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.10018768.svg)](https://doi.org/10.5281/zenodo.10018768) [![workflow pypi badge](https://img.shields.io/pypi/v/distance_explainer.svg?colorB=blue)](https://pypi.python.org/project/distance_explainer/)
2
+
3
+ # `distance_explainer`
4
+
5
+ XAI method to explain distances in embedded spaces.
6
+
7
+ ![overview schema](https://github.com/user-attachments/assets/bbd5a79c-c50b-47a2-89fc-d8ed3053c845)
8
+
9
+
10
+ ## Installation
11
+
12
+ To install distance_explainer from GitHub repository, do:
13
+
14
+ ```console
15
+ git clone git@github.com:dianna-ai/distance_explainer.git
16
+ cd distance_explainer
17
+ python3 -m pip install .
18
+ ```
19
+ ## How to use
20
+
21
+ See our [tutorial](tutorial.ipynb) how to use this package.
22
+ In short:
23
+ ```python
24
+ image1 = np.random.random((100, 100, 3))
25
+ image2 = np.random.random((100, 100, 3))
26
+
27
+ image2_embedded = model(image2)
28
+ explainer = DistanceExplainer(axis_labels={2: 'channels'})
29
+ attribution_map = explainer.explain_image_distance(model, image1, image2_embedded)
30
+ ```
31
+ ## Contributing
32
+
33
+ If you want to contribute to the development of distance_explainer,
34
+ have a look at the [contribution guidelines](docs/CONTRIBUTING.md).
35
+
36
+ ## Credits
37
+
38
+ 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,95 @@
1
+ [build-system]
2
+ requires = ["setuptools", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [tool.pytest.ini_options]
6
+ testpaths = ["tests"]
7
+
8
+ [tool.coverage.run]
9
+ branch = true
10
+ source = ["distance_explainer"]
11
+ command_line = "-m pytest"
12
+
13
+ [tool.tox]
14
+ legacy_tox_ini = """
15
+ [tox]
16
+ envlist = py39,py310,py311
17
+ skip_missing_interpreters = true
18
+ [testenv]
19
+ commands = pytest
20
+ extras = dev
21
+ """
22
+
23
+ [tool.ruff]
24
+ # Enable Pyflakes `E` and `F` codes by default.
25
+ select = [
26
+ "F", # Pyflakes
27
+ "E", # pycodestyle (error)
28
+ "W", # pycodestyle (warning)
29
+ # "C90", # mccabe
30
+ "I", # isort
31
+ "D", # pydocstyle
32
+ # "PL", # Pylint
33
+ # "PLC", # Convention
34
+ # "PLE", # Error
35
+ # "PLR", # Refactor
36
+ # "PLW", # Warning
37
+
38
+ ]
39
+ ignore = [
40
+ 'D100', # Missing module docstring
41
+ # The following list excludes rules irrelevant to the Google style
42
+ 'D203',
43
+ 'D204',
44
+ 'D213',
45
+ 'D215',
46
+ 'D400',
47
+ 'D401',
48
+ 'D404',
49
+ 'D406',
50
+ 'D407',
51
+ 'D408',
52
+ 'D409',
53
+ 'D413',
54
+ ]
55
+
56
+ # Allow autofix for all enabled rules (when `--fix`) is provided.
57
+ fixable = ["A", "B", "C", "D", "E", "F", "I"]
58
+ unfixable = []
59
+
60
+ exclude = [
61
+ ".bzr",
62
+ ".direnv",
63
+ ".eggs",
64
+ ".git",
65
+ ".hg",
66
+ ".mypy_cache",
67
+ ".nox",
68
+ ".pants.d",
69
+ ".ruff_cache",
70
+ ".svn",
71
+ ".tox",
72
+ ".venv",
73
+ "__pypackages__",
74
+ "_build",
75
+ "buck-out",
76
+ "build",
77
+ "dist",
78
+ "node_modules",
79
+ "venv",
80
+ ".venv",
81
+ "scripts",
82
+ ]
83
+ per-file-ignores = {}
84
+
85
+
86
+ # Allow unused variables when underscore-prefixed.
87
+ dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$"
88
+
89
+ target-version = "py39"
90
+ line-length = 120
91
+
92
+ [tool.ruff.isort]
93
+ known-first-party = ["distance_explainer"]
94
+ force-single-line = true
95
+ no-lines-before = ["future","standard-library","third-party","first-party","local-folder"]
@@ -0,0 +1,57 @@
1
+ [metadata]
2
+ author = Christiaan Meijer
3
+ author_email = c.meijer@esciencecenter.nl
4
+ classifiers =
5
+ Development Status :: 2 - Pre-Alpha
6
+ Intended Audience :: Developers
7
+ License :: OSI Approved :: Apache Software License
8
+ Natural Language :: English
9
+ Programming Language :: Python :: 3
10
+ Programming Language :: Python :: 3.9
11
+ Programming Language :: Python :: 3.10
12
+ Programming Language :: Python :: 3.11
13
+ Programming Language :: Python :: 3.12
14
+ description = XAI method to explain distances in embedded spaces
15
+ keywords =
16
+ XAI
17
+ embedded spaces
18
+ long_description = file: README.md
19
+ long_description_content_type = text/markdown
20
+ name = distance_explainer
21
+ project_urls =
22
+ Bug Tracker = https://github.com/dianna-ai/distance_explainer/issues
23
+ url = https://github.com/dianna-ai/distance_explainer
24
+ version = 0.4.0
25
+
26
+ [options]
27
+ python_requires = >=3.9
28
+ install_requires =
29
+ dianna>=1.4
30
+ numpy
31
+ pytest
32
+ tqdm
33
+ scikit-learn
34
+ pyyaml
35
+ dataclass_wizard
36
+
37
+ [options.extras_require]
38
+ dev =
39
+ build
40
+ bump2version
41
+ coverage [toml]
42
+ ruff
43
+ pytest
44
+ pytest-cov
45
+ sphinx
46
+ sphinx_rtd_theme
47
+ sphinx-autoapi
48
+ tox
49
+ myst_parser
50
+ publishing =
51
+ twine
52
+ wheel
53
+
54
+ [egg_info]
55
+ tag_build =
56
+ tag_date = 0
57
+
@@ -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
+ [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.10018768.svg)](https://doi.org/10.5281/zenodo.10018768) [![workflow pypi badge](https://img.shields.io/pypi/v/distance_explainer.svg?colorB=blue)](https://pypi.python.org/project/distance_explainer/)
46
+
47
+ # `distance_explainer`
48
+
49
+ XAI method to explain distances in embedded spaces.
50
+
51
+ ![overview schema](https://github.com/user-attachments/assets/bbd5a79c-c50b-47a2-89fc-d8ed3053c845)
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,13 @@
1
+ CITATION.cff
2
+ LICENSE
3
+ MANIFEST.in
4
+ README.md
5
+ pyproject.toml
6
+ setup.cfg
7
+ src/distance_explainer.py
8
+ src/distance_explainer.egg-info/PKG-INFO
9
+ src/distance_explainer.egg-info/SOURCES.txt
10
+ src/distance_explainer.egg-info/dependency_links.txt
11
+ src/distance_explainer.egg-info/requires.txt
12
+ src/distance_explainer.egg-info/top_level.txt
13
+ tests/test_distance.py
@@ -0,0 +1,24 @@
1
+ dianna>=1.4
2
+ numpy
3
+ pytest
4
+ tqdm
5
+ scikit-learn
6
+ pyyaml
7
+ dataclass_wizard
8
+
9
+ [dev]
10
+ build
11
+ bump2version
12
+ coverage[toml]
13
+ ruff
14
+ pytest
15
+ pytest-cov
16
+ sphinx
17
+ sphinx_rtd_theme
18
+ sphinx-autoapi
19
+ tox
20
+ myst_parser
21
+
22
+ [publishing]
23
+ twine
24
+ wheel
@@ -0,0 +1 @@
1
+ distance_explainer
@@ -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))
@@ -0,0 +1,79 @@
1
+ """Tests for the distance_explainer."""
2
+ import dataclasses
3
+ import os
4
+ from typing import Callable
5
+ import numpy as np
6
+ import pytest
7
+ from numpy.typing import ArrayLike
8
+ from distance_explainer import DistanceExplainer
9
+ from tests.config import Config
10
+ from tests.config import get_default_config
11
+
12
+ DUMMY_EMBEDDING_DIMENSIONALITY = 10
13
+
14
+
15
+ @pytest.fixture(autouse=True)
16
+ def set_all_the_seeds(seed_value=0):
17
+ """Set all necessary seeds."""
18
+ os.environ['PYTHONHASHSEED'] = str(seed_value)
19
+ np.random.seed(seed_value)
20
+
21
+
22
+ @pytest.fixture()
23
+ def dummy_model() -> Callable:
24
+ """Get a dummy model that returns a random embedding for every input in a batch."""
25
+ return lambda x: np.random.randn(x.shape[0], DUMMY_EMBEDDING_DIMENSIONALITY)
26
+
27
+
28
+ @pytest.fixture
29
+ def dummy_data() -> tuple[ArrayLike, ArrayLike]:
30
+ """Get random dummy data."""
31
+ embedded_reference = np.random.randn(DUMMY_EMBEDDING_DIMENSIONALITY)
32
+ input_arr = np.random.random((32, 32, 3))
33
+ return embedded_reference, input_arr
34
+
35
+
36
+ def get_explainer(config: Config, axis_labels={2: 'channels'}, preprocess_function=None) -> DistanceExplainer:
37
+ """Get explainer object."""
38
+ explainer = DistanceExplainer(mask_selection_range_max=config.mask_selection_range_max,
39
+ mask_selection_range_min=config.mask_selection_range_min,
40
+ mask_selection_negative_range_max=config.mask_selection_negative_range_max,
41
+ mask_selection_negative_range_min=config.mask_selection_negative_range_min,
42
+ n_masks=config.number_of_masks,
43
+ axis_labels=axis_labels,
44
+ preprocess_function=preprocess_function,
45
+ feature_res=config.feature_res,
46
+ p_keep=config.p_keep)
47
+ return explainer
48
+
49
+
50
+ def test_distance_explainer_saliency(dummy_data: tuple[ArrayLike, ArrayLike],
51
+ dummy_model: Callable):
52
+ """Code output should be identical to recorded saliency."""
53
+ embedded_reference, input_arr = dummy_data
54
+ explainer = get_explainer(get_default_config())
55
+ expected_saliency, expected_value = np.load('./tests/test_data/test_dummy_data_exact_expected_output.npz').values()
56
+
57
+ saliency = explainer.explain_image_distance(dummy_model, input_arr, embedded_reference)
58
+
59
+ assert saliency.shape == (1,) + input_arr.shape[:2] + (1,) # Has correct shape
60
+ assert np.allclose(expected_saliency, saliency) # Has correct saliency
61
+
62
+
63
+ @pytest.mark.parametrize("empty_side,expected_tag",
64
+ [({"mask_selection_range_max": 0.}, "pos_empty"),
65
+ ({"mask_selection_negative_range_min": 1.}, "neg_empty")])
66
+ def test_distance_explainer_one_sided_saliency(dummy_data: tuple[ArrayLike, ArrayLike],
67
+ dummy_model: Callable,
68
+ empty_side: dict[str, float],
69
+ expected_tag: str):
70
+ """Code output should be identical to recorded saliency."""
71
+ embedded_reference, input_arr = dummy_data
72
+ expected_saliency, expected_value = np.load(
73
+ f'./tests/test_data/test_dummy_data_exact_expected_output_{expected_tag}.npz').values()
74
+ config = dataclasses.replace(get_default_config(), **empty_side)
75
+ explainer = get_explainer(config)
76
+
77
+ saliency = explainer.explain_image_distance(dummy_model, input_arr, embedded_reference)
78
+ assert saliency.shape == (1,) + input_arr.shape[:2] + (1,) # Has correct shape
79
+ assert np.allclose(expected_saliency, saliency) # Has correct saliency