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)算法简介
简介 工作的过程中经常会遇到这样一个问题,在构建模型训练数据时,我们很难保证训练数据的纯净度,数据中往往会参杂很多被错误标记噪声数据,而数据的质量决定了最终模型性能的好坏.如果进行人工二次标记,成本会 ...
随机推荐
- Redis 安装、配置、集群
1. Redis的安装 1.1. Redis的安装 Redis是c语言开发的. 安装redis需要c语言的编译环境.如果没有gcc需要在线安装.yum install gcc-c++ 安装步骤: ...
- 异常 java.net.ConnectException: Connection refused: no further information
java.net.ConnectException: Connection refused: no further information at sun.nio.ch.SocketChannelImp ...
- RN TextInput用法
效果图: 代码: import React, {Component} from 'react' import {StyleSheet, View, Text, TouchableOpacity, Te ...
- Got timeout reading communication packets解决方法
Got timeout reading communication packets解决方法 http://www.th7.cn/db/mysql/201702/225243.shtml [Note] ...
- centOS和windows7双系统下重装windows后恢复centOS引导
电脑原本是windows7和centOS双系统,后来重装windows系统后,发现没有centOS引导,于是重新恢复centOS引导. 1.官网下载centos系统镜像CentOS-7-x86_64- ...
- log4j。日志输出
log4j.rootLogger = debug , stdout , D , E log4j.appender.stdout = org.apache.log4j.ConsoleAppender l ...
- 3-Python3 环境搭建
- 玩nginx部署不同的web app
需求:一台服务器上部署多个应用 ,比如www.host.com/app 映射到 www.host.com:8081 实现方法:1. nginx 使用把路径访问映射到端口上.但是遇到一个问题是web a ...
- 一步一步学Python(3) 基础补充
最近在系统学习Python,以MOOC上面的一套Python3的课程为基础.本文主要总结一下基础部分的关键点. 1.python基本数据类型 2.python运算符 3.构建简洁高效的IDE环境 4. ...
- border的特殊用法
大家很容易在一些网页上看到二级菜单上有一个小的三角形,这个小三角型 除了可以使用图片或者使用iconfont写出来,还可以使用border写出来 这边简单的为大家举一个例子,希望对大家有用吧! css ...