机器学习基础之新奇和异常值检测

异常值检测一般要求新发现的数据是否与现有观测数据具有相同的分布或者不同的分布,相同的分布可以称之为内点(inlier),具有不同分布的点可以称之为离群值。离群点和新奇点检测是不同的,有一个重要的区分必须掌握:

离群点检测:训练数据包含离群点,这些离群点被定义为远离其它内点的观察值。因此,离群点检测估计器会尝试拟合出训练数据中内围点聚集的区域, 而忽略异常值观察。

新奇点检测:训练数据没有受到离群点污染,我们感兴趣的是检测一个新的观测值是否为离群点。在这种情况下,离群点被认为是新奇点。

离群点检测和新奇点检测都用于异常检测, 其中一项感兴趣的是检测异常或异常观察。离群点检测又被称之为无监督异常检测,新奇点检测又被称之为半监督异常检测。 在离群点检测的背景下, 离群点/异常点不能够形成密集的簇,因为可用的估计器假设离群点/异常点位于低密度区域。相反的,在新奇点检测的背景下, 新奇点/异常点只要位于训练数据的低密度区域,是可以形成稠密聚类簇的,在此背景下被认为是正常的。

scikit-learn有一套机器学习工具estimator.fit(X_train),可用于新奇点或离群值检测。然后可以使用estimator.predict(X_test)方法将新观察值分类为离群点或内点 :内围点会被标记为1,而离群点标记为-1。

离群点检测方法总结

下面的例子展示了二维数据集上不同异常检测算法的特点。数据集包含一种或两种模式(高密度区域),以说明算法处理多模式数据的能力。

对于每个数据集,产生15%的样本作为随机均匀噪声。这个比例是给予OneClassSVM的nu参数和其他离群点检测算法的污染参数的值。由于局部离群因子(LOF)用于离群值检测时没有对新数据应用的预测方法,因此除了局部离群值因子(LOF)外,inliers和离群值之间的决策边界以黑色显示。

sklearn.svm。一个已知的eclasssvm对异常值很敏感,因此在异常值检测方面表现不太好。该估计器最适合在训练集没有异常值的情况下进行新颖性检测。也就是说,在高维的离群点检测,或者在不对嵌入数据的分布做任何假设的情况下,一个类支持向量机可能在这些情况下给出有用的结果,这取决于它的超参数的值。

sklearn.covariance。椭圆包络假设数据是高斯分布,并学习一个椭圆。因此,当数据不是单峰时,它就会退化。但是请注意,这个估计器对异常值是稳健的。

sklearn.ensemble。IsolationForest sklearn.neighbors。LocalOutlierFactor对于多模态数据集似乎表现得相当好。sklearn的优势。第三个数据集的局部离群因子超过其他估计显示,其中两种模式有不同的密度。这种优势是由LOF的局域性来解释的,即它只比较一个样本的异常分数与其相邻样本的异常分数。

最后,对于最后一个数据集,很难说一个样本比另一个样本更反常,因为它们是均匀分布在超立方体中。除了sklearn。svm。有一点过度拟合的支持向量机,所有的估计器都对这种情况给出了合适的解决方案。在这种情况下,明智的做法是更密切地观察样本的异常分数,因为一个好的估计器应该给所有样本分配相似的分数。

虽然这些例子给出了一些关于算法的直觉,但这种直觉可能不适用于非常高维的数据。

最后,请注意,模型的参数在这里是精心挑选的,但在实践中需要进行调整。在没有标记数据的情况下,这个问题是完全无监督的,因此模型的选择是一个挑战。

# Author: Alexandre Gramfort <[email protected]>
#         Albert Thomas <[email protected]>
# License: BSD 3 clause
​
import time
​
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
​
from sklearn import svm
from sklearn.datasets import make_moons, make_blobs
from sklearn.covariance import EllipticEnvelope
from sklearn.ensemble import IsolationForest
from sklearn.neighbors import LocalOutlierFactor
​
print(__doc__)
​
matplotlib.rcParams['contour.negative_linestyle'] = 'solid'
​
# Example settings
n_samples = 300
outliers_fraction = 0.15
n_outliers = int(outliers_fraction * n_samples)
n_inliers = n_samples - n_outliers
​
# define outlier/anomaly detection methods to be compared
anomaly_algorithms = [
    ("Robust covariance", EllipticEnvelope(contamination=outliers_fraction)),
    ("One-Class SVM", svm.OneClassSVM(nu=outliers_fraction, kernel="rbf",
                                      gamma=0.1)),
    ("Isolation Forest", IsolationForest(contamination=outliers_fraction,
                                         random_state=42)),
    ("Local Outlier Factor", LocalOutlierFactor(
        n_neighbors=35, contamination=outliers_fraction))]
