sklearn异常检测demo
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的更多相关文章
- Abnormal Detection(异常检测)和 Supervised Learning(有监督训练)在异常检测上的应用初探
1. 异常检测 VS 监督学习 0x1:异常检测算法和监督学习算法的对比 总结来讲: . 在异常检测中,异常点是少之又少,大部分是正常样本,异常只是相对小概率事件 . 异常点的特征表现非常不集中,即异 ...
- 异常检测算法:Isolation Forest
iForest (Isolation Forest)是由Liu et al. [1] 提出来的基于二叉树的ensemble异常检测算法,具有效果好.训练快(线性复杂度)等特点. 1. 前言 iFore ...
- 离群点检测与序列数据异常检测以及异常检测大杀器-iForest
1. 异常检测简介 异常检测,它的任务是发现与大部分其他对象不同的对象,我们称为异常对象.异常检测算法已经广泛应用于电信.互联网和信用卡的诈骗检测.贷款审批.电子商务.网络入侵和天气预报等领域.这些异 ...
- 使用GAN 进行异常检测——anoGAN,TODO,待用于安全分析实验
先说实验成功的代码: git clone https://github.com/tkwoo/anogan-keras.git mkdir weights python main.py --mode t ...
- 26.异常检测---孤立森林 | one-class SVM
novelty detection:当训练数据中没有离群点,我们的目标是用训练好的模型去检测另外发现的新样本 outlier dection:当训练数据中包含离群点,模型训练时要匹配训练数据的中心样 ...
- 异常检测-基于孤立森林算法Isolation-based Anomaly Detection-2-实现
参考https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.IsolationForest.html#sklearn.en ...
- # URL异常检测
(Isolation Forest无监督)这个算法是随机森林的推广. iTree树构造:随机选一个属性,再随机选该特征的一个值,对样本进行二叉划分,重复以上操作. iTree构建好了后,就可以对数据进 ...
- 网络KPI异常检测之时序分解算法
时间序列数据伴随着我们的生活和工作.从牙牙学语时的“1, 2, 3, 4, 5, ……”到房价的走势变化,从金融领域的刷卡记录到运维领域的核心网性能指标.时间序列中的规律能加深我们对事物和场景的认识, ...
- 【异常检测】孤立森林(Isolation Forest)算法简介
简介 工作的过程中经常会遇到这样一个问题,在构建模型训练数据时,我们很难保证训练数据的纯净度,数据中往往会参杂很多被错误标记噪声数据,而数据的质量决定了最终模型性能的好坏.如果进行人工二次标记,成本会 ...
随机推荐
- 【PyQt5-Qt Designer】猜数字(小项目)
参考:https://zhuanlan.zhihu.com/p/28287825 https://www.cnblogs.com/hhh5460/p/5174266.html 最终效果: 本次练习涉及 ...
- MSSQL2008 部署及开启远程连接
最近不少用户在windows2003 server 32位操作系统上安装SQL Server2008总是失败,出现大量错误.今天经过通过我反复测试安装,找出了一个便捷的安装方法,节省大家宝贵时间,具体 ...
- composer安装其实可以很简单 两行命令就解决了
最近接了一个cakephp项目,就想着用composer安装实施,因为Composer 可以方便地帮你安装项目中声明所依赖的外部工具库(libraries).之前没有接触过,相对比较陌生,但是相信ph ...
- perfmon——使用windows系统自带的性能监视器监控进程信息
第一次使用perfmon监控应用进程的信息,步骤总结如下: 第一部分 性能监视器 1.快捷键Win+R打开运行界面,输入“perfmon”命令后回车即可打开windows的性能监视器 2.点击“性能监 ...
- 006-优化web请求二-应用缓存、异步调用【Future、ListenableFuture、CompletableFuture】、ETag、WebSocket【SockJS、Stomp】
四.应用缓存 使用spring应用缓存.使用方式:使用@EnableCache注解激活Spring的缓存功能,需要创建一个CacheManager来处理缓存.如使用一个内存缓存示例 package c ...
- 【LNMP】提示Nginx PHP “No input file specified”错误的解决办法
原理: 任何对.php文件的请求,都简单地交给php-cgi去处理,但没有验证该php文件是否存在. PHP文件不存在,没办法返回普通的404错误,它返回 一个404,并带上一句”No input f ...
- python的static方法和class方法
class Caculator(object): name = "caculator" def __init__(self, x, y): self._x = x self._y ...
- 爆破root密码hash John the Ripper和hydra爆破ssh密码
官方网站:http://www.openwall.com/john/ 下载:wget http://www.openwall.com/john/j/john-1.8.0.tar.gz 解压:tar - ...
- ELKStack的基础入门和中文指南
一.ELKStack的中文指南 redhat系列配置repo源 rpm --import https://artifacts.elastic.co/GPG-KEY-elasticsearch vi / ...
- haproxy json 自定义格式日志 并用rsyslog 收集
haproxy的配置 日志投送: global log 127.0.0.1 local1 info 默认端口是udp514 默认日志: defaults log global log-format \ ...