异常检测——局部异常因子(Local Outlier Factor ,LOF)算法
在中等高维数据集上执行异常值检测的另一种有效方法是使用局部异常因子(Local Outlier Factor ,LOF)算法。
1、算法思想
LOF通过计算一个数值score来反映一个样本的异常程度。这个数值的大致意思是:一个样本点周围的样本点所处位置的平均密度比上该样本点所在位置的密度。比值越大于1,则该点所在位置的密度越小于其周围样本所在位置的密度,这个点就越有可能是异常点。关于密度等理论概念,详见下面第二部分。
2、LOF的具体理论
关于LOF的理论,可以参考这篇文章,写的非常详细具体!
https://blog.csdn.net/wangyibo0201/article/details/51705966
3、LocalOutlierFactor主要参数和函数介绍
class sklearn.neighbors.LocalOutlierFactor(n_neighbors=20, algorithm=’auto’, leaf_size=30, metric=’minkowski’, p=2, metric_params=None, contamination=0.1, n_jobs=1)
1)主要参数
       n_neighbors : 
                 设置k,default=20
       contamination : 
                 设置样本中异常点的比例,default=0.1
2)主要属性:
       negative_outlier_factor_ : numpy array, shape (n_samples,)
                 和LOF相反的值,值越小,越有可能是异常点。(注:上面提到LOF的值越接近1,越可能是正常样本,LOF的值越大于1,则越可能是异常样本)。这里就正好反一下。
