-
Notifications
You must be signed in to change notification settings - Fork 13
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
15 changed files
with
321 additions
and
250 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,5 +1,6 @@ | ||
# flake8: noqa: F401 | ||
"""Tools for visualization of model explanations.""" | ||
from .image import plot_image | ||
from .tabular import plot_tabular | ||
from .text import highlight_text | ||
from .timeseries import plot_timeseries |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
"""Visualization module for tabular data.""" | ||
from typing import List | ||
from typing import Optional | ||
import matplotlib.pyplot as plt | ||
import numpy as np | ||
|
||
|
||
def plot_tabular( | ||
x: np.ndarray, | ||
y: List[str], | ||
x_label: str = "Importance score", | ||
y_label: str = "Features", | ||
num_features: Optional[int] = None, | ||
show_plot: Optional[bool] = True, | ||
output_filename: Optional[str] = None, | ||
) -> plt.Figure: | ||
"""Plot feature importance with segments highlighted. | ||
Args: | ||
x (np.ndarray): Array of feature importance scores | ||
y (List[str]): List of feature names | ||
x_label (str): Label for the x-axis | ||
y_label (str): Label or list of labels for the y-axis | ||
num_features (Optional[int]): Number of most salient features to display | ||
show_plot (bool, optional): Shows plot if true (for testing or writing | ||
plots to disk instead). | ||
output_filename (str, optional): Name of the file to save | ||
the plot to (optional). | ||
Returns: | ||
plt.Figure | ||
""" | ||
if not num_features: | ||
num_features = len(x) | ||
fig, ax = plt.subplots() | ||
abs_values = [abs(i) for i in x] | ||
top_values = [x for _, x in sorted(zip(abs_values, x), reverse=True)][:num_features] | ||
top_features = [x for _, x in sorted(zip(abs_values, y), reverse=True)][ | ||
:num_features | ||
] | ||
|
||
colors = ["r" if x >= 0 else "b" for x in top_values] | ||
ax.barh(top_features, top_values, color=colors) | ||
ax.set_xlabel(x_label) | ||
ax.set_ylabel(y_label) | ||
|
||
if show_plot: | ||
plt.show() | ||
if output_filename: | ||
plt.savefig(output_filename) | ||
|
||
return fig |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,67 @@ | ||
"""Unit tests for LIME image.""" | ||
from unittest import TestCase | ||
import numpy as np | ||
import dianna | ||
from dianna.methods.lime_image import LIMEImage | ||
from tests.methods.test_onnx_runner import generate_data | ||
from tests.utils import run_model | ||
|
||
|
||
class LimeOnImages(TestCase): | ||
"""Suite of Lime tests for the image case.""" | ||
|
||
@staticmethod | ||
def test_lime_function(): | ||
"""Test if lime runs and outputs are correct given some data and a model function.""" | ||
input_data = np.random.random((224, 224, 3)) | ||
heatmap_expected = np.load('tests/test_data/heatmap_lime_function.npy') | ||
labels = [1] | ||
|
||
explainer = LIMEImage(random_state=42) | ||
heatmap = explainer.explain(run_model, | ||
input_data, | ||
labels, | ||
num_samples=100) | ||
|
||
assert heatmap[0].shape == input_data.shape[:2] | ||
assert np.allclose(heatmap, heatmap_expected, atol=1e-5) | ||
|
||
@staticmethod | ||
def test_lime_filename(): | ||
"""Test if lime runs and outputs are correct given some data and a model file.""" | ||
model_filename = 'tests/test_data/mnist_model.onnx' | ||
input_data = generate_data(batch_size=1)[0].astype(np.float32) | ||
axis_labels = ('channels', 'y', 'x') | ||
labels = [1] | ||
|
||
heatmap = dianna.explain_image(model_filename, | ||
input_data, | ||
method='LIME', | ||
labels=labels, | ||
random_state=42, | ||
axis_labels=axis_labels) | ||
|
||
heatmap_expected = np.load('tests/test_data/heatmap_lime_filename.npy') | ||
assert heatmap[0].shape == input_data[0].shape | ||
assert np.allclose(heatmap, heatmap_expected, atol=1e-5) | ||
|
||
@staticmethod | ||
def test_lime_values(): | ||
"""Test if get_explanation_values function works correctly.""" | ||
input_data = np.random.random((224, 224, 3)) | ||
heatmap_expected = np.load('tests/test_data/heatmap_lime_values.npy') | ||
labels = [1] | ||
|
||
explainer = LIMEImage(random_state=42) | ||
heatmap = explainer.explain(run_model, | ||
input_data, | ||
labels, | ||
return_masks=False, | ||
num_samples=100) | ||
|
||
assert heatmap[0].shape == input_data.shape[:2] | ||
assert np.allclose(heatmap, heatmap_expected, atol=1e-5) | ||
|
||
def setUp(self) -> None: | ||
"""Set seed.""" | ||
np.random.seed(42) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.