mojolearn.TreeExplainer#

class mojolearn.TreeExplainer(model, data=None, *, feature_perturbation='tree_path_dependent', model_output='raw')[source]#

Bases: _TreesEnsembleBase

Exact SHAP values for mojolearn tree models.

Computes the exact path-dependent TreeSHAP of the shap package for a fitted RandomForestClassifier, RandomForestRegressor, ExtraTreesClassifier, ExtraTreesRegressor, DecisionTreeClassifier, DecisionTreeRegressor, DARTClassifier or DARTRegressor. On GPU installs it runs on the device. Values are float32.

Differs from shap: the tree models store no per-node training counts, so data is required and each node’s cover is the number of background rows that reach it.

Parameters:
  • model (estimator) – A fitted mojolearn tree model from the list above. Any other model raises NotImplementedError; an unfitted DART model raises RuntimeError.

  • data (array of shape (n_background, n_features)) – Background rows that define the node covers. Required: None raises NotImplementedError.

  • feature_perturbation ({“tree_path_dependent”, “auto”}, default “tree_path_dependent”) – Only the path-dependent algorithm is available; "interventional" raises NotImplementedError.

  • model_output ({“raw”}, default “raw”) – Only the raw model output is explained; other values raise NotImplementedError.

Variables:
  • expected_value (float or array of shape (n_outputs,)) – The base value the SHAP values add up from: a float for one output, else a float32 array.

  • n_outputs_ (int) – Number of model outputs explained.

  • n_features_in_ (int) – Number of features in data.

Raises:

NotImplementedError – When a root-to-leaf path splits on more than 255 distinct features.

Examples

>>> import numpy as np, mojolearn
>>> rng = np.random.default_rng(0)
>>> X = rng.random((1000, 8), dtype=np.float32)
>>> y = X @ np.arange(8, dtype=np.float32)
>>> model = mojolearn.RandomForestRegressor().fit(X, y)
>>> explainer = mojolearn.TreeExplainer(model, X[:200])
>>> explainer.shap_values(X[:10]).shape
(10, 8)
__init__(model, data=None, *, feature_perturbation='tree_path_dependent', model_output='raw')[source]#

Methods

close()

Release the explainer's native resources.

get_params([deep])

numeric_mode_used()

The numeric mode this estimator runs in.

set_params(**params)

Set constructor parameters.

shap_values(X)

SHAP values of the rows of X.

vendor_used()

The GPU backend this estimator runs on.

close()[source]#

Release the explainer’s native resources.

After close, shap_values raises RuntimeError.

shap_values(X)[source]#

SHAP values of the rows of X.

Parameters:

X (array of shape (n_samples, n_features)) – Rows to explain, converted to float32. A feature count different from data raises ValueError.

Returns:

array, float32 – Shape (n_samples, n_features) for one output, else (n_samples, n_features, n_outputs).