shapiq.explainer.WeightedKNNExplainer¶

class shapiq.explainer.WeightedKNNExplainer(model, class_index=None, n_bits=3, data=None, index='SV', max_order=1)[source]¶

Bases: NNExplainerBase

Explainer for weighted KNN models.

Implements the algorithm for efficiently computing exact Shapley values for weighted KNN models proposed by Wang et al.[1]. The algorithm achieves a runtime complexity of \(O\bigl(\frac{k^2 N^2 W}{C}\bigr)\), where

  • \(k\) is the defining hyperparameter of the \(k\)-nearest neighbors model,

  • \(N\) is the size of the training dataset,

  • \(W = 2^b\) is the size of the discretized weights space, with \(b\) being the number of discretization

    bits,

  • \(C\) is the number of classes of the training dataset.

Since the parameters \(k\), \(W\) and \(C\) can be considered constants for most purposes, the effective complexity is \(O(N^2)\).

References

Initializes the class.

Parameters:
  • model (KNeighborsClassifier) – The NN model to explain. Must be an instance of sklearn.neighbors.KNeighborsClassifier or sklearn.neighbors.RadiusNeighborsClassifier. The model must not use multi-output classification, i.e. the y value provided to model.fit(X, y) must be a 1D vector.

  • class_index (int | None) – The class index of the model to explain. Note that, as opposed to most Explainers, this must not be None!

  • n_bits (int)

  • data (np.ndarray | None)

  • index (ValidNNExplainerIndices)

  • max_order (int)

Raises:

sklearn.exceptions.NotFittedError – The constructor was called with a model that hasn’t been fitted.

explain_function(x)[source]¶

Explain a single prediction in terms of interaction values.

Parameters:
  • x (ndarray[tuple[Any, ...], dtype[floating]]) – A numpy array of a data point to be explained.

  • *args – Additional positional arguments passed to the explainer.

  • **kwargs – Additional keyword-only arguments passed to the explainer.

Return type:

InteractionValues

Returns:

The interaction values of the prediction.