shapiq.explainer.KNNExplainer¶

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

Bases: NNExplainerBase

Explainer for unweighted KNN models.

Implements the algorithm proposed by Jia et al.[1] to efficiently calculate Shapley values for unweighted KNN models. The algorithm itself has a linear time complexity, but requires sorting training points by distance to the test point, resulting in a time complexity of \(O(N \log N)\) for explaining a single data point.

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!

  • 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.

model: KNeighborsClassifier¶

The model to be explained, either as a Model instance or a callable function.