diff --git a/CHANGELOG.md b/CHANGELOG.md index 766fec325..4e710ce52 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Development +- fixes `waterfall_plot` coloring only the last feature value in interaction labels. With `feature=value` labels and `abbreviate=False`, every feature value is now black, while feature names and interaction separators remain gray. - fixes the `"CHII"` estimates of `SHAPIQ` and `SVARMIQ`, which were wrong even with a budget of all `2**n` coalitions: the Monte Carlo approximators weighted the discrete derivatives with `s / t`, the coefficient of the Moebius representation of the chaining interaction index, instead of its cardinal-index weight `s * (s + t - 1)! * (n - s - t)! / n!`. [#643](https://github.com/mmschlk/shapiq/pull/643) - adds GraphSHAP-IQ in `shapiq.graph` for exact Shapley values and interactions of the nodes of graph neural networks (Muschalik et al., 2025). `GraphExplainer` explains `torch_geometric` models with a graph-level output, and `shapiq.Explainer` picks it for models with message passing layers. As for trees, a graph is converted into an internal representation, the `GraphModel` (edges, node features, and the radius of the receptive fields), and the new `GraphBaselineImputer`, a `BaselineImputer` whose players are the nodes, gives absent nodes the baseline node features. `GraphSHAPIQ` computes the values of any game that is local on a graph without `torch`; with `max_interaction_size`, it approximates them with fewer evaluations while keeping them efficient. `torch_geometric` graphs and models need the new extra `shapiq[graph]`. [#550](https://github.com/mmschlk/shapiq/pull/550) - adds graph games to `shapiq_games` and `shapiq_benchmark`: `shapiq_games.GraphGame`, the `GraphComputer` of their exact values with GraphSHAP-IQ (chosen by `default_computer` for games that are local on the graph), and `GraphSetup`, which trains a GCN, GIN, or GAT on a TUDataset graph classification dataset (`load_graph_dataset`, e.g. `"MUTAG"` or `"PROTEINS"`). Their exact values are feasible for graphs far beyond the 25 players of brute force. [#550](https://github.com/mmschlk/shapiq/pull/550) diff --git a/src/shapiq/plot/waterfall.py b/src/shapiq/plot/waterfall.py index 859032efd..18c0b15e6 100644 --- a/src/shapiq/plot/waterfall.py +++ b/src/shapiq/plot/waterfall.py @@ -12,6 +12,7 @@ import matplotlib.pyplot as plt import numpy as np +from matplotlib.offsetbox import AnnotationBbox, HPacker, TextArea from matplotlib.transforms import ScaledTranslation from ._config import BLUE, RED @@ -251,14 +252,10 @@ def _draw_waterfall_plot( fontsize=12, ) - # draw the y-ticks twice, once in gray and then again with just the feature names in black - # The 1e-8 is so matplotlib 3.3 doesn't try and collapse the ticks - ytick_pos = list(range(num_features)) + list(np.arange(num_features) + 1e-8) - plt.yticks( - ytick_pos, - yticklabels[:-1] + [label.split("=")[-1] for label in yticklabels[:-1]], - fontsize=13, - ) + # draw the y-ticks with the full label (used only to size the plot correctly); the + # colored rendering (feature names in gray, feature values in black) is done further + # below once the final figure size is known. + plt.yticks(range(num_features), yticklabels[:-1], fontsize=13) # Check that the y-ticks are not drawn outside the plot max_label_width = ( @@ -345,11 +342,45 @@ def _draw_waterfall_plot( tick_labels[1].set_color("#999999") - # color the y tick labels that have the feature values as gray - # (these fall behind the black ones with just the feature name) - tick_labels = ax.yaxis.get_majorticklabels() + # Color every feature value in black, keeping names and interaction separators gray. + # Pack the segments at draw time so resizing and export preserve their alignment. + ax.set_yticklabels(["" for _ in range(num_features)]) for i in range(num_features): - tick_labels[i].set_color("#999999") + parts = yticklabels[i].split(" x ") + segments = [] + for j, part in enumerate(parts): + if j > 0: + segments.append((" x ", "#999999")) + if "=" in part: + name_part, value_part = part.split("=", 1) + segments.append((name_part + "=", "#999999")) + segments.append((value_part, "black")) + else: + segments.append((part, "black")) + + label_box = HPacker( + children=[ + TextArea(text, textprops={"fontsize": 13, "color": color}) + for text, color in segments + ], + align="baseline", + pad=0, + sep=0, + ) + ax.add_artist( + AnnotationBbox( + label_box, + (0, i), + xycoords=ax.get_yaxis_transform(), + xybox=(-5, 0), + boxcoords="offset points", + box_alignment=(1, 0.5), + frameon=False, + pad=0, + annotation_clip=False, + clip_on=False, + ), + ) if show: plt.show() @@ -373,8 +404,9 @@ def waterfall_plot( Args: interaction_values: The interaction values as an interaction object. feature_names: The names of the features. Defaults to ``None``. To display feature values - alongside feature names, provide strings in the format ``"value=feature"`` (e.g., - ``"25=Age"``). The plot will show the value in gray and the feature name in black. + alongside feature names, provide strings in the format ``"feature=value"`` (e.g., + ``"Age=25"``) and set ``abbreviate=False`` to preserve the full labels. The plot shows + feature names and interaction separators in gray and every feature value in black. show: Whether to show the plot. Defaults to ``False``. max_display: The maximum number of interactions to display. Defaults to ``10``. abbreviate: Whether to abbreviate the feature names. Defaults to ``True``. diff --git a/tests/shapiq/tests_unit/tests_plots/test_waterfall.py b/tests/shapiq/tests_unit/tests_plots/test_waterfall.py index 37d8cb58a..cde629699 100644 --- a/tests/shapiq/tests_unit/tests_plots/test_waterfall.py +++ b/tests/shapiq/tests_unit/tests_plots/test_waterfall.py @@ -2,8 +2,15 @@ from __future__ import annotations +from io import BytesIO +from itertools import pairwise + import matplotlib.pyplot as plt import numpy as np +import pytest +from matplotlib.colors import to_rgba +from matplotlib.text import Text +from matplotlib.transforms import Bbox from shapiq import ExactComputer, InteractionValues, waterfall_plot @@ -55,3 +62,95 @@ def test_waterfall_plot(interaction_values_list: list[InteractionValues]): wp = iv.plot_waterfall(show=False) assert isinstance(wp, plt.Axes) plt.close() + + +@pytest.fixture +def waterfall_with_feature_values(): + """Render main effects and an interaction with explicit feature values.""" + iv = InteractionValues( + values={(0,): 0.25, (1,): -0.15, (0, 1): 0.35}, + index="k-SII", + max_order=2, + min_order=1, + n_players=2, + baseline_value=0.5, + ) + fig = plt.figure(dpi=100) + try: + iv.plot_waterfall( + feature_names=np.array(["Age=25", "Km=10"]), + abbreviate=False, + show=False, + ) + fig.canvas.draw() + yield fig, fig.axes[0] + finally: + plt.close(fig) + + +def test_waterfall_feature_value_colors(waterfall_with_feature_values): + """Color both values black in main-effect and interaction labels.""" + _, ax = waterfall_with_feature_values + texts = ax.findobj(match=Text) + for label, color, count in [ + ("Age=", "#999999", 2), + ("25", "black", 2), + (" x ", "#999999", 1), + ("Km=", "#999999", 2), + ("10", "black", 2), + ]: + matching = [text for text in texts if text.get_text() == label] + assert len(matching) == count + assert all(to_rgba(text.get_color()) == to_rgba(color) for text in matching) + + +@pytest.mark.parametrize("rendering", ["resize", "dpi", "tight", "svg", "pdf", "layout"]) +def test_waterfall_label_alignment(waterfall_with_feature_values, rendering): + """Keep interaction labels aligned and their segments adjacent on each redraw.""" + fig, ax = waterfall_with_feature_values + texts = ax.findobj(match=Text) + # The interaction has the largest contribution and occupies the top row. + segments = [ + max( + (text for text in texts if text.get_text() == label), + key=lambda text: text.get_window_extent().y1, + ) + for label in ["Age=", "25", " x ", "Km=", "10"] + ] + measurements = [] + + def record_alignment(event): + bounds = [text.get_window_extent(renderer=event.renderer) for text in segments] + label_bounds = Bbox.union(bounds) + row_y = ax.transData.transform((0, 2))[1] + right_edge = ax.transAxes.transform((0, 0))[0] - event.renderer.points_to_pixels(5) + measurements.append( + [ + (label_bounds.y0 + label_bounds.y1) / 2 - row_y, + label_bounds.x1 - right_edge, + *[right.x0 - left.x1 for left, right in pairwise(bounds)], + ], + ) + + callback = fig.canvas.mpl_connect("draw_event", record_alignment) + try: + if rendering == "resize": + fig.set_size_inches(fig.get_figwidth() * 0.8, fig.get_figheight() * 1.5) + fig.canvas.draw() + elif rendering == "layout": + fig.tight_layout() + fig.canvas.draw() + else: + with BytesIO() as output: + if rendering == "dpi": + fig.savefig(output, format="png", dpi=200) + elif rendering == "tight": + fig.savefig(output, format="png", bbox_inches="tight") + else: + fig.savefig(output, format=rendering) + finally: + fig.canvas.mpl_disconnect(callback) + + assert measurements + # Font hinting can make glyph bounds slightly smaller than the layout box. + np.testing.assert_allclose(measurements, 0, atol=0.5, rtol=0)