【问题标题】:Why sklearn Isolation Forest predicts wrongly?为什么sklearn Isolation Forest预测错误?
【发布时间】:2019-12-27 02:12:04
【问题描述】:

我正在查看sklearn的隔离森林官方样本:IsolationForest example
我只是做了一个小改动来绘制拟合隔离森林的预测异常:y_pred_train[y_pred_train ==-1,:]
完整代码如下:

rng = np.random.RandomState(42)

# Generate train data
X = 0.3 * rng.randn(100, 2)
X_train = np.r_[X + 2, X - 2]
# Generate some regular novel observations
X = 0.3 * rng.randn(20, 2)
X_test = np.r_[X + 2, X - 2]
# Generate some abnormal novel observations
X_outliers = rng.uniform(low=-4, high=4, size=(20, 2))

# fit the model
clf = IsolationForest(behaviour='new', 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)
y_pred_outliers = clf.predict(X_outliers)

# plot the line, the samples, and the nearest vectors to the plane
xx, yy = np.meshgrid(np.linspace(-5, 5, 50), np.linspace(-5, 5, 50))
Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)

plt.title("IsolationForest")
plt.contourf(xx, yy, Z, cmap=plt.cm.Blues_r)

b1 = plt.scatter(X_train[:, 0], X_train[:, 1], c='white',
                 s=20,alpha=0.5, edgecolor='k')
b11 = plt.scatter(X_train[y_pred_train==-1, 0], X_train[y_pred_train==-1, 1], c='grey',
                 s=20,alpha=0.5, edgecolor='k')
b2 = plt.scatter(X_test[:, 0], X_test[:, 1], c='green',
                 s=20, edgecolor='k')
c = plt.scatter(X_outliers[:, 0], X_outliers[:, 1], c='red',
                s=20, edgecolor='k')
plt.axis('tight')
plt.xlim((-5, 5))
plt.ylim((-5, 5))
plt.legend([b1,b11, b2, c],
           ["training observations","predicted_abnormal",
            "new regular observations", "new abnormal observations"],
           loc="upper left")
plt.show()

但是现在拟合的隔离森林将样本中定义为规则的许多数据点预测为异常。为什么会这样?为什么原文章声称它们是正则的?

【问题讨论】:

    标签: python machine-learning scikit-learn anomaly-detection


    【解决方案1】:

    请注意,在此示例中,异常值是独立于训练和测试数据生成和拟合的。如果异常值不适合模型,异常值会“更接近”正常值。这些在您的代码中以灰色显示。但是,如果将异常值拟合到模型中,则被视为异常的值会发生变化。这就是您发布的文章中没有显示它们的原因。这些值可以说是“暂时异常”。

    考虑如何计算异常分数,如本文所述:https://towardsdatascience.com/outlier-detection-with-isolation-forest-3d190448d45e

    【讨论】:

      猜你喜欢
      • 2017-06-24
      • 2020-11-13
      • 2020-06-26
      • 2018-12-20
      • 1970-01-01
      • 2019-02-12
      • 1970-01-01
      • 1970-01-01
      • 2021-04-30
      相关资源
      最近更新 更多