explainiverse 0.2.2__py3-none-any.whl → 0.2.3__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 +1 -1
- explainiverse/core/registry.py +18 -0
- explainiverse/explainers/__init__.py +3 -0
- explainiverse/explainers/gradient/__init__.py +11 -0
- explainiverse/explainers/gradient/integrated_gradients.py +348 -0
- {explainiverse-0.2.2.dist-info → explainiverse-0.2.3.dist-info}/METADATA +34 -7
- {explainiverse-0.2.2.dist-info → explainiverse-0.2.3.dist-info}/RECORD +9 -7
- {explainiverse-0.2.2.dist-info → explainiverse-0.2.3.dist-info}/LICENSE +0 -0
- {explainiverse-0.2.2.dist-info → explainiverse-0.2.3.dist-info}/WHEEL +0 -0
explainiverse/__init__.py
CHANGED
explainiverse/core/registry.py
CHANGED
|
@@ -369,6 +369,7 @@ def _create_default_registry() -> ExplainerRegistry:
|
|
|
369
369
|
from explainiverse.explainers.global_explainers.ale import ALEExplainer
|
|
370
370
|
from explainiverse.explainers.global_explainers.sage import SAGEExplainer
|
|
371
371
|
from explainiverse.explainers.counterfactual.dice_wrapper import CounterfactualExplainer
|
|
372
|
+
from explainiverse.explainers.gradient.integrated_gradients import IntegratedGradientsExplainer
|
|
372
373
|
|
|
373
374
|
registry = ExplainerRegistry()
|
|
374
375
|
|
|
@@ -461,6 +462,23 @@ def _create_default_registry() -> ExplainerRegistry:
|
|
|
461
462
|
)
|
|
462
463
|
)
|
|
463
464
|
|
|
465
|
+
# Register Integrated Gradients (for neural networks)
|
|
466
|
+
registry.register(
|
|
467
|
+
name="integrated_gradients",
|
|
468
|
+
explainer_class=IntegratedGradientsExplainer,
|
|
469
|
+
meta=ExplainerMeta(
|
|
470
|
+
scope="local",
|
|
471
|
+
model_types=["neural"],
|
|
472
|
+
data_types=["tabular", "image"],
|
|
473
|
+
task_types=["classification", "regression"],
|
|
474
|
+
description="Integrated Gradients - axiomatic attributions for neural networks (requires PyTorch)",
|
|
475
|
+
paper_reference="Sundararajan et al., 2017 - 'Axiomatic Attribution for Deep Networks' (ICML)",
|
|
476
|
+
complexity="O(n_steps * forward_pass)",
|
|
477
|
+
requires_training_data=False,
|
|
478
|
+
supports_batching=True
|
|
479
|
+
)
|
|
480
|
+
)
|
|
481
|
+
|
|
464
482
|
# =========================================================================
|
|
465
483
|
# Global Explainers (model-level)
|
|
466
484
|
# =========================================================================
|
|
@@ -8,6 +8,7 @@ Local Explainers (instance-level):
|
|
|
8
8
|
- TreeSHAP: Optimized exact SHAP for tree-based models
|
|
9
9
|
- Anchors: High-precision rule-based explanations
|
|
10
10
|
- Counterfactual: Diverse counterfactual explanations
|
|
11
|
+
- Integrated Gradients: Gradient-based attributions for neural networks
|
|
11
12
|
|
|
12
13
|
Global Explainers (model-level):
|
|
13
14
|
- Permutation Importance: Feature importance via permutation
|
|
@@ -25,6 +26,7 @@ from explainiverse.explainers.global_explainers.permutation_importance import Pe
|
|
|
25
26
|
from explainiverse.explainers.global_explainers.partial_dependence import PartialDependenceExplainer
|
|
26
27
|
from explainiverse.explainers.global_explainers.ale import ALEExplainer
|
|
27
28
|
from explainiverse.explainers.global_explainers.sage import SAGEExplainer
|
|
29
|
+
from explainiverse.explainers.gradient.integrated_gradients import IntegratedGradientsExplainer
|
|
28
30
|
|
|
29
31
|
__all__ = [
|
|
30
32
|
# Local explainers
|
|
@@ -33,6 +35,7 @@ __all__ = [
|
|
|
33
35
|
"TreeShapExplainer",
|
|
34
36
|
"AnchorsExplainer",
|
|
35
37
|
"CounterfactualExplainer",
|
|
38
|
+
"IntegratedGradientsExplainer",
|
|
36
39
|
# Global explainers
|
|
37
40
|
"PermutationImportanceExplainer",
|
|
38
41
|
"PartialDependenceExplainer",
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# src/explainiverse/explainers/gradient/__init__.py
|
|
2
|
+
"""
|
|
3
|
+
Gradient-based explainers for neural networks.
|
|
4
|
+
|
|
5
|
+
These explainers require models that support gradient computation,
|
|
6
|
+
typically via the PyTorchAdapter.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from explainiverse.explainers.gradient.integrated_gradients import IntegratedGradientsExplainer
|
|
10
|
+
|
|
11
|
+
__all__ = ["IntegratedGradientsExplainer"]
|
|
@@ -0,0 +1,348 @@
|
|
|
1
|
+
# src/explainiverse/explainers/gradient/integrated_gradients.py
|
|
2
|
+
"""
|
|
3
|
+
Integrated Gradients - Axiomatic Attribution for Deep Networks.
|
|
4
|
+
|
|
5
|
+
Integrated Gradients computes feature attributions by accumulating gradients
|
|
6
|
+
along a straight-line path from a baseline to the input. It satisfies two
|
|
7
|
+
key axioms:
|
|
8
|
+
- Sensitivity: If a feature differs between input and baseline and changes
|
|
9
|
+
the prediction, it receives non-zero attribution.
|
|
10
|
+
- Implementation Invariance: Attributions are identical for functionally
|
|
11
|
+
equivalent networks.
|
|
12
|
+
|
|
13
|
+
Reference:
|
|
14
|
+
Sundararajan, M., Taly, A., & Yan, Q. (2017). Axiomatic Attribution for
|
|
15
|
+
Deep Networks. ICML 2017. https://arxiv.org/abs/1703.01365
|
|
16
|
+
|
|
17
|
+
Example:
|
|
18
|
+
from explainiverse.explainers.gradient import IntegratedGradientsExplainer
|
|
19
|
+
from explainiverse.adapters import PyTorchAdapter
|
|
20
|
+
|
|
21
|
+
adapter = PyTorchAdapter(model, task="classification")
|
|
22
|
+
|
|
23
|
+
explainer = IntegratedGradientsExplainer(
|
|
24
|
+
model=adapter,
|
|
25
|
+
feature_names=feature_names,
|
|
26
|
+
n_steps=50
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
explanation = explainer.explain(instance)
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
import numpy as np
|
|
33
|
+
from typing import List, Optional, Union, Callable
|
|
34
|
+
|
|
35
|
+
from explainiverse.core.explainer import BaseExplainer
|
|
36
|
+
from explainiverse.core.explanation import Explanation
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class IntegratedGradientsExplainer(BaseExplainer):
|
|
40
|
+
"""
|
|
41
|
+
Integrated Gradients explainer for neural networks.
|
|
42
|
+
|
|
43
|
+
Computes attributions by integrating gradients along the path from
|
|
44
|
+
a baseline (default: zero vector) to the input. The integral is
|
|
45
|
+
approximated using the Riemann sum.
|
|
46
|
+
|
|
47
|
+
Attributes:
|
|
48
|
+
model: Model adapter with predict_with_gradients() method
|
|
49
|
+
feature_names: List of feature names
|
|
50
|
+
class_names: List of class names (for classification)
|
|
51
|
+
n_steps: Number of steps for integral approximation
|
|
52
|
+
baseline: Baseline input (default: zeros)
|
|
53
|
+
method: Integration method ("riemann_middle", "riemann_left", "riemann_right", "riemann_trapezoid")
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
def __init__(
|
|
57
|
+
self,
|
|
58
|
+
model,
|
|
59
|
+
feature_names: List[str],
|
|
60
|
+
class_names: Optional[List[str]] = None,
|
|
61
|
+
n_steps: int = 50,
|
|
62
|
+
baseline: Optional[np.ndarray] = None,
|
|
63
|
+
method: str = "riemann_middle"
|
|
64
|
+
):
|
|
65
|
+
"""
|
|
66
|
+
Initialize the Integrated Gradients explainer.
|
|
67
|
+
|
|
68
|
+
Args:
|
|
69
|
+
model: A model adapter with predict_with_gradients() method.
|
|
70
|
+
Use PyTorchAdapter for PyTorch models.
|
|
71
|
+
feature_names: List of input feature names.
|
|
72
|
+
class_names: List of class names (for classification tasks).
|
|
73
|
+
n_steps: Number of steps for approximating the integral.
|
|
74
|
+
More steps = more accurate but slower. Default: 50.
|
|
75
|
+
baseline: Baseline input for comparison. If None, uses zeros.
|
|
76
|
+
Can also be "random" for random baseline or a callable.
|
|
77
|
+
method: Integration method:
|
|
78
|
+
- "riemann_middle": Middle Riemann sum (default, most accurate)
|
|
79
|
+
- "riemann_left": Left Riemann sum
|
|
80
|
+
- "riemann_right": Right Riemann sum
|
|
81
|
+
- "riemann_trapezoid": Trapezoidal rule
|
|
82
|
+
"""
|
|
83
|
+
super().__init__(model)
|
|
84
|
+
|
|
85
|
+
# Validate model has gradient capability
|
|
86
|
+
if not hasattr(model, 'predict_with_gradients'):
|
|
87
|
+
raise TypeError(
|
|
88
|
+
"Model adapter must have predict_with_gradients() method. "
|
|
89
|
+
"Use PyTorchAdapter for PyTorch models."
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
self.feature_names = list(feature_names)
|
|
93
|
+
self.class_names = list(class_names) if class_names else None
|
|
94
|
+
self.n_steps = n_steps
|
|
95
|
+
self.baseline = baseline
|
|
96
|
+
self.method = method
|
|
97
|
+
|
|
98
|
+
def _get_baseline(self, instance: np.ndarray) -> np.ndarray:
|
|
99
|
+
"""Get the baseline for a given input shape."""
|
|
100
|
+
if self.baseline is None:
|
|
101
|
+
# Default: zero baseline
|
|
102
|
+
return np.zeros_like(instance)
|
|
103
|
+
elif isinstance(self.baseline, str) and self.baseline == "random":
|
|
104
|
+
# Random baseline (useful for images)
|
|
105
|
+
return np.random.uniform(
|
|
106
|
+
low=instance.min(),
|
|
107
|
+
high=instance.max(),
|
|
108
|
+
size=instance.shape
|
|
109
|
+
).astype(instance.dtype)
|
|
110
|
+
elif callable(self.baseline):
|
|
111
|
+
return self.baseline(instance)
|
|
112
|
+
else:
|
|
113
|
+
return np.array(self.baseline).reshape(instance.shape)
|
|
114
|
+
|
|
115
|
+
def _get_interpolation_alphas(self) -> np.ndarray:
|
|
116
|
+
"""Get interpolation points based on method."""
|
|
117
|
+
if self.method == "riemann_left":
|
|
118
|
+
return np.linspace(0, 1 - 1/self.n_steps, self.n_steps)
|
|
119
|
+
elif self.method == "riemann_right":
|
|
120
|
+
return np.linspace(1/self.n_steps, 1, self.n_steps)
|
|
121
|
+
elif self.method == "riemann_middle":
|
|
122
|
+
return np.linspace(0.5/self.n_steps, 1 - 0.5/self.n_steps, self.n_steps)
|
|
123
|
+
elif self.method == "riemann_trapezoid":
|
|
124
|
+
return np.linspace(0, 1, self.n_steps + 1)
|
|
125
|
+
else:
|
|
126
|
+
raise ValueError(f"Unknown method: {self.method}")
|
|
127
|
+
|
|
128
|
+
def _compute_integrated_gradients(
|
|
129
|
+
self,
|
|
130
|
+
instance: np.ndarray,
|
|
131
|
+
baseline: np.ndarray,
|
|
132
|
+
target_class: Optional[int] = None
|
|
133
|
+
) -> np.ndarray:
|
|
134
|
+
"""
|
|
135
|
+
Compute integrated gradients for a single instance.
|
|
136
|
+
|
|
137
|
+
The integral is approximated as:
|
|
138
|
+
IG_i = (x_i - x'_i) * sum_{k=1}^{m} grad_i(x' + k/m * (x - x')) / m
|
|
139
|
+
|
|
140
|
+
where x is the input, x' is the baseline, and m is n_steps.
|
|
141
|
+
"""
|
|
142
|
+
# Get interpolation points
|
|
143
|
+
alphas = self._get_interpolation_alphas()
|
|
144
|
+
|
|
145
|
+
# Compute path from baseline to input
|
|
146
|
+
# Shape: (n_steps, n_features)
|
|
147
|
+
delta = instance - baseline
|
|
148
|
+
interpolated_inputs = baseline + alphas[:, np.newaxis] * delta
|
|
149
|
+
|
|
150
|
+
# Compute gradients at each interpolation point
|
|
151
|
+
all_gradients = []
|
|
152
|
+
for interp_input in interpolated_inputs:
|
|
153
|
+
_, gradients = self.model.predict_with_gradients(
|
|
154
|
+
interp_input.reshape(1, -1),
|
|
155
|
+
target_class=target_class
|
|
156
|
+
)
|
|
157
|
+
all_gradients.append(gradients.flatten())
|
|
158
|
+
|
|
159
|
+
all_gradients = np.array(all_gradients) # Shape: (n_steps, n_features)
|
|
160
|
+
|
|
161
|
+
# Approximate the integral
|
|
162
|
+
if self.method == "riemann_trapezoid":
|
|
163
|
+
# Trapezoidal rule: (f(0) + 2*f(1) + ... + 2*f(n-1) + f(n)) / (2n)
|
|
164
|
+
weights = np.ones(self.n_steps + 1)
|
|
165
|
+
weights[0] = 0.5
|
|
166
|
+
weights[-1] = 0.5
|
|
167
|
+
avg_gradients = np.average(all_gradients, axis=0, weights=weights)
|
|
168
|
+
else:
|
|
169
|
+
# Standard Riemann sum: average of gradients
|
|
170
|
+
avg_gradients = np.mean(all_gradients, axis=0)
|
|
171
|
+
|
|
172
|
+
# Scale by input - baseline difference
|
|
173
|
+
integrated_gradients = delta * avg_gradients
|
|
174
|
+
|
|
175
|
+
return integrated_gradients
|
|
176
|
+
|
|
177
|
+
def explain(
|
|
178
|
+
self,
|
|
179
|
+
instance: np.ndarray,
|
|
180
|
+
target_class: Optional[int] = None,
|
|
181
|
+
baseline: Optional[np.ndarray] = None,
|
|
182
|
+
return_convergence_delta: bool = False
|
|
183
|
+
) -> Explanation:
|
|
184
|
+
"""
|
|
185
|
+
Generate Integrated Gradients explanation for an instance.
|
|
186
|
+
|
|
187
|
+
Args:
|
|
188
|
+
instance: 1D numpy array of input features.
|
|
189
|
+
target_class: For classification, which class to explain.
|
|
190
|
+
If None, uses the predicted class.
|
|
191
|
+
baseline: Override the default baseline for this explanation.
|
|
192
|
+
return_convergence_delta: If True, include the convergence delta
|
|
193
|
+
(difference between sum of attributions
|
|
194
|
+
and prediction difference).
|
|
195
|
+
|
|
196
|
+
Returns:
|
|
197
|
+
Explanation object with feature attributions.
|
|
198
|
+
"""
|
|
199
|
+
instance = np.array(instance).flatten().astype(np.float32)
|
|
200
|
+
|
|
201
|
+
# Get baseline
|
|
202
|
+
if baseline is not None:
|
|
203
|
+
bl = np.array(baseline).flatten().astype(np.float32)
|
|
204
|
+
else:
|
|
205
|
+
bl = self._get_baseline(instance)
|
|
206
|
+
|
|
207
|
+
# Determine target class if not specified
|
|
208
|
+
if target_class is None and self.class_names:
|
|
209
|
+
predictions = self.model.predict(instance.reshape(1, -1))
|
|
210
|
+
target_class = int(np.argmax(predictions))
|
|
211
|
+
|
|
212
|
+
# Compute integrated gradients
|
|
213
|
+
ig_attributions = self._compute_integrated_gradients(
|
|
214
|
+
instance, bl, target_class
|
|
215
|
+
)
|
|
216
|
+
|
|
217
|
+
# Build attributions dict
|
|
218
|
+
attributions = {
|
|
219
|
+
fname: float(ig_attributions[i])
|
|
220
|
+
for i, fname in enumerate(self.feature_names)
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
# Determine class name
|
|
224
|
+
if self.class_names and target_class is not None:
|
|
225
|
+
label_name = self.class_names[target_class]
|
|
226
|
+
else:
|
|
227
|
+
label_name = f"class_{target_class}" if target_class is not None else "output"
|
|
228
|
+
|
|
229
|
+
explanation_data = {
|
|
230
|
+
"feature_attributions": attributions,
|
|
231
|
+
"attributions_raw": ig_attributions.tolist(),
|
|
232
|
+
"baseline": bl.tolist(),
|
|
233
|
+
"n_steps": self.n_steps,
|
|
234
|
+
"method": self.method
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
# Optionally compute convergence delta
|
|
238
|
+
if return_convergence_delta:
|
|
239
|
+
# The sum of attributions should equal F(x) - F(baseline)
|
|
240
|
+
pred_input = self.model.predict(instance.reshape(1, -1))
|
|
241
|
+
pred_baseline = self.model.predict(bl.reshape(1, -1))
|
|
242
|
+
|
|
243
|
+
if target_class is not None:
|
|
244
|
+
pred_diff = pred_input[0, target_class] - pred_baseline[0, target_class]
|
|
245
|
+
else:
|
|
246
|
+
pred_diff = pred_input[0, 0] - pred_baseline[0, 0]
|
|
247
|
+
|
|
248
|
+
attribution_sum = np.sum(ig_attributions)
|
|
249
|
+
convergence_delta = abs(pred_diff - attribution_sum)
|
|
250
|
+
|
|
251
|
+
explanation_data["convergence_delta"] = float(convergence_delta)
|
|
252
|
+
explanation_data["prediction_difference"] = float(pred_diff)
|
|
253
|
+
explanation_data["attribution_sum"] = float(attribution_sum)
|
|
254
|
+
|
|
255
|
+
return Explanation(
|
|
256
|
+
explainer_name="IntegratedGradients",
|
|
257
|
+
target_class=label_name,
|
|
258
|
+
explanation_data=explanation_data
|
|
259
|
+
)
|
|
260
|
+
|
|
261
|
+
def explain_batch(
|
|
262
|
+
self,
|
|
263
|
+
X: np.ndarray,
|
|
264
|
+
target_class: Optional[int] = None
|
|
265
|
+
) -> List[Explanation]:
|
|
266
|
+
"""
|
|
267
|
+
Generate explanations for multiple instances.
|
|
268
|
+
|
|
269
|
+
Note: This is not optimized for batching - it processes
|
|
270
|
+
instances sequentially. For large batches, consider using
|
|
271
|
+
the batched gradient computation in a custom implementation.
|
|
272
|
+
|
|
273
|
+
Args:
|
|
274
|
+
X: 2D numpy array of instances (n_samples, n_features).
|
|
275
|
+
target_class: Target class for all instances.
|
|
276
|
+
|
|
277
|
+
Returns:
|
|
278
|
+
List of Explanation objects.
|
|
279
|
+
"""
|
|
280
|
+
X = np.array(X)
|
|
281
|
+
if X.ndim == 1:
|
|
282
|
+
X = X.reshape(1, -1)
|
|
283
|
+
|
|
284
|
+
return [
|
|
285
|
+
self.explain(X[i], target_class=target_class)
|
|
286
|
+
for i in range(X.shape[0])
|
|
287
|
+
]
|
|
288
|
+
|
|
289
|
+
def compute_attributions_with_noise(
|
|
290
|
+
self,
|
|
291
|
+
instance: np.ndarray,
|
|
292
|
+
target_class: Optional[int] = None,
|
|
293
|
+
n_samples: int = 5,
|
|
294
|
+
noise_scale: float = 0.1
|
|
295
|
+
) -> Explanation:
|
|
296
|
+
"""
|
|
297
|
+
Compute attributions averaged over noisy baselines (SmoothGrad-style).
|
|
298
|
+
|
|
299
|
+
This can help reduce noise in the attributions by averaging over
|
|
300
|
+
multiple baselines sampled around the zero baseline.
|
|
301
|
+
|
|
302
|
+
Args:
|
|
303
|
+
instance: Input instance.
|
|
304
|
+
target_class: Target class for attribution.
|
|
305
|
+
n_samples: Number of noisy baselines to average.
|
|
306
|
+
noise_scale: Standard deviation of Gaussian noise.
|
|
307
|
+
|
|
308
|
+
Returns:
|
|
309
|
+
Explanation with averaged attributions.
|
|
310
|
+
"""
|
|
311
|
+
instance = np.array(instance).flatten().astype(np.float32)
|
|
312
|
+
|
|
313
|
+
all_attributions = []
|
|
314
|
+
for _ in range(n_samples):
|
|
315
|
+
# Create noisy baseline
|
|
316
|
+
noise = np.random.normal(0, noise_scale, instance.shape).astype(np.float32)
|
|
317
|
+
noisy_baseline = noise # Noise around zero
|
|
318
|
+
|
|
319
|
+
ig = self._compute_integrated_gradients(
|
|
320
|
+
instance, noisy_baseline, target_class
|
|
321
|
+
)
|
|
322
|
+
all_attributions.append(ig)
|
|
323
|
+
|
|
324
|
+
# Average attributions
|
|
325
|
+
avg_attributions = np.mean(all_attributions, axis=0)
|
|
326
|
+
std_attributions = np.std(all_attributions, axis=0)
|
|
327
|
+
|
|
328
|
+
attributions = {
|
|
329
|
+
fname: float(avg_attributions[i])
|
|
330
|
+
for i, fname in enumerate(self.feature_names)
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
if self.class_names and target_class is not None:
|
|
334
|
+
label_name = self.class_names[target_class]
|
|
335
|
+
else:
|
|
336
|
+
label_name = f"class_{target_class}" if target_class is not None else "output"
|
|
337
|
+
|
|
338
|
+
return Explanation(
|
|
339
|
+
explainer_name="IntegratedGradients_Smooth",
|
|
340
|
+
target_class=label_name,
|
|
341
|
+
explanation_data={
|
|
342
|
+
"feature_attributions": attributions,
|
|
343
|
+
"attributions_raw": avg_attributions.tolist(),
|
|
344
|
+
"attributions_std": std_attributions.tolist(),
|
|
345
|
+
"n_samples": n_samples,
|
|
346
|
+
"noise_scale": noise_scale
|
|
347
|
+
}
|
|
348
|
+
)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: explainiverse
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.3
|
|
4
4
|
Summary: Unified, extensible explainability framework supporting LIME, SHAP, Anchors, Counterfactuals, PDP, ALE, SAGE, and more
|
|
5
5
|
Home-page: https://github.com/jemsbhai/explainiverse
|
|
6
6
|
License: MIT
|
|
@@ -31,7 +31,7 @@ Description-Content-Type: text/markdown
|
|
|
31
31
|
# Explainiverse
|
|
32
32
|
|
|
33
33
|
**Explainiverse** is a unified, extensible Python framework for Explainable AI (XAI).
|
|
34
|
-
It provides a standardized interface for model-agnostic explainability with
|
|
34
|
+
It provides a standardized interface for model-agnostic explainability with 10 state-of-the-art XAI methods, evaluation metrics, and a plugin registry for easy extensibility.
|
|
35
35
|
|
|
36
36
|
---
|
|
37
37
|
|
|
@@ -43,6 +43,7 @@ It provides a standardized interface for model-agnostic explainability with 9 st
|
|
|
43
43
|
- **LIME** - Local Interpretable Model-agnostic Explanations ([Ribeiro et al., 2016](https://arxiv.org/abs/1602.04938))
|
|
44
44
|
- **SHAP** - SHapley Additive exPlanations via KernelSHAP ([Lundberg & Lee, 2017](https://arxiv.org/abs/1705.07874))
|
|
45
45
|
- **TreeSHAP** - Exact SHAP values for tree models, 10x+ faster ([Lundberg et al., 2018](https://arxiv.org/abs/1802.03888))
|
|
46
|
+
- **Integrated Gradients** - Axiomatic attributions for neural networks ([Sundararajan et al., 2017](https://arxiv.org/abs/1703.01365))
|
|
46
47
|
- **Anchors** - High-precision rule-based explanations ([Ribeiro et al., 2018](https://ojs.aaai.org/index.php/AAAI/article/view/11491))
|
|
47
48
|
- **Counterfactual** - DiCE-style diverse counterfactual explanations ([Mothilal et al., 2020](https://arxiv.org/abs/1905.07697))
|
|
48
49
|
|
|
@@ -109,7 +110,7 @@ adapter = SklearnAdapter(model, class_names=iris.target_names.tolist())
|
|
|
109
110
|
|
|
110
111
|
# List available explainers
|
|
111
112
|
print(default_registry.list_explainers())
|
|
112
|
-
# ['lime', 'shap', 'treeshap', 'anchors', 'counterfactual', 'permutation_importance', 'partial_dependence', 'ale', 'sage']
|
|
113
|
+
# ['lime', 'shap', 'treeshap', 'integrated_gradients', 'anchors', 'counterfactual', 'permutation_importance', 'partial_dependence', 'ale', 'sage']
|
|
113
114
|
|
|
114
115
|
# Create and use an explainer
|
|
115
116
|
explainer = default_registry.create(
|
|
@@ -128,7 +129,7 @@ print(explanation.explanation_data["feature_attributions"])
|
|
|
128
129
|
```python
|
|
129
130
|
# Find local explainers for tabular data
|
|
130
131
|
local_tabular = default_registry.filter(scope="local", data_type="tabular")
|
|
131
|
-
print(local_tabular) # ['lime', 'shap', 'treeshap', 'anchors', 'counterfactual']
|
|
132
|
+
print(local_tabular) # ['lime', 'shap', 'treeshap', 'integrated_gradients', 'anchors', 'counterfactual']
|
|
132
133
|
|
|
133
134
|
# Find explainers optimized for tree models
|
|
134
135
|
tree_explainers = default_registry.filter(model_type="tree")
|
|
@@ -200,6 +201,32 @@ predictions, gradients = adapter.predict_with_gradients(X)
|
|
|
200
201
|
activations = adapter.get_layer_output(X, layer_name="0")
|
|
201
202
|
```
|
|
202
203
|
|
|
204
|
+
### Integrated Gradients for Neural Networks
|
|
205
|
+
|
|
206
|
+
```python
|
|
207
|
+
from explainiverse.explainers import IntegratedGradientsExplainer
|
|
208
|
+
from explainiverse import PyTorchAdapter
|
|
209
|
+
|
|
210
|
+
# Wrap your PyTorch model
|
|
211
|
+
adapter = PyTorchAdapter(model, task="classification", class_names=class_names)
|
|
212
|
+
|
|
213
|
+
# Create IG explainer
|
|
214
|
+
explainer = IntegratedGradientsExplainer(
|
|
215
|
+
model=adapter,
|
|
216
|
+
feature_names=feature_names,
|
|
217
|
+
class_names=class_names,
|
|
218
|
+
n_steps=50 # More steps = more accurate
|
|
219
|
+
)
|
|
220
|
+
|
|
221
|
+
# Explain a prediction
|
|
222
|
+
explanation = explainer.explain(X_test[0])
|
|
223
|
+
print(explanation.explanation_data["feature_attributions"])
|
|
224
|
+
|
|
225
|
+
# Check convergence (sum of attributions ≈ F(x) - F(baseline))
|
|
226
|
+
explanation = explainer.explain(X_test[0], return_convergence_delta=True)
|
|
227
|
+
print(f"Convergence delta: {explanation.explanation_data['convergence_delta']}")
|
|
228
|
+
```
|
|
229
|
+
|
|
203
230
|
### Using Specific Explainers
|
|
204
231
|
|
|
205
232
|
```python
|
|
@@ -300,12 +327,12 @@ poetry run pytest tests/test_new_explainers.py -v
|
|
|
300
327
|
## Roadmap
|
|
301
328
|
|
|
302
329
|
- [x] LIME, SHAP (KernelSHAP)
|
|
303
|
-
- [x] TreeSHAP (optimized for tree models) ✅
|
|
330
|
+
- [x] TreeSHAP (optimized for tree models) ✅
|
|
304
331
|
- [x] Anchors, Counterfactuals
|
|
305
332
|
- [x] Permutation Importance, PDP, ALE, SAGE
|
|
306
333
|
- [x] Explainer Registry with filtering
|
|
307
|
-
- [x] PyTorch Adapter ✅
|
|
308
|
-
- [
|
|
334
|
+
- [x] PyTorch Adapter ✅
|
|
335
|
+
- [x] Integrated Gradients ✅ NEW
|
|
309
336
|
- [ ] GradCAM for CNNs
|
|
310
337
|
- [ ] TensorFlow adapter
|
|
311
338
|
- [ ] Interactive visualization dashboard
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
explainiverse/__init__.py,sha256
|
|
1
|
+
explainiverse/__init__.py,sha256=NmrLPOGZZPZTq1vY0G4gid5ZJWxsVGd3CfTXVIDvjaQ,1612
|
|
2
2
|
explainiverse/adapters/__init__.py,sha256=HcQGISyp-YQ4jEj2IYveX_c9X5otLcTNWRnVRRhzRik,781
|
|
3
3
|
explainiverse/adapters/base_adapter.py,sha256=Nqt0GeDn_-PjTyJcZsE8dRTulavqFQsv8sMYWS_ps-M,603
|
|
4
4
|
explainiverse/adapters/pytorch_adapter.py,sha256=GTilJAR1VF_OgWG88qZoqlqefHaSXB3i9iOwCJkyHTg,13318
|
|
@@ -6,12 +6,12 @@ explainiverse/adapters/sklearn_adapter.py,sha256=pzIBtMuqrG-6ZbUqUCMt7rSk3Ow0Fgr
|
|
|
6
6
|
explainiverse/core/__init__.py,sha256=P3jHMnH5coFqTTO1w-gT-rurkCM1-9r3pF-055pbXMg,474
|
|
7
7
|
explainiverse/core/explainer.py,sha256=Z9on-9VblYDlQx9oBm1BHpmAf_NsQajZ3qr-u48Aejo,784
|
|
8
8
|
explainiverse/core/explanation.py,sha256=6zxFh_TH8tFHc-r_H5-WHQ05Sp1Kp2TxLz3gyFek5jo,881
|
|
9
|
-
explainiverse/core/registry.py,sha256=
|
|
9
|
+
explainiverse/core/registry.py,sha256=AC8XDIdX2IGyx0KkmDajAjdo5YsrM3dcKvYoQu1vNCk,20711
|
|
10
10
|
explainiverse/engine/__init__.py,sha256=1sZO8nH1mmwK2e-KUavBQm7zYDWUe27nyWoFy9tgsiA,197
|
|
11
11
|
explainiverse/engine/suite.py,sha256=sq8SK_6Pf0qRckTmVJ7Mdosu9bhkjAGPGN8ymLGFP9E,4914
|
|
12
12
|
explainiverse/evaluation/__init__.py,sha256=Y50L_b4HKthg4epwcayPHXh0l4i4MUuzvaNlqPmUNZY,212
|
|
13
13
|
explainiverse/evaluation/metrics.py,sha256=tSBXtyA_-0zOGCGjlPZU6LdGKRH_QpWfgKa78sdlovs,7453
|
|
14
|
-
explainiverse/explainers/__init__.py,sha256=
|
|
14
|
+
explainiverse/explainers/__init__.py,sha256=3yhamu1E2hpb0vE_hg3xK621YJdZYcy7gsSGgCT4Km4,1962
|
|
15
15
|
explainiverse/explainers/attribution/__init__.py,sha256=YeVs9bS_IWDtqGbp6T37V6Zp5ZDWzLdAXHxxyFGpiQM,431
|
|
16
16
|
explainiverse/explainers/attribution/lime_wrapper.py,sha256=OnXIV7t6yd-vt38sIi7XmHFbgzlZfCEbRlFyGGd5XiE,3245
|
|
17
17
|
explainiverse/explainers/attribution/shap_wrapper.py,sha256=tKie5AvN7mb55PWOYdMvW0lUAYjfHPzYosEloEY2ZzI,3210
|
|
@@ -23,9 +23,11 @@ explainiverse/explainers/global_explainers/ale.py,sha256=tgG3XTppCf8LiD7uKzBt4DI
|
|
|
23
23
|
explainiverse/explainers/global_explainers/partial_dependence.py,sha256=dH6yMjpwZads3pACR3rSykTbssLGHH7e6HfMlpl-S3I,6745
|
|
24
24
|
explainiverse/explainers/global_explainers/permutation_importance.py,sha256=bcgKz1S_D3lrBMgpqEF_Z6qw8Knxl_cfR50hrSO2tBc,4410
|
|
25
25
|
explainiverse/explainers/global_explainers/sage.py,sha256=57Xw1SK529x5JXWt0TVrcFYUUP3C65LfUwgoM-Z3gaw,5839
|
|
26
|
+
explainiverse/explainers/gradient/__init__.py,sha256=Z4uSZcBhnHGp7DCd7bhcIMj_3f_uuCFw5AGA1JX6myQ,350
|
|
27
|
+
explainiverse/explainers/gradient/integrated_gradients.py,sha256=feBgY3Vw2rDti7fxRZtLkxse75m2dbP_R05ARqo2BRM,13367
|
|
26
28
|
explainiverse/explainers/rule_based/__init__.py,sha256=gKzlFCAzwurAMLJcuYgal4XhDj1thteBGcaHWmN7iWk,243
|
|
27
29
|
explainiverse/explainers/rule_based/anchors_wrapper.py,sha256=ML7W6aam-eMGZHy5ilol8qupZvNBJpYAFatEEPnuMyo,13254
|
|
28
|
-
explainiverse-0.2.
|
|
29
|
-
explainiverse-0.2.
|
|
30
|
-
explainiverse-0.2.
|
|
31
|
-
explainiverse-0.2.
|
|
30
|
+
explainiverse-0.2.3.dist-info/LICENSE,sha256=28rbHe8rJgmUlRdxJACfq1Sj-MtCEhyHxkJedQd1ZYA,1070
|
|
31
|
+
explainiverse-0.2.3.dist-info/METADATA,sha256=TGuHUB9HZEcTbkQ7vmXl6ygm9arV5tlzufCHMoFqmdk,10465
|
|
32
|
+
explainiverse-0.2.3.dist-info/WHEEL,sha256=sP946D7jFCHeNz5Iq4fL4Lu-PrWrFsgfLXbbkciIZwg,88
|
|
33
|
+
explainiverse-0.2.3.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|