-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
_tree.py
2091 lines (1854 loc) · 101 KB
/
_tree.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import io
import json
import os
import time
import warnings
from typing import Optional
import numpy as np
import pandas as pd
import scipy.sparse
import scipy.special
from packaging import version
from .. import maskers
from .._explanation import Explanation
from ..utils import assert_import, record_import_error, safe_isinstance
from ..utils._exceptions import (
DimensionError,
ExplainerError,
InvalidFeaturePerturbationError,
InvalidMaskerError,
InvalidModelError,
)
from ..utils._legacy import DenseData
from ._explainer import Explainer
from .other._ubjson import decode_ubjson_buffer
try:
from .. import _cext
except ImportError as e:
record_import_error("cext", "C extension was not built during install!", e)
try:
import pyspark # noqa
except ImportError as e:
record_import_error("pyspark", "PySpark could not be imported!", e)
output_transform_codes = {
"identity": 0,
"logistic": 1,
"logistic_nlogloss": 2,
"squared_loss": 3,
}
feature_perturbation_codes = {
"interventional": 0,
"tree_path_dependent": 1,
"global_path_dependent": 2,
}
def _check_xgboost_version(v: str):
if version.parse(v) < version.parse("1.6"):
raise RuntimeError(
f"SHAP requires XGBoost >= v1.6 , but found version {v}. Please upgrade"
" XGBoost."
)
def _xgboost_n_iterations(tree_limit: int, num_stacked_models: int) -> int:
"""Convert number of trees to number of iterations for XGBoost models."""
if tree_limit == -1:
tree_limit = 0
n_iterations = tree_limit // num_stacked_models
return n_iterations
def _xgboost_cat_unsupported(model):
if model.model_type == "xgboost" and model.cat_feature_indices is not None:
raise NotImplementedError(
"Categorical split is not yet supported. You can still use"
" TreeExplainer with `feature_perturbation=tree_path_dependent`."
)
class TreeExplainer(Explainer):
"""Uses Tree SHAP algorithms to explain the output of ensemble tree models.
Tree SHAP is a fast and exact method to estimate SHAP values for tree models
and ensembles of trees, under several different possible assumptions about
feature dependence. It depends on fast C++ implementations either inside an
external model package or in the local compiled C extension.
Examples
--------
See `Tree explainer examples <https://shap.readthedocs.io/en/latest/api_examples/explainers/Tree.html>`_
"""
def __init__(
self,
model,
data=None,
model_output="raw",
feature_perturbation="interventional",
feature_names=None,
approximate=False,
# FIXME: The `link` and `linearize_link` arguments are ignored. GH #3513
link=None,
linearize_link=None,
):
"""Build a new Tree explainer for the passed model.
Parameters
----------
model : model object
The tree based machine learning model that we want to explain.
XGBoost, LightGBM, CatBoost, Pyspark and most tree-based
scikit-learn models are supported.
data : numpy.array or pandas.DataFrame
The background dataset to use for integrating out features.
This argument is optional when
``feature_perturbation="tree_path_dependent"``, since in that case
we can use the number of training samples that went down each tree
path as our background dataset (this is recorded in the ``model``
object).
feature_perturbation : "interventional" (default) or "tree_path_dependent" (default when data=None)
Since SHAP values rely on conditional expectations, we need to
decide how to handle correlated (or otherwise dependent) input
features.
The "interventional" approach breaks the dependencies between
features according to the rules dictated by causal inference
(Janzing et al. 2019). Note that the "interventional" option
requires a background dataset ``data``, and its runtime scales
linearly with the size of the background dataset you use. Anywhere
from 100 to 1000 random background samples are good sizes to use.
The "tree_path_dependent" approach is to just follow the trees and
use the number of training examples that went down each leaf to
represent the background distribution. This approach does not
require a background dataset, and so is used by default when no
background dataset is provided.
model_output : "raw", "probability", "log_loss", or model method name
What output of the model should be explained.
* If "raw", then we explain the raw output of the trees, which
varies by model. For regression models, "raw" is the standard
output. For binary classification in XGBoost, this is the log odds
ratio.
* If "probability", then we explain the output of the model
transformed into probability space (note that this means the SHAP
values now sum to the probability output of the model).
* If "log_loss", then we explain the natural logarithm of the model
loss function, so that the SHAP values sum up to the log loss of
the model for each sample. This is helpful for breaking down model
performance by feature.
* If ``model_output`` is the name of a supported prediction method
on the ``model`` object, then we explain the output of that model
method name. For example, ``model_output="predict_proba"``
explains the result of calling ``model.predict_proba``.
Currently the "probability" and "log_loss" options are only
supported when ``feature_perturbation="interventional"``.
"""
if feature_names is not None:
self.data_feature_names = feature_names
elif isinstance(data, pd.DataFrame):
self.data_feature_names = list(data.columns)
masker = data
super().__init__(model, masker, feature_names=feature_names)
if type(self.masker) is maskers.Independent:
data = self.masker.data
elif masker is not None:
raise InvalidMaskerError(f"Unsupported masker type: {str(type(self.masker))}!")
if getattr(self.masker, "clustering", None) is not None:
raise ExplainerError("TreeExplainer does not support clustered data inputs! Please use shap.Explainer or pass an unclustered masker!")
if isinstance(data, pd.DataFrame):
self.data = data.values
elif isinstance(data, DenseData):
self.data = data.data
else:
self.data = data
if self.data is None:
feature_perturbation = "tree_path_dependent"
#warnings.warn("Setting feature_perturbation = \"tree_path_dependent\" because no background data was given.")
elif feature_perturbation == "interventional" and self.data.shape[0] > 1_000:
wmsg = (
f"Passing {self.data.shape[0]} background samples may lead to slow runtimes. Consider "
"using shap.sample(data, 100) to create a smaller background data set."
)
warnings.warn(wmsg)
self.data_missing = None if self.data is None else pd.isna(self.data)
self.feature_perturbation = feature_perturbation
self.expected_value = None
self.model = TreeEnsemble(model, self.data, self.data_missing, model_output)
self.model_output = model_output
#self.model_output = self.model.model_output # this allows the TreeEnsemble to translate model outputs types by how it loads the model
self.approximate = approximate
if feature_perturbation not in feature_perturbation_codes:
raise InvalidFeaturePerturbationError("Invalid feature_perturbation option!")
# check for unsupported combinations of feature_perturbation and model_outputs
if feature_perturbation == "tree_path_dependent":
if self.model.model_output != "raw":
raise ValueError("Only model_output=\"raw\" is supported for feature_perturbation=\"tree_path_dependent\"")
elif data is None:
raise ValueError("A background dataset must be provided unless you are using feature_perturbation=\"tree_path_dependent\"!")
if self.model.model_output != "raw":
if self.model.objective is None and self.model.tree_output is None:
emsg = (
"Model does not have a known objective or output type! When model_output is "
"not \"raw\" then we need to know the model's objective or link function."
)
raise Exception(emsg)
# A change in the signature of `xgboost.Booster.predict()` method has been introduced in XGBoost v1.4:
# The introduced `iteration_range` parameter is used when obtaining SHAP (incl. interaction) values from XGBoost models.
if self.model.model_type == 'xgboost':
import xgboost
_check_xgboost_version(xgboost.__version__)
# compute the expected value if we have a parsed tree for the cext
if self.model.model_output == "log_loss":
self.expected_value = self.__dynamic_expected_value
elif data is not None:
try:
self.expected_value = self.model.predict(self.data).mean(0)
except ValueError:
raise ExplainerError("Currently TreeExplainer can only handle models with categorical splits when " \
"feature_perturbation=\"tree_path_dependent\" and no background data is passed. Please try again using " \
"shap.TreeExplainer(model, feature_perturbation=\"tree_path_dependent\").")
if hasattr(self.expected_value, '__len__') and len(self.expected_value) == 1:
self.expected_value = self.expected_value[0]
elif hasattr(self.model, "node_sample_weight"):
self.expected_value = self.model.values[:,0].sum(0)
if self.expected_value.size == 1:
self.expected_value = self.expected_value[0]
self.expected_value += self.model.base_offset
if self.model.model_output != "raw":
self.expected_value = None # we don't handle transforms in this case right now...
# if our output format requires binary classification to be represented as two outputs then we do that here
if self.model.model_output == "probability_doubled" and self.expected_value is not None:
self.expected_value = [1 - self.expected_value, self.expected_value]
def __dynamic_expected_value(self, y):
"""This computes the expected value conditioned on the given label value."""
return self.model.predict(self.data, np.ones(self.data.shape[0]) * y).mean(0)
def __call__(self, X, y=None, interactions=False, check_additivity=True):
start_time = time.time()
if isinstance(X, pd.DataFrame):
feature_names = list(X.columns)
else:
feature_names = getattr(self, "data_feature_names", None)
if not interactions:
v = self.shap_values(X, y=y, from_call=True, check_additivity=check_additivity, approximate=self.approximate)
if isinstance(v, list):
v = np.stack(v, axis=-1) # put outputs at the end
else:
assert not self.approximate, "Approximate computation not yet supported for interaction effects!"
v = self.shap_interaction_values(X)
# the Explanation object expects an `expected_value` for each row
if hasattr(self.expected_value, "__len__") and len(self.expected_value) > 1:
# `expected_value` is a list / array of numbers, length k, e.g. for multi-output scenarios
# we repeat it N times along the first axis, so ev_tiled.shape == (N, k)
if isinstance(v, list):
num_rows = v[0].shape[0]
else:
num_rows = v.shape[0]
ev_tiled = np.tile(self.expected_value, (num_rows, 1))
else:
# `expected_value` is a scalar / array of 1 number, so we simply repeat it for every row in `v`
# ev_tiled.shape == (N,)
ev_tiled = np.tile(self.expected_value, v.shape[0])
# cf. GH dsgibbons#66, this conversion to numpy array should be done AFTER
# calculation of shap values
if isinstance(X, pd.DataFrame):
X = X.values
elif safe_isinstance(X, "xgboost.core.DMatrix"):
import xgboost
if version.parse(xgboost.__version__) < version.parse("1.7.0"): # pragma: no cover
# cf. GH #3357
wmsg = (
"`shap.Explanation` does not support `xgboost.DMatrix` objects for xgboost < 1.7, "
"so the `data` attribute of the `Explanation` object will be set to None. If "
"you require the `data` attribute (e.g. using `shap.plots`), then either "
"update your xgboost to >=1.7.0 or explicitly set `Explanation.data = X`, where "
"`X` is a numpy or scipy array."
)
warnings.warn(wmsg)
X = None
else:
X: scipy.sparse.csr_matrix = X.get_data()
return Explanation(
v,
base_values=ev_tiled,
data=X,
feature_names=feature_names,
compute_time=time.time() - start_time,
)
def _validate_inputs(self, X, y, tree_limit, check_additivity):
# see if we have a default tree_limit in place.
if tree_limit is None:
tree_limit = -1 if self.model.tree_limit is None else self.model.tree_limit
if tree_limit < 0 or tree_limit > self.model.values.shape[0]:
tree_limit = self.model.values.shape[0]
# convert dataframes
if isinstance(X, (pd.Series, pd.DataFrame)):
X = X.values
flat_output = False
if len(X.shape) == 1:
flat_output = True
X = X.reshape(1, X.shape[0])
if X.dtype != self.model.input_dtype:
X = X.astype(self.model.input_dtype)
X_missing = np.isnan(X, dtype=bool)
assert isinstance(X, np.ndarray), "Unknown instance type: " + str(type(X))
assert len(X.shape) == 2, "Passed input data matrix X must have 1 or 2 dimensions!"
if self.model.model_output == "log_loss":
if y is None:
emsg = (
"Both samples and labels must be provided when model_output = \"log_loss\" "
"(i.e. `explainer.shap_values(X, y)`)!"
)
raise ExplainerError(emsg)
if X.shape[0] != len(y):
emsg = (
f"The number of labels ({len(y)}) does not match the number of samples "
f"to explain ({X.shape[0]})!"
)
raise DimensionError(emsg)
if self.feature_perturbation == "tree_path_dependent":
if not self.model.fully_defined_weighting:
emsg = (
"The background dataset you provided does "
"not cover all the leaves in the model, "
"so TreeExplainer cannot run with the "
"feature_perturbation=\"tree_path_dependent\" option! "
"Try providing a larger background "
"dataset, no background dataset, or using "
"feature_perturbation=\"interventional\"."
)
raise ExplainerError(emsg)
if check_additivity and self.model.model_type == "pyspark":
warnings.warn(
"check_additivity requires us to run predictions which is not supported with "
"spark, "
"ignoring."
" Set check_additivity=False to remove this warning")
check_additivity = False
return X, y, X_missing, flat_output, tree_limit, check_additivity
def shap_values(self, X, y=None, tree_limit=None, approximate=False, check_additivity=True, from_call=False):
"""Estimate the SHAP values for a set of samples.
Parameters
----------
X : numpy.array, pandas.DataFrame or catboost.Pool (for catboost)
A matrix of samples (# samples x # features) on which to explain the model's output.
y : numpy.array
An array of label values for each sample. Used when explaining loss functions.
tree_limit : None (default) or int
Limit the number of trees used by the model. By default, the limit of the original model
is used (``None``). ``-1`` means no limit.
approximate : bool
Run fast, but only roughly approximate the Tree SHAP values. This runs a method
previously proposed by Saabas which only considers a single feature ordering. Take care
since this does not have the consistency guarantees of Shapley values and places too
much weight on lower splits in the tree.
check_additivity : bool
Run a validation check that the sum of the SHAP values equals the output of the model. This
check takes only a small amount of time, and will catch potential unforeseen errors.
Note that this check only runs right now when explaining the margin of the model.
Returns
-------
np.array
Estimated SHAP values, usually of shape ``(# samples x # features)``.
Each row sums to the difference between the model output for that
sample and the expected value of the model output (which is stored
as the ``expected_value`` attribute of the explainer).
The shape of the returned array depends on the number of model outputs:
* one output: array of shape ``(#num_samples, *X.shape[1:])``.
* multiple outputs: array of shape ``(#num_samples, *X.shape[1:],
#num_outputs)``.
.. versionchanged:: 0.45.0
Return type for models with multiple outputs changed from list to np.ndarray.
"""
# see if we have a default tree_limit in place.
if tree_limit is None:
tree_limit = -1 if self.model.tree_limit is None else self.model.tree_limit
# shortcut using the C++ version of Tree SHAP in XGBoost, LightGBM, and CatBoost
if self.feature_perturbation == "tree_path_dependent" and self.model.model_type != "internal" and self.data is None:
model_output_vals = None
phi = None
if self.model.model_type == "xgboost":
import xgboost
n_iterations = _xgboost_n_iterations(
tree_limit, self.model.num_stacked_models
)
if not isinstance(X, xgboost.core.DMatrix):
# Retrieve any DMatrix properties if they have been set on the TreeEnsemble Class
dmatrix_props = getattr(self.model, "_xgb_dmatrix_props", {})
X = xgboost.DMatrix(X, **dmatrix_props)
phi = self.model.original_model.predict(
X, iteration_range=(0, n_iterations), pred_contribs=True,
approx_contribs=approximate, validate_features=False
)
if check_additivity and self.model.model_output == "raw":
model_output_vals = self.model.original_model.predict(
X, iteration_range=(0, n_iterations), output_margin=True,
validate_features=False
)
elif self.model.model_type == "lightgbm":
assert not approximate, "approximate=True is not supported for LightGBM models!"
phi = self.model.original_model.predict(X, num_iteration=tree_limit, pred_contrib=True)
# Note: the data must be joined on the last axis
if self.model.original_model.params['objective'] == 'binary':
if not from_call:
warnings.warn('LightGBM binary classifier with TreeExplainer shap values output has changed to a list of ndarray')
if phi.shape[1] != X.shape[1] + 1:
try:
phi = phi.reshape(X.shape[0], phi.shape[1]//(X.shape[1]+1), X.shape[1]+1)
except ValueError as e:
emsg = (
"This reshape error is often caused by passing a bad data matrix to SHAP. "
"See https://github.com/shap/shap/issues/580."
)
raise ValueError(emsg) from e
elif self.model.model_type == "catboost": # thanks to the CatBoost team for implementing this...
assert not approximate, "approximate=True is not supported for CatBoost models!"
assert tree_limit == -1, "tree_limit is not yet supported for CatBoost models!"
import catboost
if type(X) != catboost.Pool:
X = catboost.Pool(X, cat_features=self.model.cat_feature_indices)
phi = self.model.original_model.get_feature_importance(data=X, fstr_type='ShapValues')
# note we pull off the last column and keep it as our expected_value
if phi is not None:
if len(phi.shape) == 3:
self.expected_value = [phi[0, i, -1] for i in range(phi.shape[1])]
out = [phi[:, i, :-1] for i in range(phi.shape[1])]
else:
self.expected_value = phi[0, -1]
out = phi[:, :-1]
if check_additivity and model_output_vals is not None:
self.assert_additivity(out, model_output_vals)
if isinstance(out, list):
out = np.stack(out, axis=-1)
return out
X, y, X_missing, flat_output, tree_limit, check_additivity = self._validate_inputs(
X, y, tree_limit, check_additivity
)
transform = self.model.get_transform()
_xgboost_cat_unsupported(self.model)
# run the core algorithm using the C extension
assert_import("cext")
phi = np.zeros((X.shape[0], X.shape[1]+1, self.model.num_outputs))
if not approximate:
_cext.dense_tree_shap(
self.model.children_left, self.model.children_right, self.model.children_default,
self.model.features, self.model.thresholds, self.model.values, self.model.node_sample_weight,
self.model.max_depth, X, X_missing, y, self.data, self.data_missing, tree_limit,
self.model.base_offset, phi, feature_perturbation_codes[self.feature_perturbation],
output_transform_codes[transform], False
)
else:
_cext.dense_tree_saabas(
self.model.children_left, self.model.children_right, self.model.children_default,
self.model.features, self.model.thresholds, self.model.values,
self.model.max_depth, tree_limit, self.model.base_offset, output_transform_codes[transform],
X, X_missing, y, phi
)
out = self._get_shap_output(phi, flat_output)
if check_additivity and self.model.model_output == "raw":
self.assert_additivity(out, self.model.predict(X))
# This statements handles the case of multiple outputs
# e.g. a multi-class classification problem, multi-target regression problem
# in this case the output shape corresponds to [num_samples, num_features, num_outputs]
if isinstance(out, list):
out = np.stack(out, axis=-1)
return out
def _get_shap_output(self, phi, flat_output):
"""Pull off the last column of ``phi`` and keep it as our expected_value."""
if self.model.num_outputs == 1:
if self.expected_value is None and self.model.model_output != "log_loss":
self.expected_value = phi[0, -1, 0]
if flat_output:
out = phi[0, :-1, 0]
else:
out = phi[:, :-1, 0]
else:
if self.expected_value is None and self.model.model_output != "log_loss":
self.expected_value = [phi[0, -1, i] for i in range(phi.shape[2])]
if flat_output:
out = [phi[0, :-1, i] for i in range(self.model.num_outputs)]
else:
out = [phi[:, :-1, i] for i in range(self.model.num_outputs)]
# if our output format requires binary classification to be represented as two outputs then we do that here
if self.model.model_output == "probability_doubled":
out = [-out, out]
return out
def shap_interaction_values(self, X, y=None, tree_limit=None):
"""Estimate the SHAP interaction values for a set of samples.
Parameters
----------
X : numpy.array, pandas.DataFrame or catboost.Pool (for catboost)
A matrix of samples (# samples x # features) on which to explain the model's output.
y : numpy.array
An array of label values for each sample. Used when explaining loss functions (not yet supported).
tree_limit : None (default) or int
Limit the number of trees used by the model. By default, the limit of the original model
is used (``None``). ``-1`` means no limit.
Returns
-------
np.array
Returns a matrix. The shape depends on the number of model outputs:
* one output: matrix of shape (#num_samples, #features, #features).
* multiple outputs: matrix of shape (#num_samples, #features, #features, #num_outputs).
The matrix (#num_samples, # features, # features) for each sample sums
to the difference between the model output for that sample and the expected value of the model output
(which is stored in the ``expected_value`` attribute of the explainer). Each row of this matrix sums to the
SHAP value for that feature for that sample. The diagonal entries of the matrix represent the
"main effect" of that feature on the prediction. The symmetric off-diagonal entries represent the
interaction effects between all pairs of features for that sample.
For models with vector outputs, this returns a list of tensors, one for each output.
.. versionchanged:: 0.45.0
Return type for models with multiple outputs changed from list to np.ndarray.
"""
assert self.model.model_output == "raw", "Only model_output = \"raw\" is supported for SHAP interaction values right now!"
#assert self.feature_perturbation == "tree_path_dependent", "Only feature_perturbation = \"tree_path_dependent\" is supported for SHAP interaction values right now!"
transform = "identity"
# see if we have a default tree_limit in place.
if tree_limit is None:
tree_limit = -1 if self.model.tree_limit is None else self.model.tree_limit
# shortcut using the C++ version of Tree SHAP in XGBoost
if (
self.model.model_type == "xgboost"
and self.feature_perturbation == "tree_path_dependent"
):
import xgboost
if not isinstance(X, xgboost.core.DMatrix):
X = xgboost.DMatrix(X)
n_iterations = _xgboost_n_iterations(
tree_limit, self.model.num_stacked_models
)
phi = self.model.original_model.predict(
X,
iteration_range=(0, n_iterations),
pred_interactions=True,
validate_features=False
)
# note we pull off the last column and keep it as our expected_value
# multi-outputs
if len(phi.shape) == 4:
self.expected_value = [phi[0, i, -1, -1] for i in range(phi.shape[1])]
# phi is given as [#num_observations, #num_classes, #features, #features]
# slice out the expected values, then move the classes to the last dimension
return np.swapaxes(phi[:, :, :-1, :-1], axis1=1, axis2=3)
# regression and binary classification case
else:
self.expected_value = phi[0, -1, -1]
return phi[:, :-1, :-1]
elif (self.model.model_type == "catboost") and (self.feature_perturbation == "tree_path_dependent"): # thanks again to the CatBoost team for implementing this...
assert tree_limit == -1, "tree_limit is not yet supported for CatBoost models!"
import catboost
if type(X) != catboost.Pool:
X = catboost.Pool(X, cat_features=self.model.cat_feature_indices)
phi = self.model.original_model.get_feature_importance(data=X, fstr_type='ShapInteractionValues')
# note we pull off the last column and keep it as our expected_value
if len(phi.shape) == 4:
self.expected_value = getattr(self, "expected_value", [phi[0, i, -1, -1] for i in range(phi.shape[1])])
return [phi[:, i, :-1, :-1] for i in range(phi.shape[1])]
else:
self.expected_value = getattr(self, "expected_value", phi[0, -1, -1])
return phi[:, :-1, :-1]
X, y, X_missing, flat_output, tree_limit, _ = self._validate_inputs(X, y, tree_limit, False)
# run the core algorithm using the C extension
assert_import("cext")
phi = np.zeros((X.shape[0], X.shape[1]+1, X.shape[1]+1, self.model.num_outputs))
_cext.dense_tree_shap(
self.model.children_left, self.model.children_right, self.model.children_default,
self.model.features, self.model.thresholds, self.model.values, self.model.node_sample_weight,
self.model.max_depth, X, X_missing, y, self.data, self.data_missing, tree_limit,
self.model.base_offset, phi, feature_perturbation_codes[self.feature_perturbation],
output_transform_codes[transform], True
)
return self._get_shap_interactions_output(phi, flat_output)
def _get_shap_interactions_output(self, phi, flat_output):
"""Pull off the last column and keep it as our expected_value"""
if self.model.num_outputs == 1:
# get expected value only if not already set
self.expected_value = getattr(self, "expected_value", phi[0, -1, -1, 0])
if flat_output:
out = phi[0, :-1, :-1, 0]
else:
out = phi[:, :-1, :-1, 0]
else:
self.expected_value = [phi[0, -1, -1, i] for i in range(phi.shape[3])]
if flat_output:
out = np.stack([phi[0, :-1, :-1, i] for i in range(self.model.num_outputs)], axis=-1)
else:
out = np.stack([phi[:, :-1, :-1, i] for i in range(self.model.num_outputs)], axis=-1)
return out
def assert_additivity(self, phi, model_output):
def check_sum(sum_val, model_output):
diff = np.abs(sum_val - model_output)
if np.max(diff / (np.abs(sum_val) + 1e-2)) > 1e-2:
ind = np.argmax(diff)
err_msg = "Additivity check failed in TreeExplainer! Please ensure the data matrix you passed to the " \
"explainer is the same shape that the model was trained on. If your data shape is correct " \
"then please report this on GitHub."
if self.feature_perturbation != "interventional":
err_msg += " Consider retrying with the feature_perturbation='interventional' option."
err_msg += " This check failed because for one of the samples the sum of the SHAP values" \
f" was {sum_val[ind]:f}, while the model output was {model_output[ind]:f}. If this" \
" difference is acceptable you can set check_additivity=False to disable this check."
raise ExplainerError(err_msg)
if isinstance(phi, list):
for i in range(len(phi)):
check_sum(self.expected_value[i] + phi[i].sum(-1), model_output[:,i])
else:
check_sum(self.expected_value + phi.sum(-1), model_output)
@staticmethod
def supports_model_with_masker(model, masker):
"""Determines if this explainer can handle the given model.
This is an abstract static method meant to be implemented by each subclass.
"""
if not isinstance(masker, (maskers.Independent)) and masker is not None:
return False
try:
TreeEnsemble(model)
except Exception:
return False
return True
class TreeEnsemble:
"""An ensemble of decision trees.
This object provides a common interface to many different types of models.
"""
def __init__(self, model, data=None, data_missing=None, model_output=None):
self.model_type = "internal"
self.trees = None
self.base_offset = 0
self.model_output = model_output
self.objective = None # what we explain when explaining the loss of the model
self.tree_output = None # what are the units of the values in the leaves of the trees
self.internal_dtype = np.float64
self.input_dtype = np.float64 # for sklearn we need to use np.float32 to always get exact matches to their predictions
self.data = data
self.data_missing = data_missing
self.fully_defined_weighting = True # does the background dataset land in every leaf (making it valid for the tree_path_dependent method)
self.tree_limit = None # used for limiting the number of trees we use by default (like from early stopping)
self.num_stacked_models = 1 # If this is greater than 1 it means we have multiple stacked models with the same number of trees in each model (XGBoost multi-output style)
self.cat_feature_indices = None # If this is set it tells us which features are treated categorically
# we use names like keras
objective_name_map = {
"mse": "squared_error",
"variance": "squared_error",
"friedman_mse": "squared_error",
"reg:linear": "squared_error",
"reg:squarederror": "squared_error",
"regression": "squared_error",
"regression_l2": "squared_error",
"mae": "absolute_error",
"gini": "binary_crossentropy",
"entropy": "binary_crossentropy",
"reg:logistic": "binary_crossentropy",
"binary:logistic": "binary_crossentropy",
"binary_logloss": "binary_crossentropy",
"binary": "binary_crossentropy",
}
tree_output_name_map = {
"regression": "raw_value",
"regression_l2": "squared_error",
"reg:linear": "raw_value",
"reg:squarederror": "raw_value",
"reg:logistic": "log_odds",
"binary:logistic": "log_odds",
"binary_logloss": "log_odds",
"binary": "log_odds",
}
if isinstance(model, dict) and "trees" in model:
# This allows a dictionary to be passed that represents the model.
# this dictionary has several numerical parameters and also a list of trees
# where each tree is a dictionary describing that tree
if "internal_dtype" in model:
self.internal_dtype = model["internal_dtype"]
if "input_dtype" in model:
self.input_dtype = model["input_dtype"]
if "objective" in model:
self.objective = model["objective"]
if "tree_output" in model:
self.tree_output = model["tree_output"]
if "base_offset" in model:
self.base_offset = model["base_offset"]
self.trees = [SingleTree(t, data=data, data_missing=data_missing) for t in model["trees"]]
elif isinstance(model, list) and isinstance(model[0], SingleTree): # old-style direct-load format
self.trees = model
elif safe_isinstance(
model,
[
"sklearn.ensemble.RandomForestRegressor",
"sklearn.ensemble.forest.RandomForestRegressor",
"econml.grf._base_grf.BaseGRF",
],
):
assert hasattr(model, "estimators_"), "Model has no `estimators_`! Have you called `model.fit`?"
self.internal_dtype = model.estimators_[0].tree_.value.dtype.type
self.input_dtype = np.float32
scaling = 1.0 / len(model.estimators_) # output is average of trees
self.trees = [SingleTree(e.tree_, scaling=scaling, data=data, data_missing=data_missing) for e in model.estimators_]
self.objective = objective_name_map.get(model.criterion, None)
self.tree_output = "raw_value"
elif safe_isinstance(
model,
[
"sklearn.ensemble.IsolationForest",
"sklearn.ensemble._iforest.IsolationForest",
],
):
self.dtype = np.float32
scaling = 1.0 / len(model.estimators_) # output is average of trees
self.trees = [IsoTree(e.tree_, f, scaling=scaling, data=data, data_missing=data_missing) for e, f in zip(model.estimators_, model.estimators_features_)]
self.tree_output = "raw_value"
elif safe_isinstance(model, ["pyod.models.iforest.IForest"]):
self.dtype = np.float32
scaling = 1.0 / len(model.estimators_) # output is average of trees
self.trees = [IsoTree(e.tree_, f, scaling=scaling, data=data, data_missing=data_missing) for e, f in zip(model.detector_.estimators_, model.detector_.estimators_features_)]
self.tree_output = "raw_value"
elif safe_isinstance(
model,
[
"sklearn.ensemble.ExtraTreesRegressor",
"sklearn.ensemble.forest.ExtraTreesRegressor",
"skopt.learning.forest.RandomForestRegressor",
"skopt.learning.forest.ExtraTreesRegressor",
],
):
assert hasattr(model, "estimators_"), "Model has no `estimators_`! Have you called `model.fit`?"
self.internal_dtype = model.estimators_[0].tree_.value.dtype.type
self.input_dtype = np.float32
scaling = 1.0 / len(model.estimators_) # output is average of trees
self.trees = [SingleTree(e.tree_, scaling=scaling, data=data, data_missing=data_missing) for e in model.estimators_]
self.objective = objective_name_map.get(model.criterion, None)
self.tree_output = "raw_value"
elif safe_isinstance(
model,
[
"sklearn.tree.DecisionTreeRegressor",
"sklearn.tree.tree.DecisionTreeRegressor",
"econml.grf._base_grftree.GRFTree",
],
):
self.internal_dtype = model.tree_.value.dtype.type
self.input_dtype = np.float32
self.trees = [SingleTree(model.tree_, data=data, data_missing=data_missing)]
self.objective = objective_name_map.get(model.criterion, None)
self.tree_output = "raw_value"
elif safe_isinstance(
model,
[
"sklearn.tree.DecisionTreeClassifier",
"sklearn.tree.tree.DecisionTreeClassifier",
],
):
self.internal_dtype = model.tree_.value.dtype.type
self.input_dtype = np.float32
self.trees = [SingleTree(model.tree_, normalize=True, data=data, data_missing=data_missing)]
self.objective = objective_name_map.get(model.criterion, None)
self.tree_output = "probability"
elif safe_isinstance(
model,
[
"sklearn.ensemble.ExtraTreesClassifier",
"sklearn.ensemble.forest.ExtraTreesClassifier",
"sklearn.ensemble.RandomForestClassifier",
"sklearn.ensemble.forest.RandomForestClassifier",
],
):
assert hasattr(model, "estimators_"), "Model has no `estimators_`! Have you called `model.fit`?"
self.internal_dtype = model.estimators_[0].tree_.value.dtype.type
self.input_dtype = np.float32
scaling = 1.0 / len(model.estimators_) # output is average of trees
self.trees = [SingleTree(e.tree_, normalize=True, scaling=scaling, data=data, data_missing=data_missing) for e in model.estimators_]
self.objective = objective_name_map.get(model.criterion, None)
self.tree_output = "probability"
elif safe_isinstance(
model,
[
"sklearn.ensemble.GradientBoostingRegressor",
"sklearn.ensemble.gradient_boosting.GradientBoostingRegressor",
],
):
self.input_dtype = np.float32
# currently we only support the mean and quantile estimators
if safe_isinstance(
model.init_,
[
"sklearn.ensemble.MeanEstimator",
"sklearn.ensemble.gradient_boosting.MeanEstimator",
],
):
self.base_offset = model.init_.mean
elif safe_isinstance(
model.init_,
[
"sklearn.ensemble.QuantileEstimator",
"sklearn.ensemble.gradient_boosting.QuantileEstimator",
],
):
self.base_offset = model.init_.quantile
elif safe_isinstance(model.init_, "sklearn.dummy.DummyRegressor"):
self.base_offset = model.init_.constant_[0]
else:
emsg = f"Unsupported init model type: {type(model.init_)}"
raise InvalidModelError(emsg)
self.trees = [SingleTree(e.tree_, scaling=model.learning_rate, data=data, data_missing=data_missing) for e in model.estimators_[:,0]]
self.objective = objective_name_map.get(model.criterion, None)
self.tree_output = "raw_value"
elif safe_isinstance(model, ["sklearn.ensemble.HistGradientBoostingRegressor"]):
# cf. GH #1028 for implementation notes
import sklearn
if self.model_output == "predict":
self.model_output = "raw"
self.input_dtype = sklearn.ensemble._hist_gradient_boosting.common.X_DTYPE
self.base_offset = model._baseline_prediction
self.trees = []
for p in model._predictors:
nodes = p[0].nodes
# each node has values: ('value', 'count', 'feature_idx', 'threshold', 'missing_go_to_left', 'left', 'right', 'gain', 'depth', 'is_leaf', 'bin_threshold')
tree = {
"children_left": np.array([-1 if n[9] else n[5] for n in nodes]),
"children_right": np.array([-1 if n[9] else n[6] for n in nodes]),
"children_default": np.array([-1 if n[9] else (n[5] if n[4] else n[6]) for n in nodes]),
"features": np.array([-2 if n[9] else n[2] for n in nodes]),
"thresholds": np.array([n[3] for n in nodes], dtype=np.float64),
"values": np.array([[n[0]] for n in nodes], dtype=np.float64),
"node_sample_weight": np.array([n[1] for n in nodes], dtype=np.float64),
}
self.trees.append(SingleTree(tree, data=data, data_missing=data_missing))
self.objective = objective_name_map.get(model.loss, None)
self.tree_output = "raw_value"
elif safe_isinstance(model, ["sklearn.ensemble.HistGradientBoostingClassifier"]):
# cf. GH #1028 for implementation notes
import sklearn
self.base_offset = model._baseline_prediction
has_len = hasattr(self.base_offset, "__len__")
# Note for newer sklearn versions, the base_offset is an array even for binary classification
if has_len and self.base_offset.shape == (1, 1):
self.base_offset = self.base_offset[0, 0]
has_len = False
if has_len and self.model_output != "raw":
emsg = (
"Multi-output HistGradientBoostingClassifier models are not yet supported unless "
"model_output=\"raw\". See GitHub issue #1028."
)
raise NotImplementedError(emsg)
self.input_dtype = sklearn.ensemble._hist_gradient_boosting.common.X_DTYPE
self.num_stacked_models = len(model._predictors[0])
if self.model_output == "predict_proba":
if self.num_stacked_models == 1:
self.model_output = "probability_doubled" # with predict_proba we need to double the outputs to match
else:
self.model_output = "probability"
self.trees = []
for p in model._predictors:
for i in range(self.num_stacked_models):
nodes = p[i].nodes
# each node has values: ('value', 'count', 'feature_idx', 'threshold', 'missing_go_to_left', 'left', 'right', 'gain', 'depth', 'is_leaf', 'bin_threshold')
tree = {
"children_left": np.array([-1 if n[9] else n[5] for n in nodes]),
"children_right": np.array([-1 if n[9] else n[6] for n in nodes]),
"children_default": np.array([-1 if n[9] else (n[5] if n[4] else n[6]) for n in nodes]),
"features": np.array([-2 if n[9] else n[2] for n in nodes]),
"thresholds": np.array([n[3] for n in nodes], dtype=np.float64),
"values": np.array([[n[0]] for n in nodes], dtype=np.float64),
"node_sample_weight": np.array([n[1] for n in nodes], dtype=np.float64),
}
self.trees.append(SingleTree(tree, data=data, data_missing=data_missing))
self.objective = objective_name_map.get(model.loss, None)
self.tree_output = "log_odds"
elif safe_isinstance(
model,
[
"sklearn.ensemble.GradientBoostingClassifier",
"sklearn.ensemble._gb.GradientBoostingClassifier",
"sklearn.ensemble.gradient_boosting.GradientBoostingClassifier",
],
):
self.input_dtype = np.float32
# TODO: deal with estimators for each class
if model.estimators_.shape[1] > 1:
emsg = "GradientBoostingClassifier is only supported for binary classification right now!"
raise InvalidModelError(emsg)
# currently we only support the logs odds estimator
if safe_isinstance(
model.init_,
[
"sklearn.ensemble.LogOddsEstimator",
"sklearn.ensemble.gradient_boosting.LogOddsEstimator",
],
):
self.base_offset = model.init_.prior
self.tree_output = "log_odds"
elif safe_isinstance(model.init_, "sklearn.dummy.DummyClassifier"):
self.base_offset = scipy.special.logit(model.init_.class_prior_[1]) # with two classes the trees only model the second class.
self.tree_output = "log_odds"
else:
emsg = f"Unsupported init model type: {type(model.init_)}"
raise InvalidModelError(emsg)
self.trees = [SingleTree(e.tree_, scaling=model.learning_rate, data=data, data_missing=data_missing) for e in model.estimators_[:,0]]
self.objective = objective_name_map.get(model.criterion, None)
elif "pyspark.ml" in str(type(model)):
assert_import("pyspark")
self.model_type = "pyspark"
# model._java_obj.getImpurity() can be gini, entropy or variance.
self.objective = objective_name_map.get(model._java_obj.getImpurity(), None)
if "Classification" in str(type(model)):
normalize = True
self.tree_output = "probability"
else:
normalize = False
self.tree_output = "raw_value"
# Spark Random forest, create 1 weighted (avg) tree per sub-model
if safe_isinstance(
model,
[
"pyspark.ml.classification.RandomForestClassificationModel",