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是亚马逊发表的一篇异常检测算法,是对周志华孤立森林的改进.但是相比孤立森林,具有更为扎实的理论基础.文章的理论论证相对较为晦涩,且没给出详细的证明过程.本文不对该算法进行详尽的描述,仅对 ...
随机推荐
- php by oneself
在php里面写html代码真的很麻烦,最近学到了一个新的方法: <html> <head> <title>PHP</title> <meta ht ...
- AJAX回调(调用后台方法返回数据)
记得先要导入jquery.js. 格式一 $.ajax({"Key1":"value1","key2":"value2" ...
- [转载]窗口之间的主从关系与Z-Order
窗口之间的主从关系与Z-Order 原文地址:http://www.cnblogs.com/dhatbj/p/3288152.html说明:这是本人2008年写的一篇旧文,从未公开发表过.其中除了一小 ...
- 2016HUAS暑假集训训练题 F - 简单计算器
Description 读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值. Input 测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运 ...
- 5_STL设计理念_迭代器
他山之石,可以攻玉. http://blog.csdn.net/jxh_123/article/details/30793397?utm_source=tuicool&utm_medium=r ...
- IOS第18天(1,核心动画layer, 旋转,缩放,平移,边框,剪裁,圆角)
****动画效果 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { [UIView animateWithDurat ...
- Python脚本模拟登录网页之ZiMuZu篇
ZiMuZu.tv这个网站喜欢看电影看美剧的人一定都熟悉. 这个网站原先的升级策略是每天登陆网站, 然后去一个"每日签到"的页面点击一个签到按钮, 以实现帐号等级的升级. 之前网上 ...
- 【iCore3 双核心板】例程十八:USB_VCP实验——虚拟串口
实验指导书及代码包下载: http://pan.baidu.com/s/1c1erqIc iCore3 购买链接: https://item.taobao.com/item.htm?id=524229 ...
- ElasticSearch实战-入门
http://www.cnblogs.com/smartloli/ 1.概述 今天接着<ElasticSearch实战-日志监控平台>一文来给大家分享后续的学习,在<ElasticS ...
- 001_从原理上搞定编码-- Base64编码
开发者对 Base64编码肯定很熟悉,是否对它有很清晰的认识就不一定了.实际 上Base64已经简单到不能再简单了,如果对它的理解还是模棱两可实在不应该.大概介绍一下Base64的相关内容,花几分钟时 ...