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是亚马逊发表的一篇异常检测算法,是对周志华孤立森林的改进.但是相比孤立森林,具有更为扎实的理论基础.文章的理论论证相对较为晦涩,且没给出详细的证明过程.本文不对该算法进行详尽的描述,仅对 ...
随机推荐
- 使用swf与swc引入资源的区别[as3]
SWF用于运行时加载,而SWC在编译时用做外部库.使用SWC库,只有当类被引用,才编译入主程序中. getDefinition: 在使用swc库方式引入资源时,getDefinitionByName反 ...
- Linux_文件及文件夹[创建][复制][移动][删除][重命名]
一.文件/文件夹创建 1.文件的创建 touch , vi/vim/nano , ... 语 法: touch [-acfm][-d <日期时间>][-r <参考文件或目 录&g ...
- windows查看进程
由端口到进程: 直接查看进程: 查看本机连接端口: 杀进程: (eg:kill httpd) tskill 1596
- 启动tomcat,报java.lang.NoClassDefFoundError
用的Build Path加进来的jar包,没有读取到,应该讲jar包放在lib目录下
- GitHub上删除项目
1. 在自己的repositories中,选择要删除的项目,左击. 2. 选择 [Settings] 3. 选择 [Delete ** ] 4. 在弹出框中 输入 要删除的项目名,点击下方的按钮 ...
- HTML 5 服务器发送事件
接收 Server-Sent 事件通知 EventSource 对象用于接收服务器发送事件通知: 实例 var source=new EventSource("demo_sse.php&qu ...
- Oracle10g RAC的简单操作
1.查看OCR位置用户指定的位置会被放置在 /etc/oracle/ocr.loc(Liunx系统) 或 /var/opt/oracle/ocr.loc [oracle@rac4 opt]$ cat ...
- window.open()&&window.showmodaldialog()
open 打开一个新窗口,并装载URL指定的文档,或装载一个空白文档,如果没提供URL的话. 适用于 窗口 语法 window = object.open([URL[,name[,features[, ...
- php Use of undefined constant的问题解决方式
在每个文件头上加 error_reporting(0); 或者 搜索php.ini: error_reporting = E_ALL 改为: error_reporting = E_ALL & ...
- 在HTML文件的表单中添加{%csrf_token%}便可以解决问题
原因是django为了在用户提交表单时防止跨站攻击所做的保护 只需在HTML文件的表单中添加{%csrf_token%}便可以解决问题 ------------------------if判断{% i ...