​
# Define datasets
blobs_params = dict(random_state=0, n_samples=n_inliers, n_features=2)
datasets = [
    make_blobs(centers=[[0, 0], [0, 0]], cluster_std=0.5,
               **blobs_params)[0],
    make_blobs(centers=[[2, 2], [-2, -2]], cluster_std=[0.5, 0.5],
               **blobs_params)[0],
    make_blobs(centers=[[2, 2], [-2, -2]], cluster_std=[1.5, .3],
               **blobs_params)[0],
    4. * (make_moons(n_samples=n_samples, noise=.05, random_state=0)[0] -
          np.array([0.5, 0.25])),
    14. * (np.random.RandomState(42).rand(n_samples, 2) - 0.5)]
​
# Compare given classifiers under given settings
xx, yy = np.meshgrid(np.linspace(-7, 7, 150),
                     np.linspace(-7, 7, 150))
​
plt.figure(figsize=(len(anomaly_algorithms) * 2 + 3, 12.5))
plt.subplots_adjust(left=.02, right=.98, bottom=.001, top=.96, wspace=.05,
                    hspace=.01)
​
plot_num = 1
rng = np.random.RandomState(42)
​
for i_dataset, X in enumerate(datasets):
    # Add outliers
    X = np.concatenate([X, rng.uniform(low=-6, high=6,
                       size=(n_outliers, 2))], axis=0)
​
    for name, algorithm in anomaly_algorithms:
        t0 = time.time()
        algorithm.fit(X)
        t1 = time.time()
        plt.subplot(len(datasets), len(anomaly_algorithms), plot_num)
        if i_dataset == 0:
            plt.title(name, size=18)
​
        # fit the data and tag outliers
        if name == "Local Outlier Factor":
            y_pred = algorithm.fit_predict(X)
        else:
            y_pred = algorithm.fit(X).predict(X)
​
        # plot the levels lines and the points
        if name != "Local Outlier Factor":  # LOF does not implement predict
            Z = algorithm.predict(np.c_[xx.ravel(), yy.ravel()])
            Z = Z.reshape(xx.shape)
            plt.contour(xx, yy, Z, levels=[0], linewidths=2, colors='black')
​
        colors = np.array(['#377eb8', '#ff7f00'])
        plt.scatter(X[:, 0], X[:, 1], s=10, color=colors[(y_pred + 1) // 2])
​
        plt.xlim(-7, 7)
        plt.ylim(-7, 7)
        plt.xticks(())
        plt.yticks(())
        plt.text(.99, .01, ('%.2fs' % (t1 - t0)).lstrip('0'),
                 transform=plt.gca().transAxes, size=15,
                 horizontalalignment='right')
        plot_num += 1
​
plt.show()

一个新奇点检测例子

下图是一个使用支持向量机进行新奇点检测的例子。

支持向量机是一种无监督的算法,它学习一个用于新鲜度检测的决策函数:将新数据分类为与训练集相似或不同的数据。

print(__doc__)
​
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.font_manager
from sklearn import svm
​
xx, yy = np.meshgrid(np.linspace(-5, 5, 500), np.linspace(-5, 5, 500))
# Generate train data
X = 0.3 * np.random.randn(100, 2)
X_train = np.r_[X + 2, X - 2]
# Generate some regular novel observations
X = 0.3 * np.random.randn(20, 2)
X_test = np.r_[X + 2, X - 2]
# Generate some abnormal novel observations
X_outliers = np.random.uniform(low=-4, high=4, size=(20, 2))
​
# fit the model
clf = svm.OneClassSVM(nu=0.1, kernel="rbf", gamma=0.1)
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)
n_error_train = y_pred_train[y_pred_train == -1].size
n_error_test = y_pred_test[y_pred_test == -1].size
n_error_outliers = y_pred_outliers[y_pred_outliers == 1].size
​
# plot the line, the points, and the nearest vectors to the plane
Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
​
plt.title("Novelty Detection")
plt.contourf(xx, yy, Z, levels=np.linspace(Z.min(), 0, 7), cmap=plt.cm.PuBu)
a = plt.contour(xx, yy, Z, levels=[0], linewidths=2, colors='darkred')
plt.contourf(xx, yy, Z, levels=[0, Z.max()], colors='palevioletred')
​
s = 40
b1 = plt.scatter(X_train[:, 0], X_train[:, 1], c='white', s=s, edgecolors='k')
b2 = plt.scatter(X_test[:, 0], X_test[:, 1], c='blueviolet', s=s,
                 edgecolors='k')
c = plt.scatter(X_outliers[:, 0], X_outliers[:, 1], c='gold', s=s,
                edgecolors='k')
plt.axis('tight')
plt.xlim((-5, 5))
plt.ylim((-5, 5))
plt.legend([a.collections[0], b1, b2, c],
           ["learned frontier", "training observations",
            "new regular observations", "new abnormal observations"],
           loc="upper left",
           prop=matplotlib.font_manager.FontProperties(size=11))
plt.xlabel(
    "error train: %d/200 ; errors novel regular: %d/40 ; "
    "errors novel abnormal: %d/40"
    % (n_error_train, n_error_test, n_error_outliers))
plt.show()

(1)获取更多优质内容及精彩资讯,可前往:https://www.cda.cn/?seo

(2)了解更多数据领域的优质课程:

机器学习经典算法之k-means聚类

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章