shapley values for machine learning model
this topic defines shapley values, describes two available algorithms in the statistics and machine learning toolbox™ feature that computes shapley values, provides examples for each, and shows how to reduce the computational cost.
what is a shapley value?
in game theory, the shapley value of a player is the average marginal contribution of the player in a cooperative game. that is, shapley values are fair allocations, to individual players, of the total gain generated from a cooperative game. in the context of machine learning prediction, the shapley value of a feature for a query point explains the contribution of the feature to a prediction (the response for regression or the score of each class for classification) at the specified query point. the shapley value corresponds to the deviation of the prediction for the query point from the average prediction, due to the feature. for each query point, the sum of the shapley values for all features corresponds to the total deviation of the prediction from the average.
the shapley value of the ith feature for the query point x is defined by the value function v:
(1) |
m is the number of all features.
is the set of all features.
|s| is the cardinality of the set s, or the number of elements in the set s.
vx(s) is the value function of the features in a set s for the query point x. the value of the function indicates the expected contribution of the features in s to the prediction for the query point x.
shapley value in statistics and machine learning toolbox
you can compute shapley values for a machine learning model by using a shapley
object. use
the values to interpret the contributions of individual features in the model to the
prediction for a query point. you can compute shapley values in two ways:
create a
shapley
object for a machine learning model with a specified query point by using theshapley
function. the function computes the shapley values of all features in the model for the query point.create a
shapley
object for a machine learning model by using theshapley
function, and then compute the shapley values for a specified query point by using thefit
function.
algorithms
shapley
offers two
types of algorithms: interventional, which uses interventional distributions for the value
function, and conditional, which uses conditional distributions for the value function. you
can specify the algorithm type to use by setting the method
name-value
argument of the shapley
function or
the fit
function.
the difference between the two types of algorithms is the definition of the value function. both types define the value function so that the sum of the shapley values of a query point over all features corresponds to the total deviation of the prediction for the query point from the average.
therefore, the value function vx(s) must correspond to the expected contribution of the features in
s to the prediction (f) for the query point
x. the algorithms compute the expected contribution by using artificial
samples created from the specified data (x). you must provide
x
through the machine learning model input or a separate data input argument when you create a
shapley
object. in the artificial samples, the values for the features in
s come from the query point. for the rest of the features (features in
sc, the complement of
s), an interventional algorithm generates samples using interventional
distributions, whereas a conditional algorithm generates samples using conditional
distributions.
interventional algorithms
by default, shapley
uses one of these interventional algorithms:
kernel shap , linear shap , or tree shap .
computing exact shapley values can be computationally expensive if
shapley
uses all possible subsets s. therefore,
shapley
estimates the shapley values by limiting the maximum number of
subsets to use for the kernel shap algorithm. for more details, see computational cost.
for linear models and tree-based models, shapley
offers the linear
shap and tree shap algorithms, respectively. these algorithms are computationally less
expensive and compute exact shapley values. the algorithms return the same shapley values
that the kernel shap algorithm returns when using all possible subsets. the linear shap
and tree shap algorithms are different from the kernel shap algorithm in these
ways:
the linear shap and tree shap algorithms ignore the
responsetransform
property (for regression) and thescoretransform
property (for classification) of the machine learning model. that is, the algorithms compute shapley values based on raw responses or raw scores without applying response transformation or score transformation, respectively. the kernel shap algorithm uses transformed values if the model specifies transformation in theresponsetransform
orscoretransform
property.the kernel shap algorithm uses observations with missing values for tree models and ensemble models of tree learners. the linear shap and tree shap algorithms cannot handle observations with missing values for any models.
shapley
selects an algorithm based on the machine learning model type
and other specified options:
linear shap algorithm for these linear models:
regressionsvm
,compactregressionsvm
,classificationsvm
, andcompactclassificationsvm
models that use a linear kernel function
tree shap algorithm for these tree models and ensemble models with tree learners:
tree models —
regressiontree
,compactregressiontree
, , andcompactclassificationtree
ensemble models with tree learners — ,
regressionbaggedensemble
, , , , and models that use tree learnersto use the tree shap algorithm, you must specify the
method
name-value argument (ensemble aggregation method) as'bag'
,'adaboostm2'
,'gentleboost'
,'logitboost'
, or'rusboost'
when you train a classification ensemble model.
kernel shap algorithm for all other model types and for these cases:
if observations in the input predictor data or values in the query point contain missing values, the software uses kernel shap.
if you specify the
maxnumsubsets
name-value argument (maximum number of predictor subsets to use for shapley value computation) ofshapley
orfit
, the software uses kernel shap.in some cases, kernel shap can be computationally less expensive than tree shap. for example, kernel shap can be more efficient if a model contains a deep tree for low-dimensional data. the software heuristically selects an efficient algorithm.
an interventional algorithm defines the value function of the features in s at the query point x as the expected prediction with respect to the interventional distribution d, which is the joint distribution of the features in sc:
xs is the query point value for the features in s, and xsc are the features in sc.
to evaluate the value function vx(s) at the query point x, with the assumption that the
features are not highly correlated, shapley
uses the values in the data
x as samples of the interventional distribution d
for the features in sc:
n is the number of observations, and (xsc)j contains the values of the features in sc for the jth observation.
for example, suppose you have three features in x and four observations: (x11,x12,x13), (x21,x22,x23), (x31,x32,x33), and (x41,x42,x43). assume that s includes the first feature, and sc includes the rest. in this case, the value function of the first feature evaluated at the query point (x41,x42,x43) is
an interventional algorithm is computationally less expensive than a conditional algorithm and supports ordered categorical predictors. however, an interventional algorithm requires the feature independence assumption and uses out-of-distribution samples [4]. the artificial samples created with a mix of the query point and the data x can contain unrealistic observations. for example, (x41,x12,x13) might be a sample that does not occur in the full joint distribution of the three features.
conditional algorithm
specify the method
name-value argument as
'conditional'
to use the extension to the kernel shap algorithm , which is a conditional algorithm.
a conditional algorithm defines the value function of the features in s at the query point x using the conditional distribution of xsc, given that xs has the query point values:
to evaluate the value function vx(s) at the query point x, shapley
uses
nearest neighbors of the query point, which correspond to 10% of the observations in the
data x. this approach uses more realistic samples than an
interventional algorithm and does not require the feature independence assumption.
however, a conditional algorithm is computationally more expensive, does not support
ordered categorical predictors, and cannot handle nan
s in continuous
features. also, the algorithm might assign a nonzero shapley value to a dummy feature,
which does not contribute to the prediction, if the dummy feature is correlated with an
important feature [4].
specify computation algorithm
this example trains a linear classification model and computes shapley values using an interventional algorithm ('method','interventional'
) and then a conditional algorithm ('method','conditional'
).
train linear classification model
load the ionosphere
data set. this data set has 34 predictors and 351 binary responses for radar returns, either bad ('b'
) or good ('g'
).
load ionosphere
train a linear classification model. for better accuracy of linear coefficients, specify the objective function minimization technique ('solver'
name-value argument) as the limited-memory broyden-fletcher-goldfarb-shanno quasi-newton algorithm ('lbfgs'
).
mdl = fitclinear(x,y,'solver','lbfgs')
mdl = classificationlinear responsename: 'y' classnames: {'b' 'g'} scoretransform: 'none' beta: [34x1 double] bias: -3.7100 lambda: 0.0028 learner: 'svm' properties, methods
compute shapley values using interventional algorithm
compute the shapley values for the first observation using the linear shap algorithm, which is an interventional algorithm. you do not have to specify the method
name-value argument because 'interventional'
is the default.
querypoint = x(1,:);
explainer1 = shapley(mdl,x,'querypoint',querypoint);
for a classification model, shapley
computes shapley values using the predicted class score for each class. plot the shapley values for the predicted class by using the plot
function.
plot(explainer1)
the horizontal bar graph shows the shapley values for the 10 most important variables, sorted by their absolute values. each value explains the deviation of the score for the query point from the average score of the predicted class, due to the corresponding variable.
for a linear model, shapley
assumes features are independent from one another and computes the shapley values from the estimated coefficients (mdl.beta
) . compute the shapley values for the positive class (the second class in mdl.classnames
, 'g'
) directly from the estimated coefficients.
linearshapvalues = (mdl.beta'.*(querypoint-mean(x)))';
create a table containing the shapley values computed from shapley
and the values from the coefficients.
t = table(explainer1.shapleyvalues.predictor,explainer1.shapleyvalues.g,linearshapvalues, ... 'variablenames',{'predictor','values from shapley','values from coefficients'})
t=34×3 table
predictor values from shapley values from coefficients
_________ ___________________ ________________________
"x1" 0.28789 0.28789
"x2" 0 0
"x3" 0.20822 0.20822
"x4" -0.01998 -0.01998
"x5" 0.20872 0.20872
"x6" -0.076991 -0.076991
"x7" 0.19188 0.19188
"x8" -0.64386 -0.64386
"x9" 0.42348 0.42348
"x10" -0.030049 -0.030049
"x11" -0.23132 -0.23132
"x12" 0.1422 0.1422
"x13" -0.045973 -0.045973
"x14" -0.29022 -0.29022
"x15" 0.21051 0.21051
"x16" 0.13382 0.13382
⋮
compute shapley values using conditional algorithm
compute the shapley values for the first observation using the extension to the kernel shap algorithm, which is a conditional algorithm.
explainer2 = shapley(mdl,x,'querypoint',querypoint,'method','conditional');
plot the shapley values.
plot(explainer2)
the two algorithms identify different sets for the 10 most important variables. only two variables, x8
and x22
, are included in both sets.
computational cost
the computational cost for shapley values increases if the number of observations or features is large.
large number of observations
computing the value function (v) can be computationally expensive
if you have a large number of observations, for example, more than 1000. for faster
computation, use a smaller sample of the observations when you create a shapley
object,
or run in parallel by specifying useparallel
as
true
when you compute the values using the shapley
or
fit
function.
the useparallel
option is available when shapley
uses the tree shap algorithm for an ensemble of trees, the kernel shap algorithm, or the
extension to the kernel shap algorithm. computing in parallel requires parallel computing toolbox™.
large number of features
computing the summand in equation 1 for all possible subsets
s can be computationally expensive when m (the
number of features) is large for the kernel shap algorithm or the extension to the kernel
shap algorithm. the total number of subsets to consider is 2m. instead of computing the summand for all subsets, you can specify the
maximum number of subsets by using the maxnumsubsets
name-value argument. shapley
chooses subsets to use based on their weight
values. the weight of a subset is proportional to 1/(denominator of the summand), which
corresponds to 1 over the binomial coefficient: . therefore, a subset with a high or low value of cardinality has a large
weight value. shapley
includes the subsets with the highest weight first,
and then includes the other subsets in descending order based on their weight
values.
reduce computational cost
this example shows how to reduce the computational cost of shapley values when you have a large number of both observations and features.
load the sample data set nychousing2015
.
load nychousing2015
the data set includes 91,446 observations of 10 variables with information on the sales of properties in new york city in 2015. this example uses these variables to analyze the sale prices (saleprice
).
preprocess the data set. convert the datetime
array (saledate
) to the month numbers.
nychousing2015.saledate = month(nychousing2015.saledate);
train a neural network regression model.
mdl = fitrnet(nychousing2015,'saleprice','standardize',true);
compute the shapley values of all predictor variables for the first observation. measure the time required for the computation by using tic
and toc
.
tic
explainer1 = shapley(mdl,'querypoint',nychousing2015(1,:));
warning: computation can be slow because the predictor data has over 1000 observations. use a smaller sample of the training set or specify 'useparallel' as true for faster computation.
toc
elapsed time is 150.637868 seconds.
as the warning message indicates, the computation can be slow because the predictor data has over 1000 observations.
shapley
provides several options to reduce the computational cost when you have a large number of observations or features:
large number of observations — use a smaller sample of the training data and run in parallel by specifying
useparallel
astrue
.large number of features — specify the
maxnumsubsets
name-value argument to limit the number of subsets included in the computation.
start a parallel pool.
parpool;
starting parallel pool (parpool) using the 'processes' profile ... connected to parallel pool with 6 workers.
compute the shapley values again using a smaller sample of the training data and the parallel computing option. also, specify the maximum number of subsets as 2^5
.
numsamples = 5e2; tbl = datasample(nychousing2015,numsamples,'replace',false); tic explainer2 = shapley(mdl,tbl,'querypoint',nychousing2015(1,:), ... 'useparallel',true,'maxnumsubsets',2^5); toc
elapsed time is 0.844226 seconds.
specifying the additional options reduces the computation time.
references
[4] kumar, i. elizabeth, suresh venkatasubramanian, carlos scheidegger, and sorelle friedler. "problems with shapley-value-based explanations as feature importance measures." proceedings of the 37th international conference on machine learning 119 (july 2020): 5491–500.