3)主要函数:
        fit_predict(X)
                  X : array-like, shape (n_samples, n_features
                  返回一个数组,-1表示异常点,1表示正常点。
4、LOF实例(sklearn)
# !/usr/bin/python
    # -*- coding:utf-8 -*-
     
    import numpy as np
    import matplotlib.pyplot as plt
    from sklearn.neighbors import LocalOutlierFactor
    from scipy import stats
     
    # 构造训练样本
    n_samples = 200  #样本总数
    outliers_fraction = 0.25  #异常样本比例
    n_inliers = int((1. - outliers_fraction) * n_samples)
    n_outliers = int(outliers_fraction * n_samples)
     
    rng = np.random.RandomState(42)
    X = 0.3 * rng.randn(n_inliers // 2, 2)
    X_train = np.r_[X + 2, X - 2]   #正常样本
    X_train = np.r_[X_train, np.random.uniform(low=-6, high=6, size=(n_outliers, 2))]  #正常样本加上异常样本
     
    # fit the model
    clf = LocalOutlierFactor(n_neighbors=35, contamination=outliers_fraction)
    y_pred = clf.fit_predict(X_train)
    scores_pred = clf.negative_outlier_factor_
    threshold = stats.scoreatpercentile(scores_pred, 100 * outliers_fraction)  # 根据异常样本比例,得到阈值,用于绘图
     
    # plot the level sets of the decision function
    xx, yy = np.meshgrid(np.linspace(-7, 7, 50), np.linspace(-7, 7, 50))
    Z = clf._decision_function(np.c_[xx.ravel(), yy.ravel()])  # 类似scores_pred的值,值越小越有可能是异常点
    Z = Z.reshape(xx.shape)
     
    plt.title("Local Outlier Factor (LOF)")
    # plt.contourf(xx, yy, Z, cmap=plt.cm.Blues_r)
     
    plt.contourf(xx, yy, Z, levels=np.linspace(Z.min(), threshold, 7), cmap=plt.cm.Blues_r)  # 绘制异常点区域,值从最小的到阈值的那部分
    a = plt.contour(xx, yy, Z, levels=[threshold], linewidths=2, colors='red')  # 绘制异常点区域和正常点区域的边界
    plt.contourf(xx, yy, Z, levels=[threshold, Z.max()], colors='palevioletred')  # 绘制正常点区域,值从阈值到最大的那部分
     
    b = plt.scatter(X_train[:-n_outliers, 0], X_train[:-n_outliers, 1], c='white',
                        s=20, edgecolor='k')
    c = plt.scatter(X_train[-n_outliers:, 0], X_train[-n_outliers:, 1], c='black',
                        s=20, edgecolor='k')
    plt.axis('tight')
    plt.xlim((-7, 7))
    plt.ylim((-7, 7))
    plt.legend([a.collections[0], b, c],
               ['learned decision function', 'true inliers', 'true outliers'],
               loc="upper left")
    plt.show()
结果:
参考文献:
http://scikit-learn.org/stable/modules/generated/sklearn.neighbors.LocalOutlierFactor.html#sklearn.neighbors.LocalOutlierFactor
http://scikit-learn.org/stable/auto_examples/neighbors/plot_lof.html
http://scikit-learn.org/stable/auto_examples/covariance/plot_outlier_detection.html
https://blog.csdn.net/wangyibo0201/article/details/51705966 
---------------------  
原文:https://blog.csdn.net/YE1215172385/article/details/79766906
异常检测——局部异常因子(Local Outlier Factor ,LOF)算法的更多相关文章
- 离群点检测与序列数据异常检测以及异常检测大杀器-iForest
		
1. 异常检测简介 异常检测,它的任务是发现与大部分其他对象不同的对象,我们称为异常对象.异常检测算法已经广泛应用于电信.互联网和信用卡的诈骗检测.贷款审批.电子商务.网络入侵和天气预报等领域.这些异 ...
 - 从时序异常检测(Time series anomaly detection algorithm)算法原理讨论到时序异常检测应用的思考
		
1. 主要观点总结 0x1:什么场景下应用时序算法有效 历史数据可以被用来预测未来数据,对于一些周期性或者趋势性较强的时间序列领域问题,时序分解和时序预测算法可以发挥较好的作用,例如: 四季与天气的关 ...
 - 【异常检测】孤立森林(Isolation Forest)算法简介
		
简介 工作的过程中经常会遇到这样一个问题,在构建模型训练数据时,我们很难保证训练数据的纯净度,数据中往往会参杂很多被错误标记噪声数据,而数据的质量决定了最终模型性能的好坏.如果进行人工二次标记,成本会 ...
 - WebApi 全局异常与局部异常
		
全局异常过滤器 public class ApiExceptionFilter:ExceptionFilterAttribute { private IHostingEnvironment _env; ...
 - 异常检测LOF
		
局部异常因子算法-Local Outlier Factor(LOF)在数据挖掘方面,经常需要在做特征工程和模型训练之前对数据进行清洗,剔除无效数据和异常数据.异常检测也是数据挖掘的一个方向,用于反作弊 ...
 - Python机器学习笔记:异常点检测算法——LOF(Local Outiler Factor)
		
完整代码及其数据,请移步小编的GitHub 传送门:请点击我 如果点击有误:https://github.com/LeBron-Jian/MachineLearningNote 在数据挖掘方面,经常需 ...
 - sklearn异常检测demo
		
sklearn 异常检测demo代码走读 # 0基础学python,读代码学习python组件api import time import numpy as np import matplotlib ...
 - 【R笔记】使用R语言进行异常检测
		
本文转载自cador<使用R语言进行异常检测> 本文结合R语言,展示了异常检测的案例,主要内容如下: (1)单变量的异常检测 (2)使用LOF(local outlier factor,局 ...
 - 26.异常检测---孤立森林 | one-class SVM
		
novelty detection:当训练数据中没有离群点,我们的目标是用训练好的模型去检测另外发现的新样本 outlier dection:当训练数据中包含离群点,模型训练时要匹配训练数据的中心样 ...
 
随机推荐
- 20145335郝昊《网络攻防》Exp4 MS11_050
			
20145335郝昊<网络攻防>Exp4 MS11_050 实验内容 初步掌握平台matesploit的使用 了解漏洞MS11_050漏洞:use-after-free漏洞,即对象被释放之 ...
 - vijos 运输计划 - 二分答案 - 差分 - Tarjan
			
Description 公元 2044 年,人类进入了宇宙纪元.L 国有 n 个星球,还有 n−1 条双向航道,每条航道建立在两个星球之间,这 n−1 条航道连通了 L 国的所有星球.小 P 掌管一家 ...
 - Win32 API编程:使用CreateProcess创建新进程
			
#include <windows.h> #include <tchar.h> #include <stdio.h> int main(int argc, char ...
 - SQL数据插入字符串时转义函数
			
函数一: std::string CheckString(std::string& strSource) { std::string strOldValue = "'"; ...
 - Spring Aop的理解和简单实现
			
1.AOP概念 所说的面向切面编程其实就是在处理一系列业务逻辑的时候这一系列动作看成一个动作集合.比如连接数据库来说: 加载驱动-----获取class--------获取连接对象-------访问数 ...
 - C#面试题集锦
			
1.貌似最常用的是 值类型和引用类型,还有 装箱和 http://www.cnblogs.com/Autumoon/archive/2008/08/18/1270685.html http://ww ...
 - 【第三十六章】 metrics(4)- metrics-graphite
			
将metrics report给graphite(carbon-relay) 一.代码 1.pom.xml <!-- metrics-graphite --> <dependency ...
 - 【第二十七章】 springboot + zipkin(brave-okhttp实现)
			
本文截取自:http://blog.csdn.net/liaokailin/article/details/52077620 一.前提 1.zipkin基本知识:附8 zipkin 2.启动zipki ...
 - Mac升级到EI Captain之后pip install 无法使用问题
			
错误log: creating /System/Library/Frameworks/Python.framework/Versions/2.7/share error: could not crea ...
 - CRLF line terminators导致shell脚本报错:command not found --转载
			
Linux和Windows文本文件的行结束标志不同.在Linux中,文本文件用"/n"表示回车换行,而Windows用"/r/n"表示回车换行.有时候在Wind ...