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

2023-11-07 13:40

本文主要是介绍机器学习基础之新奇和异常值检测,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

异常值检测一般要求新发现的数据是否与现有观测数据具有相同的分布或者不同的分布,相同的分布可以称之为内点(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 <alexandre.gramfort@inria.fr>
#         Albert Thomas <albert.thomas@telecom-paristech.fr>
# 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 outliersX = 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 outliersif name == "Local Outlier Factor":y_pred = algorithm.fit_predict(X)else:y_pred = algorithm.fit(X).predict(X)
​# plot the levels lines and the pointsif name != "Local Outlier Factor":  # LOF does not implement predictZ = 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聚类

这篇关于机器学习基础之新奇和异常值检测的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/363989

相关文章

mysql的基础语句和外键查询及其语句详解(推荐)

《mysql的基础语句和外键查询及其语句详解(推荐)》:本文主要介绍mysql的基础语句和外键查询及其语句详解(推荐),本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋... 目录一、mysql 基础语句1. 数据库操作 创建数据库2. 表操作 创建表3. CRUD 操作二、外键

Python基础语法中defaultdict的使用小结

《Python基础语法中defaultdict的使用小结》Python的defaultdict是collections模块中提供的一种特殊的字典类型,它与普通的字典(dict)有着相似的功能,本文主要... 目录示例1示例2python的defaultdict是collections模块中提供的一种特殊的字

Java Optional避免空指针异常的实现

《JavaOptional避免空指针异常的实现》空指针异常一直是困扰开发者的常见问题之一,本文主要介绍了JavaOptional避免空指针异常的实现,帮助开发者编写更健壮、可读性更高的代码,减少因... 目录一、Optional 概述二、Optional 的创建三、Optional 的常用方法四、Optio

Python基础文件操作方法超详细讲解(详解版)

《Python基础文件操作方法超详细讲解(详解版)》文件就是操作系统为用户或应用程序提供的一个读写硬盘的虚拟单位,文件的核心操作就是读和写,:本文主要介绍Python基础文件操作方法超详细讲解的相... 目录一、文件操作1. 文件打开与关闭1.1 打开文件1.2 关闭文件2. 访问模式及说明二、文件读写1.

Java异常架构Exception(异常)详解

《Java异常架构Exception(异常)详解》:本文主要介绍Java异常架构Exception(异常),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1. Exception 类的概述Exception的分类2. 受检异常(Checked Exception)

C#基础之委托详解(Delegate)

《C#基础之委托详解(Delegate)》:本文主要介绍C#基础之委托(Delegate),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1. 委托定义2. 委托实例化3. 多播委托(Multicast Delegates)4. 委托的用途事件处理回调函数LINQ

Java报NoClassDefFoundError异常的原因及解决

《Java报NoClassDefFoundError异常的原因及解决》在Java开发过程中,java.lang.NoClassDefFoundError是一个令人头疼的运行时错误,本文将深入探讨这一问... 目录一、问题分析二、报错原因三、解决思路四、常见场景及原因五、深入解决思路六、预http://www

一文带你深入了解Python中的GeneratorExit异常处理

《一文带你深入了解Python中的GeneratorExit异常处理》GeneratorExit是Python内置的异常,当生成器或协程被强制关闭时,Python解释器会向其发送这个异常,下面我们来看... 目录GeneratorExit:协程世界的死亡通知书什么是GeneratorExit实际中的问题案例

Java进阶学习之如何开启远程调式

《Java进阶学习之如何开启远程调式》Java开发中的远程调试是一项至关重要的技能,特别是在处理生产环境的问题或者协作开发时,:本文主要介绍Java进阶学习之如何开启远程调式的相关资料,需要的朋友... 目录概述Java远程调试的开启与底层原理开启Java远程调试底层原理JVM参数总结&nbsMbKKXJx

Java捕获ThreadPoolExecutor内部线程异常的四种方法

《Java捕获ThreadPoolExecutor内部线程异常的四种方法》这篇文章主要为大家详细介绍了Java捕获ThreadPoolExecutor内部线程异常的四种方法,文中的示例代码讲解详细,感... 目录方案 1方案 2方案 3方案 4结论方案 1使用 execute + try-catch 记录