简介
在本实验中,我们将介绍使用隔离森林(Isolation Forest)进行异常检测的过程。我们将首先生成一个包含两个聚类和一些离群点的数据集,然后训练一个隔离森林模型来识别离群点。最后,我们将可视化模型的决策边界,以了解它如何区分内点和离群点。
虚拟机使用提示
虚拟机启动完成后,点击左上角切换到“笔记本”(Notebook)标签页,以访问 Jupyter Notebook 进行练习。
有时,你可能需要等待几秒钟,以便 Jupyter Notebook 完成加载。由于 Jupyter Notebook 的限制,操作验证无法自动化。
如果你在学习过程中遇到问题,请随时向 Labby 提问。课程结束后提供反馈,我们将立即为你解决问题。
数据生成
我们将生成一个包含两个聚类和一些离群点的数据集。聚类将通过从标准正态分布中随机采样生成。其中一个聚类将是球形的,另一个将略有变形。离群点将通过从均匀分布中随机采样生成。
import numpy as np
from sklearn.model_selection import train_test_split
n_samples, n_outliers = 120, 40
rng = np.random.RandomState(0)
covariance = np.array([[0.5, -0.1], [0.7, 0.4]])
cluster_1 = 0.4 * rng.randn(n_samples, 2) @ covariance + np.array([2, 2]) ## 一般
cluster_2 = 0.3 * rng.randn(n_samples, 2) + np.array([-2, -2]) ## 球形
outliers = rng.uniform(low=-4, high=4, size=(n_outliers, 2))
X = np.concatenate([cluster_1, cluster_2, outliers])
y = np.concatenate(
[np.ones((2 * n_samples), dtype=int), -np.ones((n_outliers), dtype=int)]
)
X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, random_state=42)
可视化数据集
我们可以可视化生成的聚类,以了解数据集的样子。
import matplotlib.pyplot as plt
scatter = plt.scatter(X[:, 0], X[:, 1], c=y, s=20, edgecolor="k")
handles, labels = scatter.legend_elements()
plt.axis("square")
plt.legend(handles=handles, labels=["outliers", "inliers"], title="true class")
plt.title("Gaussian inliers with \nuniformly distributed outliers")
plt.show()
训练模型
我们将使用训练数据训练一个隔离森林(Isolation Forest)模型。
from sklearn.ensemble import IsolationForest
clf = IsolationForest(max_samples=100, random_state=0)
clf.fit(X_train)
绘制离散决策边界
我们将使用DecisionBoundaryDisplay类来可视化离散决策边界。背景颜色表示在给定区域内的样本是否被预测为离群点。散点图显示真实标签。
import matplotlib.pyplot as plt
from sklearn.inspection import DecisionBoundaryDisplay
disp = DecisionBoundaryDisplay.from_estimator(
clf,
X,
response_method="predict",
alpha=0.5,
)
disp.ax_.scatter(X[:, 0], X[:, 1], c=y, s=20, edgecolor="k")
disp.ax_.set_title("Binary decision boundary \nof IsolationForest")
plt.axis("square")
plt.legend(handles=handles, labels=["outliers", "inliers"], title="true class")
plt.show()
绘制路径长度决策边界
通过设置response_method="decision_function",DecisionBoundaryDisplay的背景表示一个观测值的正态性度量。这样的分数由在随机树森林上平均的路径长度给出,而路径长度本身由隔离给定样本所需的叶节点深度(或等效地,分割次数)给出。
disp = DecisionBoundaryDisplay.from_estimator(
clf,
X,
response_method="decision_function",
alpha=0.5,
)
disp.ax_.scatter(X[:, 0], X[:, 1], c=y, s=20, edgecolor="k")
disp.ax_.set_title("Path length decision boundary \nof IsolationForest")
plt.axis("square")
plt.legend(handles=handles, labels=["outliers", "inliers"], title="true class")
plt.colorbar(disp.ax_.collections[1])
plt.show()
总结
在本实验中,我们学习了如何使用隔离森林进行异常检测。我们生成了一个包含两个聚类和一些异常值的数据集,训练了一个隔离森林模型来识别异常值,并可视化了模型的决策边界,以了解它是如何区分内点和异常值的。