|
| 1 | +"""Implementation of the ProductKernelExplainer class.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +from typing import TYPE_CHECKING, Any |
| 6 | + |
| 7 | +from shapiq import InteractionValues |
| 8 | +from shapiq.explainer.base import Explainer |
| 9 | +from shapiq.game_theory import get_computation_index |
| 10 | + |
| 11 | +from .product_kernel import ProductKernelComputer, ProductKernelSHAPIQIndices |
| 12 | +from .validation import validate_pk_model |
| 13 | + |
| 14 | +if TYPE_CHECKING: |
| 15 | + import numpy as np |
| 16 | + from sklearn.gaussian_process import GaussianProcessRegressor |
| 17 | + from sklearn.svm import SVC, SVR |
| 18 | + |
| 19 | + from shapiq.typing import Model |
| 20 | + |
| 21 | + from .base import ProductKernelModel |
| 22 | + |
| 23 | + |
| 24 | +class ProductKernelExplainer(Explainer): |
| 25 | + """The ProductKernelExplainer class for product kernel-based models. |
| 26 | +
|
| 27 | + The ProductKernelExplainer can be used with a variety of product kernel-based models. The explainer can handle both regression and |
| 28 | + classification models. See [pkex-shapley]_ for details. |
| 29 | +
|
| 30 | +
|
| 31 | + References: |
| 32 | + .. [pkex-shapley] Majid Mohammadi and Siu Lun Chau, Krikamol Muandet. (2025). Computing Exact Shapley Values in Polynomial Time for Product-Kernel Methods. https://arxiv.org/abs/2505.16516 |
| 33 | +
|
| 34 | + Attributes: |
| 35 | + model: The product kernel model to explain. Can be a dictionary, a ProductKernelModel, or a list of ProductKernelModels. |
| 36 | + Note that the model will be converted to a ProductKernelModel if it is not already in that format. |
| 37 | + Supported models include scikit-learn's SVR, SVC (binary classification only), and GaussianProcessRegressor. |
| 38 | + Beware that for classification models, the class to explain is set to the predicted class of the model. |
| 39 | + For further details, see the `validate_pk_model` function in `shapiq.explainer.product_kernel.validation`. |
| 40 | + max_order: The maximum interaction order to be computed. Defaults to ``1``. |
| 41 | + min_order: The minimum interaction order to be computed. Defaults to ``0``. |
| 42 | + index: The type of interaction to be computed. Currently, only ``"SV"`` is supported. |
| 43 | + """ |
| 44 | + |
| 45 | + def __init__( |
| 46 | + self, |
| 47 | + model: ( |
| 48 | + ProductKernelModel | Model | SVR | SVC | GaussianProcessRegressor # pyright: ignore[reportInvalidTypeVarUse] |
| 49 | + ), |
| 50 | + *, |
| 51 | + min_order: int = 0, |
| 52 | + max_order: int = 1, |
| 53 | + index: ProductKernelSHAPIQIndices = "SV", |
| 54 | + **kwargs: Any, # noqa: ARG002 |
| 55 | + ) -> None: |
| 56 | + """Initializes the ProductKernelExplainer. |
| 57 | +
|
| 58 | + Args: |
| 59 | + model: A product kernel-based model to explain. |
| 60 | +
|
| 61 | + min_order: The minimum interaction order to be computed. Defaults to ``0``. |
| 62 | +
|
| 63 | + max_order: The maximum interaction order to be computed. An interaction order of ``1`` |
| 64 | + corresponds to the Shapley value. Defaults to ``1``. |
| 65 | +
|
| 66 | + index: The type of interaction to be computed. Currently, only ``"SV"`` is supported. |
| 67 | +
|
| 68 | + class_index: The class index of the model to explain. Defaults to ``None``, which will |
| 69 | + set the class index to ``1`` per default for classification models and is ignored |
| 70 | + for regression models. |
| 71 | +
|
| 72 | + **kwargs: Additional keyword arguments are ignored. |
| 73 | +
|
| 74 | + """ |
| 75 | + if max_order > 1: |
| 76 | + msg = "ProductKernelExplainer currently only supports max_order=1." |
| 77 | + raise ValueError(msg) |
| 78 | + |
| 79 | + super().__init__(model, index=index, max_order=max_order) |
| 80 | + |
| 81 | + self._min_order = min_order |
| 82 | + self._max_order = max_order |
| 83 | + |
| 84 | + self._index = index |
| 85 | + self._base_index: str = get_computation_index(self._index) |
| 86 | + |
| 87 | + # validate model |
| 88 | + self.converted_model = validate_pk_model(model) |
| 89 | + |
| 90 | + self.explainer = ProductKernelComputer( |
| 91 | + model=self.converted_model, |
| 92 | + max_order=max_order, |
| 93 | + index=index, |
| 94 | + ) |
| 95 | + |
| 96 | + self.empty_prediction = self._compute_baseline_value() |
| 97 | + |
| 98 | + def explain_function( |
| 99 | + self, |
| 100 | + x: np.ndarray, |
| 101 | + **kwargs: Any, # noqa: ARG002 |
| 102 | + ) -> InteractionValues: |
| 103 | + """Compute Shapley values for all features of an instance. |
| 104 | +
|
| 105 | + Args: |
| 106 | + x: The instance (1D array) for which to compute Shapley values. |
| 107 | + **kwargs: Additional keyword arguments are ignored. |
| 108 | +
|
| 109 | + Returns: |
| 110 | + The interaction values for the instance. |
| 111 | + """ |
| 112 | + n_players = self.converted_model.d |
| 113 | + |
| 114 | + # compute the kernel vectors for the instance x |
| 115 | + kernel_vectors = self.explainer.compute_kernel_vectors(self.converted_model.X_train, x) |
| 116 | + |
| 117 | + shapley_values = {} |
| 118 | + for j in range(self.converted_model.d): |
| 119 | + shapley_values.update({(j,): self.explainer.compute_shapley_value(kernel_vectors, j)}) |
| 120 | + |
| 121 | + return InteractionValues( |
| 122 | + values=shapley_values, |
| 123 | + index=self._base_index, |
| 124 | + min_order=self._min_order, |
| 125 | + max_order=self.max_order, |
| 126 | + n_players=n_players, |
| 127 | + estimated=False, |
| 128 | + baseline_value=self.empty_prediction, |
| 129 | + target_index=self._index, |
| 130 | + ) |
| 131 | + |
| 132 | + def _compute_baseline_value(self) -> float: |
| 133 | + """Computes the baseline value for the explainer. |
| 134 | +
|
| 135 | + Returns: |
| 136 | + The baseline value for the explainer. |
| 137 | +
|
| 138 | + """ |
| 139 | + return self.converted_model.alpha.sum() + self.converted_model.intercept |
0 commit comments