检测葡萄酒数据中的异常值

Beginner

This tutorial is from open-source community. Access the source code

简介

在本实验中,我们将使用 scikit-learn 对一个真实数据集进行异常值检测。异常值检测是识别与大多数数据有显著差异的数据点的过程。异常值可能是由测量误差、数据损坏或仅仅代表一个罕见事件引起的。异常值检测在许多应用中都很重要,如欺诈检测、网络入侵检测和医疗诊断。

虚拟机使用提示

虚拟机启动完成后,点击左上角切换到笔记本标签页,以访问 Jupyter Notebook 进行练习。

有时,你可能需要等待几秒钟让 Jupyter Notebook 完成加载。由于 Jupyter Notebook 的限制,操作验证无法自动化。

如果你在学习过程中遇到问题,随时向 Labby 提问。课程结束后提供反馈,我们会及时为你解决问题。

导入库并加载数据集

我们将首先导入必要的库,并从 scikit-learn 中加载葡萄酒数据集。葡萄酒数据集包含有关不同类型葡萄酒的信息,包括它们的化学特性。

import numpy as np
from sklearn.covariance import EllipticEnvelope
from sklearn.svm import OneClassSVM
import matplotlib.pyplot as plt
from sklearn.datasets import load_wine

## Load dataset
X1 = load_wine()["data"][:, [1, 2]]  ## two clusters
X2 = load_wine()["data"][:, [6, 9]]  ## "banana"-shaped

定义分类器和颜色

我们将定义在本实验中要使用的异常值检测分类器。我们还将定义用于绘制结果的颜色。

## Define "classifiers" to be used
classifiers = {
    "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),
}
colors = ["m", "g", "b"]

二维数据的异常值检测

我们将对二维葡萄酒数据集进行异常值检测。我们将使用三种不同的分类器来检测异常值:经验协方差、稳健协方差和单类支持向量机(One-Class SVM)。然后我们将绘制结果。

## Learn a frontier for outlier detection with several classifiers
xx1, yy1 = np.meshgrid(np.linspace(0, 6, 500), np.linspace(1, 4.5, 500))
for i, (clf_name, clf) in enumerate(classifiers.items()):
    plt.figure(1)
    clf.fit(X1)
    Z1 = clf.decision_function(np.c_[xx1.ravel(), yy1.ravel()])
    Z1 = Z1.reshape(xx1.shape)
    plt.contour(
        xx1, yy1, Z1, levels=[0], linewidths=2, colors=colors[i]
    )

## Plot the results (= shape of the data points cloud)
plt.figure(1)  ## two clusters
plt.title("Outlier detection on a real data set (wine recognition)")
plt.scatter(X1[:, 0], X1[:, 1], color="black")
plt.xlim((xx1.min(), xx1.max()))
plt.ylim((yy1.min(), yy1.max()))
plt.ylabel("ash")
plt.xlabel("malic_acid")
plt.show()

复杂数据的异常值检测

我们将对呈“香蕉”形状的葡萄酒数据集进行异常值检测。我们将使用与之前相同的三种分类器并绘制结果。

## Learn a frontier for outlier detection with several classifiers
xx2, yy2 = np.meshgrid(np.linspace(-1, 5.5, 500), np.linspace(-2.5, 19, 500))
for i, (clf_name, clf) in enumerate(classifiers.items()):
    plt.figure(2)
    clf.fit(X2)
    Z2 = clf.decision_function(np.c_[xx2.ravel(), yy2.ravel()])
    Z2 = Z2.reshape(xx2.shape)
    plt.contour(
        xx2, yy2, Z2, levels=[0], linewidths=2, colors=colors[i]
    )

## Plot the results (= shape of the data points cloud)
plt.figure(2)  ## "banana" shape
plt.title("Outlier detection on a real data set (wine recognition)")
plt.scatter(X2[:, 0], X2[:, 1], color="black")
plt.xlim((xx2.min(), xx2.max()))
plt.ylim((yy2.min(), yy2.max()))
plt.ylabel("color_intensity")
plt.xlabel("flavanoids")
plt.show()

总结

在本实验中,我们使用 scikit-learn 对二维葡萄酒数据集进行了异常值检测。我们使用了三种不同的分类器来检测异常值:经验协方差、稳健协方差和单类支持向量机(One-Class SVM)。然后我们绘制了结果,以可视化数据和检测到的异常值。异常值检测是数据分析中的一项重要任务,scikit-learn 提供了多种工具来高效地执行此任务。