我目前正在使用 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/