首页 > 解决方案 > 单变量 IsolationForest 的 Shap TreeExplainer 的 IndexError

问题描述

帮助!尝试解释 IsolationForest 时出现 IndexError。

我正在使用Scikit-learn'sIsolationForest进行异常检测。通常,我使用的数据集有多个变量——但有时它们只有一个。这适用于拟合和预测模型。但是,为了使用shap's解释模型的输出TreeExplainer,我得到一个IndexError.

请参阅下面的最小可重现示例:

import pandas as pd
import numpy as np
from sklearn.ensemble import IsolationForest
from shap import TreeExplainer

df = pd.DataFrame()
df['Column1'] = np.random.randint(0, 100, 100)
model = IsolationForest()
model.fit(X=df)
explainer = TreeExplainer(model)

问题的根本原因似乎如下(见下面的代码):每个IsolationForest都有多个隔离树。在 中TreeExplainer,多个IsoTree对象被初始化。在初始化期间,该行崩溃,因为self.features,一个列表,包含 -2,这是超出范围的,因为tree_features它只是一个数组 ( [0])。所以也许问题是在拟合 时IsolationForest,给出了错误的值self.features

# re-number the features if each tree gets a different set of features
self.features = np.where(self.features >= 0, tree_features[self.features], self.features)

知道如何解决这个问题吗?

当然,对于单变量模型,使用 Shapley 值是没有意义的,因为您可以只使用score_samples. 我打算将其用作解决方法,但肯定有一种更优雅的方式不需要这样做?

谢谢和最良好的祝愿,

亚历山大

标签: scikit-learnindex-erroranomaly-detectionshapisolation-forest

解决方案


推荐阅读