treeinterpreter

raw JSON →
0.2.3 verified Mon Apr 27 auth: no python maintenance

A library for interpreting scikit-learn's decision tree and random forest predictions by decomposing predictions into feature contributions. Current version 0.2.3, last updated in 2019 (maintenance mode).

pip install treeinterpreter
error AttributeError: module 'treeinterpreter' has no attribute 'treeinterpreter'
cause Incorrect import statement (import treeinterpreter then calling treeinterpreter.treeinterpreter).
fix
Use 'from treeinterpreter import treeinterpreter as ti' then 'ti.predict()'.
error AttributeError: 'RandomForestRegressor' object has no attribute 'estimators_'
cause Incompatible scikit-learn version (>=0.24) where estimators_ property changed.
fix
Downgrade scikit-learn to 0.23.2 or use a different interpretation library.
error ValueError: could not broadcast input array from shape (n,) into shape (m,)
cause Typically when passing a single sample but expecting 2D array.
fix
Reshape your input: X[:1] instead of X[0]. Use X.values.reshape(1, -1) for pandas.
deprecated The library is unmaintained since 2019 and may not work with recent scikit-learn versions (e.g., >0.24). Expect compatibility issues.
fix Consider alternatives like shap or interpretml for newer scikit-learn.
gotcha Duplicate naming: the module 'treeinterpreter' contains a function also named 'treeinterpreter'. Use 'from treeinterpreter import treeinterpreter as ti' to avoid confusion.
fix Import with alias as shown.
breaking Scikit-learn v0.24+ deprecated certain internal APIs used by treeinterpreter, causing AttributeError: 'ForestClassifier' object has no attribute 'estimators_' (in some contexts).
fix Downgrade scikit-learn to <=0.23 or patch the library. Use shap as alternative.
gotcha The library only supports tree-based models from scikit-learn (RandomForest, ExtraTrees, DecisionTree). Does not work with other models.
fix Ensure your model is a tree-based ensemble.

Train a random forest on Boston housing data and interpret a single prediction.

from sklearn.ensemble import RandomForestRegressor
from sklearn.datasets import load_boston
from treeinterpreter import treeinterpreter as ti

boston = load_boston()
X, y = boston.data, boston.target
rf = RandomForestRegressor()
rf.fit(X, y)
prediction, bias, contributions = ti.predict(rf, X[:1])
print('Prediction:', prediction)
print('Bias:', bias)
print('Feature contributions:', contributions)