python-3.x - Python 中的隔离森林

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

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

是否可以使用隔离森林来检测具有 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,但这似乎不起作用。

最佳答案

Do I need a separate dataset to train the model?

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

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)]

关于python-3.x - Python 中的隔离森林,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54741682/

相关文章:

python - Matplotlib 干扰图奇怪的图案

python - 尽管启用了管理员权限和两种意图,为什么我的机器人无法踢用户?

python - 获取 pandas 中连续行中唯一值的个数

R: 'spatialSign' 函数对于识别异常值有用吗?

Python导出多个数据到一个json文件

python - sklearn : use Pipeline in a RandomizedSearchCV?

python - 属性错误 : 'str' object has no attribute 'decode' while building a logistic regression model

python - 机器学习的扩展功能

database - 我如何使用 ELKI 中的索引结构?

python - 同时将 Pandas 函数应用于行和列以进行置信区间计算