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. Sublime_text编辑器插件安装

    Sublime_text 3下载与安装详细教程 参考: https://blog.csdn.net/weixin_40682842/article/details/78727266 http://ww ...

  2. python面试题~反射,元类,单例

    1 什么是反射?以及应用场景? test.py def f1(): print('f1') def f2(): print('f2') def f3(): print('f3') def f4(): ...

  3. 【托业】【新托业TOEIC新题型真题】学习笔记8-题库五->P7

    ———————————————————单词———————————————————— minister 部长 construction contractor 施工方 commence 开始:着手 bac ...

  4. mysql 权限管理 目录

    mysql 权限管理介绍 mysql 权限管理 记录 mysql 权限管理 grant 命令 mysql 权限管理 revoke 回收权限 命令 mysql 权限管理 针对库 授权 db.* mysq ...

  5. 教你一步步composer安装Magento2.3

    以前外贸建站一直用zencart,这段时间ytkah比较有时间,就决定用magento来创建一下站点.magento不像普通的程序一样下载就可以直接安装,需要借助composer安装,还没没compo ...

  6. caffe SSD目标检测lmdb数据格式制作

    一.任务 现在用caffe做目标检测一般需要lmdb格式的数据,而目标检测的数据和目标分类的lmdb格式的制作难度不同.就目标检测来说,例如准备SSD需要的数据,一般需要以下几步: 1.准备图片并标注 ...

  7. elasticsearch 处理index 一直INITIALIZING状态

    elasticsearch一个节点异常重启后有一个index恢复的过程中状态一直INITIALIZING 处理方法 PUT index_name/_settings { "index&quo ...

  8. maven设置每次构建获取最新版本号

    build.gradle中的依赖是通过设置maven依赖实现.我们知道,maven可以说是通过一个坐标定位来确定唯一一个包的,所说的坐标定位分别是groupId,artifactId和version三 ...

  9. java基础(四) -变量类型

    在Java语言中,所有的变量在使用前必须声明.声明变量的基本格式如下: type identifier [ = value][, identifier [= value] ...] ; 格式说明:ty ...

  10. 1.Spring对JDBC整合支持

    1.Spring对JDBC整合支持 Spring对DAO提供哪些支持 1)Spring对DAO异常提供统一处理 2)Spring对DAO编写提供支持的抽象类 3)提高编程效率,减少DAO编码量 Spr ...