models.shap_values()
SHAP values (Lundberg and Lee, 2017): each feature’s share of the
Usage
models.shap_values(
model,
frame,
build,
background,
features=None,
output=None,
n_permutations=None,
seed=0,
max_exact=12
)difference between a row’s output and the mean output over a background sample, the Shapley values of the game v(S), the mean over the background rows of the output with the features in S taken from the row and the others from the background row (interventional, as SHAP’s KernelExplainer). Additive by construction: a row’s values sum to its output less the baseline.
Without n_permutations the values are exact, over every coalition (Kernel SHAP’s exact limit; up to max_exact features). With it they are estimated from that many feature orders (Strumbelj and Kononenko’s permutation sampling, order p from permutation(M, seed, p), so R gives the same values); each order’s contributions add up exactly, so the estimate is additive too.
Parameters
model: object-
A fitted model with
predict(design). frame: dict-
The rows to explain.
build: callable-
build(frame) -> Design. background: dict-
The background rows, the same columns as
frame: a sample of the portfolio, a few dozen to a few hundred rows. features: list or dict = None-
As for permutation_importance: names, lists of names moved together, or a dict from label to names; every column by default.
output: callable = None-
Applied to each prediction before averaging:
math.logexplains a log-link model’s linear predictor, where a GLM’s values are exactlybeta (x - mean background x)for each term. n_permutations: int = Noneseed: int = 0max_exact: int = 12
Returns
ShapValues
Examples
>>> import math
>>> from prospicio.models import Design, Glm, shap_values
>>> f = {"x": [float(i % 4) for i in range(40)], "z": [float(i % 3) for i in range(40)]}
>>> build = lambda f: Design([[1.0] * len(f["x"]), list(f["x"]), list(f["z"])], ["(Intercept)", "x", "z"])
>>> fit = Glm("poisson").fit(build(f), [1.0 + (i % 5) for i in range(40)])
>>> s = shap_values(fit, {"x": [3.0], "z": [0.0]}, build, f, output=math.log)
>>> round(s.values[0][0] - fit.coefficients[1] * (3.0 - 1.5), 12)0.0