真实数据集上的离群点检测#

本示例演示了在真实数据集上进行稳健协方差估计的必要性。这对于离群点检测以及更好地理解数据结构都非常有用。

我们从 Wine(葡萄酒)数据集中选择了两组变量(每组包含两个变量),用以展示可以使用哪些离群点检测工具进行分析。为了便于可视化,我们采用了二维示例,但应当意识到,正如后续将指出的那样,在高维空间中情况并非如此简单。

在下方的两个示例中,主要结论是:经验协方差估计作为一种非稳健估计,极易受到观测值异构结构的影响。尽管稳健协方差估计能够聚焦于数据分布的主要模式,但它仍然基于数据应服从高斯分布的假设,这导致对数据结构的估计存在一定偏差,但仍在一定程度上保持了准确性。One-Class SVM(单类支持向量机)不对数据分布的参数形式做任何假设,因此能够更好地模拟数据的复杂形状。

# Authors: The scikit-learn developers
# SPDX-License-Identifier: BSD-3-Clause

第一个示例#

第一个示例演示了当存在离群点时,最小协方差行列式(Minimum Covariance Determinant)稳健估计器如何帮助集中于相关的聚类。在此,经验协方差估计被主聚类之外的点所偏离。当然,某些筛选工具可以指出存在两个聚类(支持向量机、高斯混合模型、单变量离群点检测等)。但如果这是一个高维示例,这些方法将无法如此轻易地应用。

from sklearn.covariance import EllipticEnvelope
from sklearn.inspection import DecisionBoundaryDisplay
from sklearn.svm import OneClassSVM

estimators = {
    "Empirical Covariance": EllipticEnvelope(support_fraction=1.0, contamination=0.25),
    "Robust Covariance (Minimum Covariance Determinant)": EllipticEnvelope(
        contamination=0.25
    ),
    "OCSVM": OneClassSVM(nu=0.25, gamma=0.35),
}
import matplotlib.lines as mlines
import matplotlib.pyplot as plt

from sklearn.datasets import load_wine

X = load_wine()["data"][:, [1, 2]]  # two clusters

fig, ax = plt.subplots()
colors = ["tab:blue", "tab:orange", "tab:red"]
# Learn a frontier for outlier detection with several classifiers
legend_lines = []
for color, (name, estimator) in zip(colors, estimators.items()):
    estimator.fit(X)
    DecisionBoundaryDisplay.from_estimator(
        estimator,
        X,
        response_method="decision_function",
        plot_method="contour",
        levels=[0],
        colors=color,
        ax=ax,
    )
    legend_lines.append(mlines.Line2D([], [], color=color, label=name))


ax.scatter(X[:, 0], X[:, 1], color="black")
bbox_args = dict(boxstyle="round", fc="0.8")
arrow_args = dict(arrowstyle="->")
ax.annotate(
    "outlying points",
    xy=(4, 2),
    xycoords="data",
    textcoords="data",
    xytext=(3, 1.25),
    bbox=bbox_args,
    arrowprops=arrow_args,
)
ax.legend(handles=legend_lines, loc="upper center")
_ = ax.set(
    xlabel="ash",
    ylabel="malic_acid",
    title="Outlier detection on a real data set (wine recognition)",
)
Outlier detection on a real data set (wine recognition)

第二个示例#

第二个示例展示了最小协方差行列式稳健协方差估计器聚焦于数据分布主要模式的能力:位置似乎估计得很好,尽管由于香蕉形分布的存在,协方差较难估计。无论如何,我们可以剔除一些离群观测值。One-Class SVM 能够捕捉真实的数据结构,但难点在于调整其核带宽参数,以便在数据散点矩阵的形状与数据过拟合风险之间取得良好的平衡。

X = load_wine()["data"][:, [6, 9]]  # "banana"-shaped

fig, ax = plt.subplots()
colors = ["tab:blue", "tab:orange", "tab:red"]
# Learn a frontier for outlier detection with several classifiers
legend_lines = []
for color, (name, estimator) in zip(colors, estimators.items()):
    estimator.fit(X)
    DecisionBoundaryDisplay.from_estimator(
        estimator,
        X,
        response_method="decision_function",
        plot_method="contour",
        levels=[0],
        colors=color,
        ax=ax,
    )
    legend_lines.append(mlines.Line2D([], [], color=color, label=name))


ax.scatter(X[:, 0], X[:, 1], color="black")
ax.legend(handles=legend_lines, loc="upper center")
ax.set(
    xlabel="flavanoids",
    ylabel="color_intensity",
    title="Outlier detection on a real data set (wine recognition)",
)

plt.show()
Outlier detection on a real data set (wine recognition)

脚本运行总耗时:(0 分 0.413 秒)

相关示例

在玩具数据集上比较用于离群点检测的异常检测算法

在玩具数据集上比较用于离群点检测的异常检测算法

使用局部离群点因子(LOF)进行离群点检测

使用局部离群点因子(LOF)进行离群点检测

鲁棒 vs 经验协方差估计

鲁棒 vs 经验协方差估计

具有协方差椭球的线性和二次判别分析

具有协方差椭球的线性和二次判别分析

由 Sphinx-Gallery 生成的图库