sklearn 异常检测demo代码走读

# 0基础学python,读代码学习python组件api
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_blobes用于生成聚类数据。centers表示聚类中心,cluster_std表示聚类数据方差。返回值(数据, 类别)
# **用于传递dict key-value参数,*用于传递元组不定数量参数。
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], # make_moons用于生成月亮形数据。返回值数据(x, y)
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
# np.meshgrid生产成网格数据
# 如输入x = [0, 1, 2, 3] y = [0, 1, 2],则输出
# xx 0 1 2 3 yy 0 0 0 0
# 0 1 2 3 1 1 1 1
# 0 1 2 3 2 2 2 2
xx, yy = np.meshgrid(np.linspace(-7, 7, 150),
np.linspace(-7, 7, 150)) # figure生成画布,subplots_adjust子图的间距调整,左边距,右边距,下边距,上边距,列间距,行间距
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
# np.concatenate数组拼接。axis=0行增加,axis=1列增加(对应行拼接)。
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
# ravel()多维数组平铺为一维数组。np.c_ cloumn列连接,np.r_ row行连接。
Z = algorithm.predict(np.c_[xx.ravel(), yy.ravel()])
# reshape这里把一维数组转化为二维数组
Z = Z.reshape(xx.shape)
# plt.contour画等高线。Z表示对应点类别,可以理解为不同的高度,plt.contour就是要画出不同高度间的分界线。
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]) # x轴范围
plt.xlim(-7, 7)
plt.ylim(-7, 7)
# x轴坐标
plt.xticks(())
plt.yticks(())
# 坐标图上显示的文字
plt.text(.99, .01, ('%.2fs' % (t1 - t0)).lstrip(''),
transform=plt.gca().transAxes, size=15,
horizontalalignment='right')
plot_num += 1 plt.show()

执行结果

sklearn异常检测demo的更多相关文章

  1. Abnormal Detection(异常检测)和 Supervised Learning(有监督训练)在异常检测上的应用初探

    1. 异常检测 VS 监督学习 0x1:异常检测算法和监督学习算法的对比 总结来讲: . 在异常检测中,异常点是少之又少,大部分是正常样本,异常只是相对小概率事件 . 异常点的特征表现非常不集中,即异 ...

  2. 异常检测算法:Isolation Forest

    iForest (Isolation Forest)是由Liu et al. [1] 提出来的基于二叉树的ensemble异常检测算法,具有效果好.训练快(线性复杂度)等特点. 1. 前言 iFore ...

  3. 离群点检测与序列数据异常检测以及异常检测大杀器-iForest

    1. 异常检测简介 异常检测,它的任务是发现与大部分其他对象不同的对象,我们称为异常对象.异常检测算法已经广泛应用于电信.互联网和信用卡的诈骗检测.贷款审批.电子商务.网络入侵和天气预报等领域.这些异 ...

  4. 使用GAN 进行异常检测——anoGAN,TODO,待用于安全分析实验

    先说实验成功的代码: git clone https://github.com/tkwoo/anogan-keras.git mkdir weights python main.py --mode t ...

  5. 26.异常检测---孤立森林 | one-class SVM

    novelty detection:当训练数据中没有离群点,我们的目标是用训练好的模型去检测另外发现的新样本 outlier  dection:当训练数据中包含离群点,模型训练时要匹配训练数据的中心样 ...

  6. 异常检测-基于孤立森林算法Isolation-based Anomaly Detection-2-实现

    参考https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.IsolationForest.html#sklearn.en ...

  7. # URL异常检测

    (Isolation Forest无监督)这个算法是随机森林的推广. iTree树构造:随机选一个属性,再随机选该特征的一个值,对样本进行二叉划分,重复以上操作. iTree构建好了后,就可以对数据进 ...

  8. 网络KPI异常检测之时序分解算法

    时间序列数据伴随着我们的生活和工作.从牙牙学语时的“1, 2, 3, 4, 5, ……”到房价的走势变化,从金融领域的刷卡记录到运维领域的核心网性能指标.时间序列中的规律能加深我们对事物和场景的认识, ...

  9. 【异常检测】孤立森林(Isolation Forest)算法简介

    简介 工作的过程中经常会遇到这样一个问题,在构建模型训练数据时,我们很难保证训练数据的纯净度,数据中往往会参杂很多被错误标记噪声数据,而数据的质量决定了最终模型性能的好坏.如果进行人工二次标记,成本会 ...

随机推荐

  1. Ubuntu14.04设置开机启动脚本(转)

    原文:https://www.magentonotes.com/ubuntu-config-autostart-shell-script.html 方法一:将脚本添加到文件/etc/rc.local ...

  2. jquery有几种选择器?

    ①.基本选择器:#id,class,element,*: ②.层次选择器:parent > child,prev + next,prev ~ siblings: ③.基本过滤器选择器::firs ...

  3. 将gitlab中的postgresql数据库开通远程访问

    postgresql数据库是gitlab的一个配置数据库,记录gitlab的一些配置信息. 我们访问gitlab中的postgresql数据有本地命令行访问和远程可视化软件访问2种方式. (一)本地命 ...

  4. 如何代码隐藏email而用户又能看到

    我们有时在网站上留一个邮箱,然后漫天垃圾邮件,非常苦恼,这是因为爬虫通过代码匹配收集网页上的邮箱,那么有没办法代码隐藏email而用户又能看到呢?其实不会很难,如果你的网站是用wordpress搭建, ...

  5. IIS下实现帝国CMS搜索页伪静态

    前面ytkah讲了apache下帝国CMS搜索页伪静态实现方法,网友说服务器是用IIS,那么IIS下如何实现帝国CMS搜索页伪静态呢?首先得先有URL重写插件,下载地址:http://www.iis. ...

  6. what's the 场外交易

    出自 MBA智库百科(https://wiki.mbalib.com/)   什么是场外交易 场外交易是指证券投资机构之间不通过股票交易所,而以电话.电传等方式相互进行的股票交易.           ...

  7. vue-preview的使用

    使用vue-preview做图片缩率图1.安装 npm i vue-preview -S2.如果使用vue-cli生成的项目,需要修改webpack.base.conf.js文件中的loaders,添 ...

  8. 外部盒模型大小固定 内部有边框div设置浮动时 缩放窗口内部div溢出的解决办法

    原因分析: chorme和firefox浏览器下当缩放窗口大小时,边框的计算宽度变大造成内部div宽度的计算宽度变大,外部div放不下内部div而溢出. 解决办法: 给内部div设置 box-sizi ...

  9. 虚拟主机是设置在httpd-vhosts.conf还是vhosts.conf还是httpd.conf

    https://blog.csdn.net/weisubao/article/details/43536723 解决方案:虚拟主机是设置在httpd-vhosts.conf还是vhosts.conf还 ...

  10. 根据构建类型动态设置AndroidManifest.xml文件中的meta-data

    当debug和release版本使用不同的值时,使用Gradle设置相应的值. Android主配置文件 <meta-data android:name="com.amap.api.v ...