异常点检测分为novelty detection 与 outlier detection
鲁棒性的高斯概率密度是novelty detection, 就是在给出的数据中, 找出一些与大部分数据偏离较远的异常数据, 我们的训练集不是纯净的, 包含异常点 outlier detection 的训练集是纯净的
这个算法的思想很好理解, 就是求出训练集在空间中的重心, 和方差, 然后根据高斯概率密度估算每个点被分配到重心的概率.
调包侠决定使用 scikit-learn:
print(__doc__)
# Author: Virgile Fritsch <virgile.fritsch@inria.fr>
# License: BSD 3 clause
import numpy as np
from sklearn.covariance import EllipticEnvelope
from sklearn.svm import OneClassSVM
import matplotlib.pyplot as plt
import matplotlib.font_manager
from sklearn.datasets import load_boston
读取包中提供的数据
# Get data
X1 = load_boston()[‘data‘][:, [8, 10]] # two clusters
X2 = load_boston()[‘data‘][:, [5, 12]] # "banana"-shaped
构造分类器
# Define "classifiers" to be used
classifiers = {
"Empirical Covariance": EllipticEnvelope(support_fraction=1.,
contamination=0.261),
"Robust Covariance (Minimum Covariance Determinant)":
EllipticEnvelope(contamination=0.261),
"OCSVM": OneClassSVM(nu=0.261, gamma=0.05)}
colors = [‘m‘, ‘g‘, ‘b‘]
legend1 = {}
legend2 = {}
训练
# Learn a frontier for outlier detection with several classifiers
# plot the frontier
xx1, yy1 = np.meshgrid(np.linspace(-8, 28, 500), np.linspace(3, 40, 500))
xx2, yy2 = np.meshgrid(np.linspace(3, 10, 500), np.linspace(-5, 45, 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)
legend1[clf_name] = plt.contour(
xx1, yy1, Z1, levels=[0], linewidths=2, colors=colors[i])
plt.figure(2)
clf.fit(X2)
Z2 = clf.decision_function(np.c_[xx2.ravel(), yy2.ravel()])
Z2 = Z2.reshape(xx2.shape)
legend2[clf_name] = plt.contour(
xx2, yy2, Z2, levels=[0], linewidths=2, colors=colors[i])
绘图
legend2_values_list = list( legend2.values() )
legend2_keys_list = list( legend2.keys() )
plt.figure(2) # "banana" shape
plt.title("Outlier detection on a real data set (boston housing)")
plt.scatter(X2[:, 0], X2[:, 1], color=‘black‘)
plt.xlim((xx2.min(), xx2.max()))
plt.ylim((yy2.min(), yy2.max()))
plt.legend((legend2_values_list[0].collections[0],
legend2_values_list[1].collections[0],
legend2_values_list[2].collections[0]),
(legend2_values_list[0], legend2_values_list[1], legend2_values_list[2]),
loc="upper center",
prop=matplotlib.font_manager.FontProperties(size=12))
plt.ylabel("% lower status of the population")
plt.xlabel("average number of rooms per dwelling")
plt.show()
结果显示:
机器学习 鲁棒的基于高斯概率密度的异常点检测(novelty detection) ellipticalenvelope算法
原文地址:http://blog.csdn.net/qq_21970857/article/details/46400593