Skip to content

Commit 9de7fac

Browse files
ThrashLionHolzner, Matthias42logosFabianK-Devmmschlk
authored
Add PolySHAP Approximator (#559)
* PolySHAP file integration * test: add cross-approximator conformance + convergence test scaffold Forward-looking spec for the 3 new SV approximators (LeverageSHAP, PolySHAP, OddSHAP). Approximator classes are looked up dynamically by name, so the file auto-skips classes that have not yet been registered in shapiq.approximator. As each implementation lands, the corresponding parametrizations activate. - Interface conformance (always required): index='SV', n_players, max_order/min_order, values shape and dtype, interaction_lookup. - Numerical convergence vs ExactComputer (xfail strict=False): atol schedule by budget percentage. - Determinism: same (n, random_state, budget, game) -> bit-identical output. 75 tests, all currently SKIP on main. Will activate as classes land. * test: extend conformance harness to ALL SV approximators Honors the cross-method testing platform promised to the tutor: unified harness covering every SV approximator in shapiq (the existing 11 — KernelSHAP, SVARM, Permutation*, ProxySPEX, ... — and the 3 new ones from this project) instead of only the new line-up. Approximator list is sourced dynamically from shapiq.approximator.SV_APPROXIMATORS (canonical registry) plus the 3 new project names, deduplicated. Future shapiq additions land in the harness automatically. Split into two scopes: * test_interface_conformance — strict shape/dtype/index/lookup contract from the API spec. Applied ONLY to the 3 new approximators (the contract is ours; existing methods have different default output conventions like ProxySPEX defaulting to FBII and max_order=n). * test_numerical_convergence_vs_exact + test_determinism — apply to ALL SV approximators. Cross-method comparison against ExactComputer ground truth on identical SOUM games. xfail with strict=False so methods that do converge surface as XPASS; methods still under development surface as XFAIL. Two robustness helpers: * _construct_or_skip — tries (n=, index='SV', max_order=1, random_state=) first (covers multi-index methods like SPEX, ProxySPEX, ProxySHAP, MSRBiased, kADDSHAP), then falls back to minimal signature for SV-only methods (KernelSHAP, OwenSamplingSV). * _safe_approximate — skips on ValueError raised by approximators that explicitly refuse a regime (e.g. SPEX 'Insufficient budget to compute the transform' at low budgets). Results: 10 passed, 95 skipped, 90 xfailed, 23 xpassed. The 23 xpassed are existing shapiq SV methods that converge cleanly at full budget on small SOUM — a useful baseline for the upcoming benchmark report. * PolySHAPKAdd, PolySHAPPartial, PolySHAPPrior refactored PolySHAP+ExplanationFrontierGenerator into subclasses requiring no generator; registered all three subclasses; removed unexpected parameters; cleaner variable naming; included unedited efficient_sampling for now * docstring: removed ref to removed para * feat(benchmark): cross-method performance harness for SV approximators Drop-in framework that any teammate can merge into their feature branch to run head-to-head benchmarks against ExactComputer across every SV approximator in shapiq, then plot the standard SHAP-literature metric curves. No source files are modified — adds a top-level benchmark/ package, a single test file, and a small in-place test-helper sys.path hook. Does not touch pyproject.toml or any other upstream config. Files added: * benchmark/__init__.py: makes the runner a proper Python package so invocation is 'python -m benchmark.performance'. * benchmark/_discovery.py: single source of truth for SV approximator discovery + SV-mode construction. Holds: - PROJECT_APPROXIMATOR_NAMES: LeverageSHAP, PolySHAP, PolySHAPKAdd / Partial / Prior, OddSHAP. - _SV_CONSTRUCT_OVERRIDES: per-class kwargs for non-standard constructors (PolySHAP variants need max_order / n_explanation_terms / q_prior). - construct_for_sv(): three-stage construction (override -> explicit SV signature -> minimal signature), returning (estimator, exc) so the caller can report the most informative exception. A ValueError from inside a matched signature wins over a TypeError from a signature mismatch. - safe_approximate(): catches ValueError and RuntimeError so sparse approximators that refuse a budget regime (SPEX, ProxySPEX, ...) skip the cell cleanly instead of crashing. * benchmark/performance.py: CLI runner that consumes _discovery, sweeps (method, game, budget, seed), records every cell in a long-format CSV, and emits one PNG per (game, metric) plus a runtime PNG. Seven metrics chosen from the union of LeverageSHAP, PolySHAP, OddSHAP and shapiq.benchmark.metrics literature: MSE / MAE / SSE / SAE / Precision@5 / Precision@10 / KendallTau. Includes a '--check' interface-probe mode that prints a constructibility table without running a sweep. * benchmark/README.md: usage doc covering merge workflow, --check, sweep CLI, output layout, CSV format, metric definitions, plot conventions, and notes on the multi-index approximators that need explicit (index='SV', max_order=1). Files modified: * tests/shapiq/tests_unit/tests_approximators/test_approximators_vs_exact.py: now imports the shared helpers from benchmark._discovery via a tightly-scoped sys.path hook at the top of the file. Picks up the ValueError-priority construction and the RuntimeError-catch that the test file previously did not have. Interface conformance is now applied to the project's six new approximator names (LeverageSHAP, PolySHAP + 3 variants, OddSHAP), so Matthias's PolySHAP variants are no longer silently skipped by the contract check. Verified locally: * pytest test_approximators_vs_exact.py: 10 passed, 170 skipped, 87 xfailed, 26 xpassed. No failures. * python -m benchmark.performance --check: surfaces all 17 method names (11 existing on main + 6 project additions) correctly. * Drop-in compatibility verified by temporary merge into all three feature branches (oddshap_approximator, leverageSHAP, PolySHAP) — clean merge in each, --check picks up the local approximator. * feat/gitignore: Add benchmark/results/* to .gitignore * PolySHAP unit tests * PolySHAP docstrings; underdefined problem warning * PolySHAP removed time measurements; fixed docstring * PolySHAP benchmark discovery * PolySHAP: removed efficient_sampling.py Removed for lack of generalization * PolySHAP seeded unit tests * PolySHAP paper reproduction notebook * FIX PolySHAP interaction values * PolySHAP maxorder showcase notebook * PolySHAPPrior excluded from benchmarking * PolySHAP bib-reference and mini-demo * PolySHAP changelog entry * PolySHAP lint fixes * PolySHAP removal of additional benchmark and notebooks * PolySHAP OddSHAP Fumagalli bib references * PolySHAP make overrides ty-compatible * PolySHAP unified class; improved unit tests * PolySHAP docstring: unbounded max_order * Adapt PolySHAP to the reworked documentation - cite the PolySHAP paper as Fumagalli.2026, its key in main's bibliography (Fumagalli.2026a is now OddSHAP) - move the example into the Shapley values gallery, cite with :cite: instead of :footcite:, and add it to EXAMPLE_ORDER - link the timeline's PolySHAP entry to the class and the example - export PolySHAP from the top-level package like the other approximators * Fix PolySHAP's prior_frontier when the empty set is not listed first The regression assumes that the empty set is the first frontier term. A prior_frontier without it (e.g. only singletons and pairs) silently returned wrong Shapley values, and one listing it last raised an IndexError. The empty set is now always put first, the other terms keep their order, and duplicate terms are ignored. * Fix PolySHAP failing for more than ~1,030 players binom(n, k) overflows float64 from n ~ 1030 on. The regression kernel weight (~1 / binom) then underflowed to 0 and the sampler's adjustment weight (~binom) overflowed to inf, so lstsq failed with "SVD did not converge". The kernel weights are now kept in log space and added to the sampler's log adjustment weights, as in the other regression approximators (see #621 for OddSHAP). * Declare only SV in PolySHAP's valid_indices PolySHAP inherited all regression indices from Regression, but it only computes Shapley values. It now declares ("SV",) like KernelSHAP, LeverageSHAP and OddSHAP. * Remove unrelated .gitignore entries Drops the duplicate .claude entry and the repository-wide cache/ rule, which are not related to PolySHAP. --------- Co-authored-by: Holzner, Matthias <matthias.holzner@campus.lmu.de> Co-authored-by: YUANLUO WU <yuanluowu@gmail.com> Co-authored-by: Fabian Kadlez <F.Kadlez@campus.lmu.de> Co-authored-by: Maximilian <maximilian.muschalik@gmail.com>
1 parent 9c583f4 commit 9de7fac

9 files changed

Lines changed: 1088 additions & 0 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,13 @@
22

33
## Development
44

5+
### New PolySHAP Approximator [#559](https://github.com/mmschlk/shapiq/pull/559)
6+
7+
Adds the `PolySHAP` approximator in `shapiq.approximator.regression` for Shapley value estimation via interaction-informed polynomial regression (Fumagalli et al., 2026).
8+
`PolySHAP` generalizes `KernelSHAP` by fitting a *k*-additive polynomial surrogate of the game before reading off the Shapley values.
9+
The interaction frontier can be the full *k*-additive frontier up to `max_order` (with `max_order=1` recovering `KernelSHAP`), a budget-controlled partial frontier (`max_terms`), or a user-supplied set of interaction terms (`prior_frontier`).
10+
It is registered as a Shapley value (`SV`) approximator.
11+
512
### Harmonized `shapiq_games` and `shapiq_benchmark` [#616](https://github.com/mmschlk/shapiq/pull/616)
613

714
- `shapiq_games` is a tested collection of game definitions: one class per game family, built from plain objects (a model, data, a point, an image, a text), with deterministic values and tested examples. It replaces the about 130 dataset-specific classes of `shapiq_games.benchmark`.

‎docs/source/_data/timeline.toml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -686,6 +686,8 @@ instead of KernelSHAP's linear model, and reads the Shapley values out of the fi
686686
It converges to the exact Shapley values and sheds light on why paired sampling improves KernelSHAP.
687687
"""
688688
cite = ["Fumagalli.2026"]
689+
api = ["shapiq.approximator.PolySHAP"]
690+
examples = ["auto_examples/approximators/shapley_values/plot_polyshap"]
689691
related = ["kernelshap", "kaddshap", "oddshap"]
690692

691693
[[entries]]

‎docs/source/conf.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,7 @@
123123
"plot_owen_sampling_sv.py",
124124
"plot_unbiased_kernelshap.py",
125125
"plot_kadd_shap.py",
126+
"plot_polyshap.py",
126127
"plot_oddshap.py",
127128
"plot_shapleig.py",
128129
),
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
"""
2+
PolySHAP
3+
========
4+
5+
Estimate Shapley values by fitting a polynomial surrogate of the game that includes
6+
interactions, instead of KernelSHAP's linear model.
7+
8+
:class:`~shapiq.approximator.PolySHAP` :cite:p:`Fumagalli.2026` extends KernelSHAP by fitting
9+
a *k-additive* surrogate of the game -- a polynomial of degree ``max_order`` over the players --
10+
and reading the Shapley values off that surrogate. ``max_order=1`` reduces to plain KernelSHAP,
11+
while higher orders capture interactions explicitly. When the game's interactions do not exceed
12+
``max_order``, PolySHAP recovers the exact Shapley values.
13+
"""
14+
15+
# sphinx_gallery_thumbnail_path = "_static/gallery/approximators_regression.png"
16+
17+
from __future__ import annotations
18+
19+
import numpy as np
20+
21+
import shapiq
22+
from shapiq import PolySHAP
23+
24+
N_PLAYERS = 8
25+
BUDGET = 200
26+
feature_names = [f"x{i}" for i in range(N_PLAYERS)]
27+
28+
weights = np.array([0.4, 0.3, 0.2, 0.1, 0.05, -0.1, -0.2, -0.3])
29+
30+
31+
def game_fun(coalitions: np.ndarray) -> np.ndarray:
32+
# A linear game plus a single pairwise interaction between x0 and x1.
33+
# This game is exactly 2-additive: its interactions never exceed order 2.
34+
coalitions = np.atleast_2d(coalitions)
35+
return (coalitions @ weights) + 0.5 * coalitions[:, 0] * coalitions[:, 1]
36+
37+
38+
# %%
39+
# Approximate Shapley values
40+
# --------------------------
41+
# The game has a pairwise interaction, so we fit a second-order (``max_order=2``)
42+
# polynomial surrogate to recover the Shapley values.
43+
44+
approximator = PolySHAP(n=N_PLAYERS, max_order=2, random_state=42)
45+
iv = approximator.approximate(BUDGET, game_fun)
46+
print(iv)
47+
48+
# %%
49+
# Force plot
50+
# ----------
51+
52+
iv.plot_force(feature_names=feature_names)
53+
54+
# %%
55+
# Higher order improves accuracy
56+
# ------------------------------
57+
# Because the game is exactly 2-additive, raising ``max_order`` to match its
58+
# interaction order recovers the exact Shapley values, whereas ``max_order=1``
59+
# (equivalent to KernelSHAP) leaves a visible approximation error. We compare
60+
# both against the exact Shapley values from :class:`~shapiq.game_theory.ExactComputer`.
61+
62+
exact = np.asarray(
63+
shapiq.ExactComputer(game_fun, n_players=N_PLAYERS)(index="SV", order=1).get_n_order_values(1)
64+
)
65+
66+
for max_order in (1, 2):
67+
est = np.asarray(
68+
PolySHAP(n=N_PLAYERS, max_order=max_order, random_state=42)
69+
.approximate(BUDGET, game_fun)
70+
.get_n_order_values(1)
71+
)
72+
mse = float(np.mean((est - exact) ** 2))
73+
print(f"max_order={max_order}: MSE vs. exact Shapley = {mse:.2e}")

‎src/shapiq/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
PermutationSamplingSII,
2727
PermutationSamplingSTII,
2828
PermutationSamplingSV,
29+
PolySHAP,
2930
ProxySHAP,
3031
ProxySPEX,
3132
RegressionFBII,
@@ -118,6 +119,7 @@
118119
"ProxySPEX",
119120
"RegressionMSR",
120121
"OddSHAP",
122+
"PolySHAP",
121123
# explainers
122124
"Explainer",
123125
"TabularExplainer",

‎src/shapiq/approximator/__init__.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
KernelSHAPIQ,
1919
LeverageSHAP,
2020
OddSHAP,
21+
PolySHAP,
2122
RegressionFBII,
2223
RegressionFSII,
2324
kADDSHAP,
@@ -66,6 +67,7 @@ def __init__(self, *_args: object, **_kwargs: object) -> None:
6667
ProxySPEX,
6768
OddSHAP,
6869
ShaplEIG,
70+
PolySHAP,
6971
]
7072

7173
# contains all SI approximators
@@ -148,4 +150,5 @@ def __init__(self, *_args: object, **_kwargs: object) -> None:
148150
"STII_APPROXIMATORS",
149151
"FSII_APPROXIMATORS",
150152
"FBII_APPROXIMATORS",
153+
"PolySHAP",
151154
]

‎src/shapiq/approximator/regression/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
from .kernelshapiq import InconsistentKernelSHAPIQ, KernelSHAPIQ
88
from .leverageshap import LeverageSHAP
99
from .oddshap import OddSHAP
10+
from .polyshap import PolySHAP
1011

1112
__all__ = [
1213
"kADDSHAP",
@@ -17,5 +18,6 @@
1718
"LeverageSHAP",
1819
"Regression",
1920
"RegressionFBII",
21+
"PolySHAP",
2022
"OddSHAP",
2123
]

0 commit comments

Comments
 (0)