explainiverse 0.7.0__py3-none-any.whl → 0.8.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.
- explainiverse/__init__.py +5 -4
- explainiverse/adapters/pytorch_adapter.py +88 -25
- explainiverse/core/explanation.py +165 -10
- explainiverse/core/registry.py +18 -0
- explainiverse/engine/suite.py +187 -78
- explainiverse/evaluation/metrics.py +189 -108
- explainiverse/explainers/attribution/lime_wrapper.py +90 -7
- explainiverse/explainers/attribution/shap_wrapper.py +104 -8
- explainiverse/explainers/gradient/__init__.py +3 -0
- explainiverse/explainers/gradient/integrated_gradients.py +189 -76
- explainiverse/explainers/gradient/lrp.py +1206 -0
- {explainiverse-0.7.0.dist-info → explainiverse-0.8.0.dist-info}/METADATA +76 -13
- {explainiverse-0.7.0.dist-info → explainiverse-0.8.0.dist-info}/RECORD +15 -14
- {explainiverse-0.7.0.dist-info → explainiverse-0.8.0.dist-info}/LICENSE +0 -0
- {explainiverse-0.7.0.dist-info → explainiverse-0.8.0.dist-info}/WHEEL +0 -0
explainiverse/__init__.py
CHANGED
|
@@ -2,9 +2,10 @@
|
|
|
2
2
|
"""
|
|
3
3
|
Explainiverse - A unified, extensible explainability framework.
|
|
4
4
|
|
|
5
|
-
Supports
|
|
6
|
-
|
|
7
|
-
|
|
5
|
+
Supports 18 state-of-the-art XAI methods including LIME, SHAP, TreeSHAP,
|
|
6
|
+
Integrated Gradients, DeepLIFT, DeepSHAP, LRP, GradCAM, TCAV, Anchors,
|
|
7
|
+
Counterfactuals, Permutation Importance, PDP, ALE, SAGE, and ProtoDash
|
|
8
|
+
through a consistent interface.
|
|
8
9
|
|
|
9
10
|
Quick Start:
|
|
10
11
|
from explainiverse import default_registry
|
|
@@ -33,7 +34,7 @@ from explainiverse.adapters.sklearn_adapter import SklearnAdapter
|
|
|
33
34
|
from explainiverse.adapters import TORCH_AVAILABLE
|
|
34
35
|
from explainiverse.engine.suite import ExplanationSuite
|
|
35
36
|
|
|
36
|
-
__version__ = "0.
|
|
37
|
+
__version__ = "0.8.0"
|
|
37
38
|
|
|
38
39
|
__all__ = [
|
|
39
40
|
# Core
|
|
@@ -25,7 +25,7 @@ Example:
|
|
|
25
25
|
"""
|
|
26
26
|
|
|
27
27
|
import numpy as np
|
|
28
|
-
from typing import List, Optional, Union,
|
|
28
|
+
from typing import List, Optional, Union, Tuple
|
|
29
29
|
|
|
30
30
|
from .base_adapter import BaseModelAdapter
|
|
31
31
|
|
|
@@ -57,6 +57,11 @@ class PyTorchAdapter(BaseModelAdapter):
|
|
|
57
57
|
explainability methods. Handles device management, tensor/numpy
|
|
58
58
|
conversions, and supports both classification and regression tasks.
|
|
59
59
|
|
|
60
|
+
Supports:
|
|
61
|
+
- Multi-class classification (output shape: [batch, n_classes])
|
|
62
|
+
- Binary classification (output shape: [batch, 1] or [batch])
|
|
63
|
+
- Regression (output shape: [batch, n_outputs] or [batch])
|
|
64
|
+
|
|
60
65
|
Attributes:
|
|
61
66
|
model: The PyTorch model (nn.Module)
|
|
62
67
|
task: "classification" or "regression"
|
|
@@ -150,11 +155,27 @@ class PyTorchAdapter(BaseModelAdapter):
|
|
|
150
155
|
def _apply_activation(self, output: "torch.Tensor") -> "torch.Tensor":
|
|
151
156
|
"""Apply output activation function."""
|
|
152
157
|
if self.output_activation == "softmax":
|
|
158
|
+
# Handle different output shapes
|
|
159
|
+
if output.dim() == 1 or (output.dim() == 2 and output.shape[1] == 1):
|
|
160
|
+
# Binary: apply sigmoid instead of softmax
|
|
161
|
+
return torch.sigmoid(output)
|
|
153
162
|
return torch.softmax(output, dim=-1)
|
|
154
163
|
elif self.output_activation == "sigmoid":
|
|
155
164
|
return torch.sigmoid(output)
|
|
156
165
|
return output
|
|
157
166
|
|
|
167
|
+
def _normalize_output_shape(self, output: "torch.Tensor") -> "torch.Tensor":
|
|
168
|
+
"""
|
|
169
|
+
Normalize output to consistent 2D shape (batch, outputs).
|
|
170
|
+
|
|
171
|
+
Handles:
|
|
172
|
+
- (batch,) -> (batch, 1)
|
|
173
|
+
- (batch, n) -> (batch, n)
|
|
174
|
+
"""
|
|
175
|
+
if output.dim() == 1:
|
|
176
|
+
return output.unsqueeze(-1)
|
|
177
|
+
return output
|
|
178
|
+
|
|
158
179
|
def predict(self, data: np.ndarray) -> np.ndarray:
|
|
159
180
|
"""
|
|
160
181
|
Generate predictions for input data.
|
|
@@ -183,16 +204,66 @@ class PyTorchAdapter(BaseModelAdapter):
|
|
|
183
204
|
tensor_batch = self._to_tensor(batch)
|
|
184
205
|
|
|
185
206
|
output = self.model(tensor_batch)
|
|
207
|
+
output = self._normalize_output_shape(output)
|
|
186
208
|
output = self._apply_activation(output)
|
|
187
209
|
outputs.append(self._to_numpy(output))
|
|
188
210
|
|
|
189
211
|
return np.vstack(outputs)
|
|
190
212
|
|
|
213
|
+
def _get_target_scores(
|
|
214
|
+
self,
|
|
215
|
+
output: "torch.Tensor",
|
|
216
|
+
target_class: Optional[Union[int, "torch.Tensor"]] = None
|
|
217
|
+
) -> "torch.Tensor":
|
|
218
|
+
"""
|
|
219
|
+
Extract target scores for gradient computation.
|
|
220
|
+
|
|
221
|
+
Handles both multi-class and binary classification outputs.
|
|
222
|
+
|
|
223
|
+
Args:
|
|
224
|
+
output: Raw model output (logits)
|
|
225
|
+
target_class: Target class index or tensor of indices
|
|
226
|
+
|
|
227
|
+
Returns:
|
|
228
|
+
Target scores tensor for backpropagation
|
|
229
|
+
"""
|
|
230
|
+
batch_size = output.shape[0]
|
|
231
|
+
|
|
232
|
+
# Normalize to 2D
|
|
233
|
+
if output.dim() == 1:
|
|
234
|
+
output = output.unsqueeze(-1)
|
|
235
|
+
|
|
236
|
+
n_outputs = output.shape[1]
|
|
237
|
+
|
|
238
|
+
if self.task == "classification":
|
|
239
|
+
if n_outputs == 1:
|
|
240
|
+
# Binary classification with single logit
|
|
241
|
+
# Score is the logit itself (positive class score)
|
|
242
|
+
return output.squeeze(-1)
|
|
243
|
+
else:
|
|
244
|
+
# Multi-class classification
|
|
245
|
+
if target_class is None:
|
|
246
|
+
target_class = output.argmax(dim=-1)
|
|
247
|
+
elif isinstance(target_class, int):
|
|
248
|
+
target_class = torch.tensor(
|
|
249
|
+
[target_class] * batch_size,
|
|
250
|
+
device=self.device
|
|
251
|
+
)
|
|
252
|
+
|
|
253
|
+
# Gather scores for target class
|
|
254
|
+
return output.gather(1, target_class.view(-1, 1)).squeeze(-1)
|
|
255
|
+
else:
|
|
256
|
+
# Regression: use first output or sum of outputs
|
|
257
|
+
if n_outputs == 1:
|
|
258
|
+
return output.squeeze(-1)
|
|
259
|
+
else:
|
|
260
|
+
return output.sum(dim=-1)
|
|
261
|
+
|
|
191
262
|
def predict_with_gradients(
|
|
192
263
|
self,
|
|
193
264
|
data: np.ndarray,
|
|
194
265
|
target_class: Optional[int] = None
|
|
195
|
-
) ->
|
|
266
|
+
) -> Tuple[np.ndarray, np.ndarray]:
|
|
196
267
|
"""
|
|
197
268
|
Generate predictions and compute gradients w.r.t. inputs.
|
|
198
269
|
|
|
@@ -203,11 +274,17 @@ class PyTorchAdapter(BaseModelAdapter):
|
|
|
203
274
|
data: Input data as numpy array.
|
|
204
275
|
target_class: Class index for gradient computation.
|
|
205
276
|
If None, uses the predicted class.
|
|
277
|
+
For binary classification with single output,
|
|
278
|
+
this is ignored (gradient w.r.t. the single logit).
|
|
206
279
|
|
|
207
280
|
Returns:
|
|
208
281
|
Tuple of (predictions, gradients) as numpy arrays.
|
|
282
|
+
- predictions: (batch, n_classes) probabilities
|
|
283
|
+
- gradients: same shape as input data
|
|
209
284
|
"""
|
|
210
285
|
data = np.array(data)
|
|
286
|
+
original_shape = data.shape
|
|
287
|
+
|
|
211
288
|
if data.ndim == 1:
|
|
212
289
|
data = data.reshape(1, -1)
|
|
213
290
|
|
|
@@ -217,20 +294,13 @@ class PyTorchAdapter(BaseModelAdapter):
|
|
|
217
294
|
|
|
218
295
|
# Forward pass
|
|
219
296
|
output = self.model(tensor_data)
|
|
220
|
-
activated_output = self._apply_activation(output)
|
|
221
297
|
|
|
222
|
-
#
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
# Select target class scores for gradient
|
|
230
|
-
target_scores = output.gather(1, target_class.view(-1, 1)).squeeze()
|
|
231
|
-
else:
|
|
232
|
-
# Regression: gradient w.r.t. output
|
|
233
|
-
target_scores = output.squeeze()
|
|
298
|
+
# Get activated output for return
|
|
299
|
+
output_normalized = self._normalize_output_shape(output)
|
|
300
|
+
activated_output = self._apply_activation(output_normalized)
|
|
301
|
+
|
|
302
|
+
# Get target scores for gradient computation
|
|
303
|
+
target_scores = self._get_target_scores(output, target_class)
|
|
234
304
|
|
|
235
305
|
# Backward pass
|
|
236
306
|
if target_scores.dim() == 0:
|
|
@@ -295,7 +365,7 @@ class PyTorchAdapter(BaseModelAdapter):
|
|
|
295
365
|
data: np.ndarray,
|
|
296
366
|
layer_name: str,
|
|
297
367
|
target_class: Optional[int] = None
|
|
298
|
-
) ->
|
|
368
|
+
) -> Tuple[np.ndarray, np.ndarray]:
|
|
299
369
|
"""
|
|
300
370
|
Get gradients of output w.r.t. a specific layer's activations.
|
|
301
371
|
|
|
@@ -339,15 +409,8 @@ class PyTorchAdapter(BaseModelAdapter):
|
|
|
339
409
|
|
|
340
410
|
output = self.model(tensor_data)
|
|
341
411
|
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
target_class = output.argmax(dim=-1)
|
|
345
|
-
elif isinstance(target_class, int):
|
|
346
|
-
target_class = torch.tensor([target_class] * data.shape[0], device=self.device)
|
|
347
|
-
|
|
348
|
-
target_scores = output.gather(1, target_class.view(-1, 1)).squeeze()
|
|
349
|
-
else:
|
|
350
|
-
target_scores = output.squeeze()
|
|
412
|
+
# Get target scores using the new method
|
|
413
|
+
target_scores = self._get_target_scores(output, target_class)
|
|
351
414
|
|
|
352
415
|
if target_scores.dim() == 0:
|
|
353
416
|
target_scores.backward()
|
|
@@ -1,24 +1,179 @@
|
|
|
1
1
|
# src/explainiverse/core/explanation.py
|
|
2
|
+
"""
|
|
3
|
+
Unified container for explanation results.
|
|
4
|
+
|
|
5
|
+
The Explanation class provides a standardized format for all explainer outputs,
|
|
6
|
+
enabling consistent handling across different explanation methods.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from typing import Dict, List, Optional, Any
|
|
10
|
+
|
|
2
11
|
|
|
3
12
|
class Explanation:
|
|
4
13
|
"""
|
|
5
14
|
Unified container for explanation results.
|
|
15
|
+
|
|
16
|
+
Attributes:
|
|
17
|
+
explainer_name: Name of the explainer that generated this explanation
|
|
18
|
+
target_class: The class/output being explained
|
|
19
|
+
explanation_data: Dictionary containing explanation details
|
|
20
|
+
(e.g., feature_attributions, heatmaps, rules)
|
|
21
|
+
feature_names: Optional list of feature names for index resolution
|
|
22
|
+
metadata: Optional additional metadata about the explanation
|
|
23
|
+
|
|
24
|
+
Example:
|
|
25
|
+
>>> explanation = Explanation(
|
|
26
|
+
... explainer_name="LIME",
|
|
27
|
+
... target_class="cat",
|
|
28
|
+
... explanation_data={"feature_attributions": {"fur": 0.8, "whiskers": 0.6}},
|
|
29
|
+
... feature_names=["fur", "whiskers", "tail", "ears"]
|
|
30
|
+
... )
|
|
31
|
+
>>> print(explanation.get_top_features(k=2))
|
|
32
|
+
[('fur', 0.8), ('whiskers', 0.6)]
|
|
6
33
|
"""
|
|
7
34
|
|
|
8
|
-
def __init__(
|
|
35
|
+
def __init__(
|
|
36
|
+
self,
|
|
37
|
+
explainer_name: str,
|
|
38
|
+
target_class: str,
|
|
39
|
+
explanation_data: Dict[str, Any],
|
|
40
|
+
feature_names: Optional[List[str]] = None,
|
|
41
|
+
metadata: Optional[Dict[str, Any]] = None
|
|
42
|
+
):
|
|
43
|
+
"""
|
|
44
|
+
Initialize an Explanation object.
|
|
45
|
+
|
|
46
|
+
Args:
|
|
47
|
+
explainer_name: Name of the explainer (e.g., "LIME", "SHAP")
|
|
48
|
+
target_class: The target class or output being explained
|
|
49
|
+
explanation_data: Dictionary containing the explanation details.
|
|
50
|
+
Common keys include:
|
|
51
|
+
- "feature_attributions": Dict[str, float] mapping feature names to importance
|
|
52
|
+
- "attributions_raw": List[float] of raw attribution values
|
|
53
|
+
- "heatmap": np.ndarray for image explanations
|
|
54
|
+
- "rules": List of rule strings for rule-based explanations
|
|
55
|
+
feature_names: Optional list of feature names. If provided, enables
|
|
56
|
+
index-based lookup in evaluation metrics.
|
|
57
|
+
metadata: Optional additional metadata (e.g., computation time, parameters)
|
|
58
|
+
"""
|
|
9
59
|
self.explainer_name = explainer_name
|
|
10
60
|
self.target_class = target_class
|
|
11
|
-
self.explanation_data = explanation_data
|
|
61
|
+
self.explanation_data = explanation_data
|
|
62
|
+
self.feature_names = list(feature_names) if feature_names is not None else None
|
|
63
|
+
self.metadata = metadata or {}
|
|
12
64
|
|
|
13
65
|
def __repr__(self):
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
66
|
+
n_features = len(self.feature_names) if self.feature_names else "N/A"
|
|
67
|
+
return (
|
|
68
|
+
f"Explanation(explainer='{self.explainer_name}', "
|
|
69
|
+
f"target='{self.target_class}', "
|
|
70
|
+
f"keys={list(self.explanation_data.keys())}, "
|
|
71
|
+
f"n_features={n_features})"
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
def get_attributions(self) -> Optional[Dict[str, float]]:
|
|
75
|
+
"""
|
|
76
|
+
Get feature attributions if available.
|
|
77
|
+
|
|
78
|
+
Returns:
|
|
79
|
+
Dictionary mapping feature names to attribution values,
|
|
80
|
+
or None if not available.
|
|
81
|
+
"""
|
|
82
|
+
return self.explanation_data.get("feature_attributions")
|
|
83
|
+
|
|
84
|
+
def get_top_features(self, k: int = 5, absolute: bool = True) -> List[tuple]:
|
|
85
|
+
"""
|
|
86
|
+
Get the top-k most important features.
|
|
87
|
+
|
|
88
|
+
Args:
|
|
89
|
+
k: Number of top features to return
|
|
90
|
+
absolute: If True, rank by absolute value of attribution
|
|
91
|
+
|
|
92
|
+
Returns:
|
|
93
|
+
List of (feature_name, attribution_value) tuples sorted by importance
|
|
94
|
+
"""
|
|
95
|
+
attributions = self.get_attributions()
|
|
96
|
+
if not attributions:
|
|
97
|
+
return []
|
|
98
|
+
|
|
99
|
+
if absolute:
|
|
100
|
+
sorted_items = sorted(
|
|
101
|
+
attributions.items(),
|
|
102
|
+
key=lambda x: abs(x[1]),
|
|
103
|
+
reverse=True
|
|
104
|
+
)
|
|
105
|
+
else:
|
|
106
|
+
sorted_items = sorted(
|
|
107
|
+
attributions.items(),
|
|
108
|
+
key=lambda x: x[1],
|
|
109
|
+
reverse=True
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
return sorted_items[:k]
|
|
113
|
+
|
|
114
|
+
def get_feature_index(self, feature_name: str) -> Optional[int]:
|
|
115
|
+
"""
|
|
116
|
+
Get the index of a feature by name.
|
|
117
|
+
|
|
118
|
+
Args:
|
|
119
|
+
feature_name: Name of the feature
|
|
120
|
+
|
|
121
|
+
Returns:
|
|
122
|
+
Index of the feature, or None if not found or feature_names not set
|
|
123
|
+
"""
|
|
124
|
+
if self.feature_names is None:
|
|
125
|
+
return None
|
|
126
|
+
try:
|
|
127
|
+
return self.feature_names.index(feature_name)
|
|
128
|
+
except ValueError:
|
|
129
|
+
return None
|
|
17
130
|
|
|
18
|
-
def plot(self,
|
|
131
|
+
def plot(self, plot_type: str = 'bar', **kwargs):
|
|
132
|
+
"""
|
|
133
|
+
Visualize the explanation.
|
|
134
|
+
|
|
135
|
+
Args:
|
|
136
|
+
plot_type: Type of plot ('bar', 'waterfall', 'heatmap')
|
|
137
|
+
**kwargs: Additional arguments passed to the plotting function
|
|
138
|
+
|
|
139
|
+
Note:
|
|
140
|
+
This is a placeholder for future visualization integration.
|
|
141
|
+
"""
|
|
142
|
+
print(
|
|
143
|
+
f"[plot: {plot_type}] Plotting explanation for {self.target_class} "
|
|
144
|
+
f"from {self.explainer_name}."
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
148
|
+
"""
|
|
149
|
+
Convert explanation to a dictionary for serialization.
|
|
150
|
+
|
|
151
|
+
Returns:
|
|
152
|
+
Dictionary representation of the explanation
|
|
153
|
+
"""
|
|
154
|
+
return {
|
|
155
|
+
"explainer_name": self.explainer_name,
|
|
156
|
+
"target_class": self.target_class,
|
|
157
|
+
"explanation_data": self.explanation_data,
|
|
158
|
+
"feature_names": self.feature_names,
|
|
159
|
+
"metadata": self.metadata
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
@classmethod
|
|
163
|
+
def from_dict(cls, data: Dict[str, Any]) -> "Explanation":
|
|
19
164
|
"""
|
|
20
|
-
|
|
21
|
-
|
|
165
|
+
Create an Explanation from a dictionary.
|
|
166
|
+
|
|
167
|
+
Args:
|
|
168
|
+
data: Dictionary with explanation data
|
|
169
|
+
|
|
170
|
+
Returns:
|
|
171
|
+
Explanation instance
|
|
22
172
|
"""
|
|
23
|
-
|
|
24
|
-
|
|
173
|
+
return cls(
|
|
174
|
+
explainer_name=data["explainer_name"],
|
|
175
|
+
target_class=data["target_class"],
|
|
176
|
+
explanation_data=data["explanation_data"],
|
|
177
|
+
feature_names=data.get("feature_names"),
|
|
178
|
+
metadata=data.get("metadata", {})
|
|
179
|
+
)
|
explainiverse/core/registry.py
CHANGED
|
@@ -375,6 +375,7 @@ def _create_default_registry() -> ExplainerRegistry:
|
|
|
375
375
|
from explainiverse.explainers.gradient.smoothgrad import SmoothGradExplainer
|
|
376
376
|
from explainiverse.explainers.gradient.saliency import SaliencyExplainer
|
|
377
377
|
from explainiverse.explainers.gradient.tcav import TCAVExplainer
|
|
378
|
+
from explainiverse.explainers.gradient.lrp import LRPExplainer
|
|
378
379
|
from explainiverse.explainers.example_based.protodash import ProtoDashExplainer
|
|
379
380
|
|
|
380
381
|
registry = ExplainerRegistry()
|
|
@@ -587,6 +588,23 @@ def _create_default_registry() -> ExplainerRegistry:
|
|
|
587
588
|
)
|
|
588
589
|
)
|
|
589
590
|
|
|
591
|
+
# Register LRP (Layer-wise Relevance Propagation)
|
|
592
|
+
registry.register(
|
|
593
|
+
name="lrp",
|
|
594
|
+
explainer_class=LRPExplainer,
|
|
595
|
+
meta=ExplainerMeta(
|
|
596
|
+
scope="local",
|
|
597
|
+
model_types=["neural"],
|
|
598
|
+
data_types=["tabular", "image"],
|
|
599
|
+
task_types=["classification", "regression"],
|
|
600
|
+
description="LRP - Layer-wise Relevance Propagation for decomposition-based attributions (requires PyTorch)",
|
|
601
|
+
paper_reference="Bach et al., 2015 - 'On Pixel-wise Explanations for Non-Linear Classifier Decisions by Layer-wise Relevance Propagation' (PLOS ONE)",
|
|
602
|
+
complexity="O(n_layers * forward_pass)",
|
|
603
|
+
requires_training_data=False,
|
|
604
|
+
supports_batching=True
|
|
605
|
+
)
|
|
606
|
+
)
|
|
607
|
+
|
|
590
608
|
# =========================================================================
|
|
591
609
|
# Global Explainers (model-level)
|
|
592
610
|
# =========================================================================
|