【问题标题】:Isolation Forest in PythonPython中的隔离森林
【发布时间】:2019-07-11 12:09:46
【问题描述】:

我目前正在使用 Python 中的 Isolation Forest 检测我的数据集中的异常值,但我并不完全理解 scikit-learn 文档中给出的示例和解释

是否可以使用 Isolation Forest 来检测包含 258 行和 10 列的数据集中的异常值?

我需要单独的数据集来训练模型吗?如果是,是否有必要让该训练数据集没有异常值?

这是我的代码:

rng = np.random.RandomState(42)
X = 0.3*rng.randn(100,2)
X_train = np.r_[X+2,X-2]
clf = IsolationForest(max_samples=100, random_state=rng, contamination='auto'
clf.fit(X_train)
y_pred_train = clf.predict(x_train)
y_pred_test = clf.predict(x_test)
print(len(y_pred_train))

我尝试将我的数据集加载到X_train,但这似乎不起作用。

【问题讨论】:

  • 您的代码适用于您的玩具示例,但稍作修正。如果您在数据集上运行 IsolationForest 时遇到问题,请向我们展示您已完成的所有预处理步骤以及您拥有的错误消息
  • 你的“异常值”是否有真实标签?
  • @davidrpugh 对于IsolationForest,您不需要任何“基本事实”,其背后的基本原理不同......
  • @SergeyBushmanov 我知道使用 IsolationForest 不需要基本实况标签,但是如果 OP 有这样的标签,那么您可以使用此信息来调整超参数或在测试数据上评分 IsolationForest用于与其他模型进行比较。

标签: python-3.x scikit-learn outliers anomaly-detection


【解决方案1】:

我需要单独的数据集来训练模型吗?

简短的回答是“否”。您在相同数据上训练和预测异常值。

IsolationForest 是一种无监督学习算法,旨在从异常值中清除您的数据(有关更多信息,请参阅docs)。在通常的机器学习设置中,您将运行它来清理您的训练数据集。就您的玩具示例而言:

rng = np.random.RandomState(42)
X = 0.3*rng.randn(100,2)
X_train = np.r_[X+2,X-2]

from sklearn.ensemble import IsolationForest
clf = IsolationForest(max_samples=100, random_state=rng, behaviour="new", contamination=.1)

clf.fit(X_train)
y_pred_train = clf.predict(X_train)
y_pred_train
array([ 1,  1,  1, -1,  1,  1,  1,  1,  1,  1, -1,  1,  1,  1,  1,  1,  1,
        1, -1,  1,  1,  1,  1,  1, -1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
        1,  1,  1, -1,  1, -1,  1, -1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
        1,  1, -1,  1, -1,  1,  1,  1,  1,  1, -1, -1,  1,  1,  1,  1,  1,
        1,  1,  1,  1,  1,  1,  1,  1,  1,  1, -1,  1,  1,  1,  1,  1,  1,
        1,  1,  1,  1, -1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
        1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
        1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
        1, -1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1,
       -1,  1,  1, -1,  1,  1,  1,  1, -1, -1,  1,  1,  1,  1,  1,  1,  1,
        1,  1,  1,  1,  1,  1,  1,  1, -1,  1,  1,  1,  1,  1,  1,  1,  1,
        1,  1, -1,  1,  1,  1,  1,  1,  1,  1,  1,  1,  1])

其中1 表示内部值,-1 表示异常值。由contamination 参数指定,异常值的比例为0.1

最后,您将删除异常值,例如:

X_train_cleaned = X_train[np.where(y_pred_train == 1, True, False)]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-29
    • 2015-07-16
    • 2018-09-10
    • 2020-11-16
    • 2021-03-20
    • 2019-08-02
    • 2019-07-20
    • 2017-08-21
    相关资源
    最近更新 更多