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. 【python-opencv】30-角点检测

    [微语]世上有很多不可能,不过不要在你未尽全力之前下结论 特征检测:找到图像特征的技术 特征描述:描述图像特征 Harris角点检测(Corner Detection) 参考: https://doc ...

  2. 【三分】light bulb(zoj3203)

    题目描述: 如图,你可以在房间里移动,灯泡的高度为H,你的身高为h,灯泡与墙的水平距离为D,求你影子的最长长度(影子长度=地上影子长度+墙上影子长度) 样例输入: 0.5 样例输出: 1.000 0. ...

  3. 汇编-5.0-[BX]和loop指令

    1.要完整的描述一个内存单元,需要两种信息:1.内存单元的地址:2.内存单元的长度(类型). 2."()"表示一个寄存器或一个内存单元中的内容.如:(ax)表示ax中的内容. &q ...

  4. LeetCode-714.Best Time to Buy and Sell Stock with Transaction Fee

    Your are given an array of integers prices, for which the i-th element is the price of a given stock ...

  5. python-面向对象-14_eval函数

    eval 函数 eval() 函数十分强大 —— 将字符串 当成 有效的表达式 来求值 并 返回计算结果 # 基本的数学计算 In [1]: eval("1 + 1") Out[1 ...

  6. OC UITextField只允许输入两位小数

    //只能输入两位小数 - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range r ...

  7. (转)JVM内存分配 -Xms128m -Xmx512m -XX:PermSize=128m -XX:MaxPermSize=512m

    在linux环境下配置项目运行环境时,部署的人员都会分配一下内存,以保证程序正常的运行.其实在开发的时候(window系统),就已经涉及到内存分配了,只是这些参数有默认值,因此一直没有去重视它. 以M ...

  8. PHP中parent、this、self和static的区别

    参考: http://www.cnblogs.com/devcjq/articles/2424738.html http://www.cnblogs.com/alsf/p/9621002.html h ...

  9. nginx反向代理 支持WebSocket

    WebSocket(简称WS)协议的握手和HTTP是兼容的,通过HTTP/1.1中协议转换机制,客户端可以传递名为“Upgrade” 头部信息将连接从HTTP连接升级到WebSocket连接 那么反向 ...

  10. linux iscsi挂载与卸载

    iscsiadm -m discovery -t sendtargets -p 192.168.4.245:3260 #扫描ISCSI Target 列出所有LUN iscsiadm -m node ...