Spark实战4:异常检测算法Scala语言
异常检测原理是根据训练数据的高斯分布,计算均值和方差,若测试数据样本点带入高斯公式计算的概率低于某个阈值(0.1),判定为异常点。
1 创建数据集转化工具类,把csv数据集转化为RDD数据结构
import org.apache.spark.mllib.linalg.{Vector, Vectors} import org.apache.spark.mllib.regression.LabeledPoint import org.apache.spark.rdd.RDD object FeaturesParser{ def parseFeatures(rawdata: RDD[String]): RDD[Vector] = { val rdd: RDD[Array[Double]] = rawdata.map(_.split(",").map(_.toDouble)) val vectors: RDD[Vector] = rdd.map(arrDouble => Vectors.dense(arrDouble)) vectors } def parseFeaturesWithLabel(cvData: RDD[String]): RDD[LabeledPoint] = { val rdd: RDD[Array[Double]] = cvData.map(_.split(",").map(_.toDouble)) val labeledPoints = rdd.map(arrDouble => ), Vectors.dense(arrDouble.slice(, arrDouble.length)))) labeledPoints } }
2 创建异常检测工具类,主要是预测是否为异常点
object AnomalyDetection { /** * True if the given point is an anomaly, false otherwise * @param point * @param means * @param variances * @param epsilon * @return */ def predict (point: Vector, means: Vector, variances: Vector, epsilon: Double): Boolean = { println("-->") println("-->v1"+probFunction(point, means, variances)) println("-->v2"+epsilon) probFunction(point, means, variances) < epsilon } def probFunction(point: Vector, means: Vector, variances: Vector): Double = { val tripletByFeature: List[(Double, Double, Double)] = (point.toArray, means.toArray, variances.toArray).zipped.toList tripletByFeature.map { triplet => val x = triplet._1 val mean = triplet._2 val variance = triplet._3 val expValue = Math.pow(Math.E, -) / variance) (1.0 / (Math.sqrt(variance) * Math.sqrt(2.0 * Math.PI))) * expValue }.product } }
3异常检测模型类
import org.apache.spark.mllib.linalg._ import org.apache.spark.rdd.RDD class AnomalyDetectionModel(means2: Vector, variances2: Vector, epsilon2: Double) extends java.io.Serializable{ var means: Vector = means2 var variances: Vector = variances2 var epsilon: Double = epsilon2 def predict(point: Vector) : Boolean ={ println("-->1") AnomalyDetection.predict(point, means, variances, epsilon) } def predict(points: RDD[Vector]): RDD[(Vector, Boolean)] = { println("-->2") points.map(p => (p,AnomalyDetection.predict(p, means, variances, epsilon))) } }
4 包括启动异常检测模型,优化参数,输出评价指标等函数功能(注意序列化Serializable )
import org.apache.spark.Logging import org.apache.spark.mllib.linalg._ import org.apache.spark.mllib.regression.LabeledPoint import org.apache.spark.mllib.stat.{MultivariateStatisticalSummary, Statistics} import org.apache.spark.rdd.RDD /** * Anomaly Detection algorithm */ class AnomalyDetection extends java.io.Serializable with Logging { val default_epsilon: Double = 0.01 def run(data: RDD[Vector]): AnomalyDetectionModel = { val sc = data.sparkContext val stats: MultivariateStatisticalSummary = Statistics.colStats(data) val mean: Vector = stats.mean val variances: Vector = stats.variance logInfo("MEAN %s VARIANCE %s".format(mean, variances)) // println(s"--> MEAN VARIANCE$mean,$variances") println("--> MEAN VARIANCE"+mean+variances) new AnomalyDetectionModel(mean, variances, default_epsilon) } /** * Uses the labeled input points to optimize the epsilon parameter by finding the best F1 Score * @param crossValData * @param anomalyDetectionModel * @return */ def optimize(crossValData: RDD[LabeledPoint], anomalyDetectionModel: AnomalyDetectionModel) = { val sc = crossValData.sparkContext val bcMean = sc.broadcast(anomalyDetectionModel.means) val bcVar = sc.broadcast(anomalyDetectionModel.variances) //compute probability density function for each example in the cross validation set val probsCV: RDD[Double] = crossValData.map(labeledpoint => AnomalyDetection.probFunction(labeledpoint.features, bcMean.value, bcVar.value) ) //select epsilon crossValData.persist() val epsilonWithF1Score: (Double, Double) = evaluate(crossValData, probsCV) crossValData.unpersist() logInfo("Best epsilon %s F1 score %s".format(epsilonWithF1Score._1, epsilonWithF1Score._2)) new AnomalyDetectionModel(anomalyDetectionModel.means, anomalyDetectionModel.variances, epsilonWithF1Score._1) } /** * Finds the best threshold to use for selecting outliers based on the results from a validation set and the ground truth. * * @param crossValData labeled data * @param probsCV probability density function as calculated for the labeled data * @return Epsilon and the F1 score */ private def evaluate(crossValData: RDD[LabeledPoint], probsCV: RDD[Double]) = { val minPval: Double = probsCV.min() val maxPval: Double = probsCV.max() logInfo("minPVal: %s, maxPVal %s".format(minPval, maxPval)) val sc = probsCV.sparkContext var bestEpsilon = 0D var bestF1 = 0D val stepsize = (maxPval - minPval) / 1000.0 //find best F1 for different epsilons for (epsilon <- minPval to maxPval by stepsize){ val bcepsilon = sc.broadcast(epsilon) val ourPredictions: RDD[Double] = probsCV.map{ prob => if (prob < bcepsilon.value) 1.0 //anomaly else 0.0 } val labelAndPredictions: RDD[(Double, Double)] = crossValData.map(_.label).zip(ourPredictions) val labelWithPredictionCached: RDD[(Double, Double)] = labelAndPredictions val falsePositives = countStatisticalMeasure(labelWithPredictionCached, 0.0, 1.0) val truePositives = countStatisticalMeasure(labelWithPredictionCached, 1.0, 1.0) val falseNegatives = countStatisticalMeasure(labelWithPredictionCached, 1.0, 0.0) val precision = truePositives / Math.max(1.0, truePositives + falsePositives) val recall = truePositives / Math.max(1.0, truePositives + falseNegatives) val f1Score = 2.0 * precision * recall / (precision + recall) if (f1Score > bestF1){ bestF1 = f1Score bestEpsilon = epsilon } } (bestEpsilon, bestF1) } /** * Function to calculate true / false positives, negatives * * @param labelWithPredictionCached * @param labelVal * @param predictionVal * @return */ private def countStatisticalMeasure(labelWithPredictionCached: RDD[(Double, Double)], labelVal: Double, predictionVal: Double): Double = { labelWithPredictionCached.filter { labelWithPrediction => val label = labelWithPrediction._1 val prediction = labelWithPrediction._2 label == labelVal && prediction == predictionVal }.count().toDouble } }
5 读取数据集,在hdfs的路径/user/mapr/,转化为RDD,训练模型,预测异常点:
import org.apache.spark.SparkConf import org.apache.spark.SparkContext import org.apache.spark.mllib.linalg._ import org.apache.spark.mllib.regression.LabeledPoint import org.apache.spark.rdd.RDD // val conf = new SparkConf().setAppName("Anomaly Detection Spark2") // val sc = new SparkContext(conf) val rawFilePath = "/user/mapr/training.csv" val cvFilePath = "/user/mapr/cross_val.csv" val rawdata = sc.textFile(rawFilePath, ).cache() val cvData = sc.textFile(cvFilePath, ).cache() val trainingVec: RDD[Vector] = FeaturesParser.parseFeatures(rawdata) val cvLabeledVec: RDD[LabeledPoint] = FeaturesParser.parseFeaturesWithLabel(cvData) // trainingVec.collect().foreach(println) // cvLabeledVec.collect().foreach(println) val data = trainingVec.cache() val anDet: AnomalyDetection = new AnomalyDetection() //derive model val model = anDet.run(data) val dataCvVec = cvLabeledVec.cache() // val optimalModel = anDet.optimize(dataCvVec, model) //find outliers in CV val cvVec = cvLabeledVec.map(_.features) // cvVec.collect().foreach(println) // print("-->"+typeOf[cvVec]) val results = model.predict(cvVec) // results.collect().foreach(println) val outliers = results.filter(_._2).collect() // outliers.foreach(v => println(v._1)) println("\nFound %s outliers\n".format(outliers.length))
备注:输出的部分结果为,异常点输出
Spark实战4:异常检测算法Scala语言的更多相关文章
- 机器学习:异常检测算法Seasonal Hybrid ESD及R语言实现
Twritters的异常检测算法(Anomaly Detection)做的比较好,Seasonal Hybrid ESD算法是先用STL把序列分解,考察残差项.假定这一项符合正态分布,然后就可以用Ge ...
- 异常检测算法--Isolation Forest
南大周志华老师在2010年提出一个异常检测算法Isolation Forest,在工业界很实用,算法效果好,时间效率高,能有效处理高维数据和海量数据,这里对这个算法进行简要总结. iTree 提到森林 ...
- 异常检测算法:Isolation Forest
iForest (Isolation Forest)是由Liu et al. [1] 提出来的基于二叉树的ensemble异常检测算法,具有效果好.训练快(线性复杂度)等特点. 1. 前言 iFore ...
- 【机器学习】异常检测算法(I)
在给定的数据集,我们假设数据是正常的 ,现在需要知道新给的数据Xtest中不属于该组数据的几率p(X). 异常检测主要用来识别欺骗,例如通过之前的数据来识别新一次的数据是否存在异常,比如根据一个用户以 ...
- kaggle信用卡欺诈看异常检测算法——无监督的方法包括: 基于统计的技术,如BACON *离群检测 多变量异常值检测 基于聚类的技术;监督方法: 神经网络 SVM 逻辑回归
使用google翻译自:https://software.seek.intel.com/dealing-with-outliers 数据分析中的一项具有挑战性但非常重要的任务是处理异常值.我们通常将异 ...
- 如何开发一个异常检测系统:使用什么特征变量(features)来构建异常检测算法
如何构建与选择异常检测算法中的features 如果我的feature像图1所示的那样的正态分布图的话,我们可以很高兴地将它送入异常检测系统中去构建算法. 如果我的feature像图2那样不是正态分布 ...
- 异常检测(Anomaly detection): 异常检测算法(应用高斯分布)
估计P(x)的分布--密度估计 我们有m个样本,每个样本有n个特征值,每个特征都分别服从不同的高斯分布,上图中的公式是在假设每个特征都独立的情况下,实际无论每个特征是否独立,这个公式的效果都不错.连乘 ...
- 异常检测算法的Octave仿真
在基于高斯分布的异常检测算法一文中,详细给出了异常检测算法的原理及其公式,本文为该算法的Octave仿真.实例为,根据训练样例(一组网络服务器)的吞吐量(Throughput)和延迟时间(Latenc ...
- 异常检测算法Robust Random Cut Forest(RRCF)关键定理引理证明
摘要:RRCF是亚马逊发表的一篇异常检测算法,是对周志华孤立森林的改进.但是相比孤立森林,具有更为扎实的理论基础.文章的理论论证相对较为晦涩,且没给出详细的证明过程.本文不对该算法进行详尽的描述,仅对 ...
随机推荐
- Trie字典树 动态内存
Trie字典树 #include "stdio.h" #include "iostream" #include "malloc.h" #in ...
- getAttribute与setAttribute用法
getAttribute和setAttribute只能用于元素节点. 1.当用getElementById获得元素节点时 /*---------------------------index.html ...
- 打造移动终端的 WebApp(一):搭建一个舞台
最近随着 Apple iOS 和 Android 平台的盛行,一个新的名词 WebApp 也逐渐火了起来,这里我也趁着热潮做一个关于 WebApp 系列的学习笔记,分享平时的一些研究以及项目中的经验, ...
- Linux下JDK安装笔记
环境说明: Linux版本: CentOS6.2 JDK:jdk-7u60-linux-x64.tar.gz 1.下载jdk-7u60-linux-x64.tar.gz,本人是放到了~/工具 目录 ...
- MyEclipse不能重新发布的解决方案
myeclipse2015已发布项目上右键clear不重新发布的解决方案: 该项目在server.xml中没有设置自动发布reloadable="true"
- java常用工具类
http://www.cnblogs.com/langtianya/p/3875124.html
- 【iCore3 双核心板_FPGA】实验十四:FSMC总线通信实验——独立地址模式
实验指导书及代码包下载: http://pan.baidu.com/s/1kVJBxJ5 iCore3 购买链接: https://item.taobao.com/item.htm?id=524229 ...
- support HTML5 in IE8
<!--this code is used to support HTML5 in IE8--> <!--[if IE]><script type="text/ ...
- js滚动加载插件
function $xhyload(o){ var that=this; if(!o){ return; }else{ that.win=$(o.config.obj); that.qpanel=$( ...
- MyEclipse 8.5整合Git,并在Github上发布项目【转】
最近Git火得如日中天,而且速度体验和团队模式都很不错.手头正好有个学生实训项目,时间紧任务重,而且学校内网管理太紧,所以就想借助于Internet的分布式开发,因此想到了Github. 经过一天的调 ...