deequ 2.0.1 anomaly的代码简单分析
创始人
2024-02-07 23:43:51
0

anomaly 总体说明

anomaly是基于两次check的结果,因此必须使用repository 进行比较,比较方法被称为strategy,有如下几种:

  • OnlineNormalStrategy 直接override def detect ,根据平均值和标准方差进行比较 mean and standard deviation.
  • SimpleThresholdStrategy : 值必须在指定范围内
  • BatchNormalStrategy :正太分布检测,所有数据在 mean lowerDeviationFactor * stdDev 和 mean + upperDeviationFactor * stdDev之间
  • AbsoluteChangeStrategy 两次变化的绝对数量,使用super trait的diff:减法
  • RelativeRateOfChangeStrategy ,两次变化的比例,diff函数中使用除法

repository

repository 目前只有文件及内存两种,文件其实就是json格式的结果保存(带timestamp 及tag:即key)

核心代码

生成Check,check包括3部分:

 /*** Add a check using Anomaly Detection methods. The Anomaly Detection Strategy only checks* if the new value is an Anomaly.** @param anomalyDetectionStrategy 策略,可以见上一节 The anomaly detection strategy* @param analyzer 和普通check一样的Analyzer,比如size,containUrl等The analyzer for the metric to run anomaly detection on* @param anomalyCheckConfig Some configuration settings for the Check 配置,主要是指定描述、指定可以比较的上一次结果的生成日期访问、tag等等,可以忽略不用,example里面也没有用*/def addAnomalyCheck[S <: State[S]](anomalyDetectionStrategy: AnomalyDetectionStrategy,analyzer: Analyzer[S, Metric[Double]],anomalyCheckConfig: Option[AnomalyCheckConfig] = None): this.type = {val anomalyCheckConfigOrDefault = anomalyCheckConfig.getOrElse {val checkDescription = s"Anomaly check for ${analyzer.toString}"AnomalyCheckConfig(CheckLevel.Warning, checkDescription)}checks :+= VerificationRunBuilderHelper.getAnomalyCheck(metricsRepository.get,anomalyDetectionStrategy, analyzer, anomalyCheckConfigOrDefault)this}

checkConfig 类

/*** Configuration for an anomaly check** @param level         Assertion level of the check group. If any of the constraints fail this*                      level is used for the status of the check.* @param description   The name describes the check block. Generally will be used to show in*                      the logs.* @param withTagValues Can contain a Map with tag names and the corresponding values to filter*                      for the Anomaly Detection* @param afterDate     The minimum dateTime of previous AnalysisResults to use for the*                      Anomaly Detection* @param beforeDate    The maximum dateTime of previous AnalysisResults to use for the*                      Anomaly Detection* @return*/
case class AnomalyCheckConfig(level: CheckLevel.Value,description: String,withTagValues: Map[String, String] = Map.empty,afterDate: Option[Long] = None,beforeDate: Option[Long] = None)

默认Constraint

 def anomalyConstraint[S <: State[S]](analyzer: Analyzer[S, Metric[Double]],anomalyAssertion: Double => Boolean,hint: Option[String] = None): Constraint = {val constraint = AnalysisBasedConstraint[S, Double, Double](analyzer, anomalyAssertion,hint = hint)new NamedConstraint(constraint, s"AnomalyConstraint($analyzer)")}

实际比较在detect 或者diff 函数内,不同strategy 类代码稍有不同

// 默认detect调用diff进行比较
override def detect(dataSeries: Vector[Double],searchInterval: (Int, Int))
: Seq[(Int, Anomaly)] = {val (start, end) = searchIntervalrequire(start <= end,"The start of the interval cannot be larger than the end.")val startPoint = Seq(start - order, 0).maxval data = diff(DenseVector(dataSeries.slice(startPoint, end): _*), order).datadata.zipWithIndex.filter { case (value, _) =>(value < maxRateDecrease.getOrElse(Double.MinValue)|| value > maxRateIncrease.getOrElse(Double.MaxValue))}.map { case (change, index) =>(index + startPoint + order, Anomaly(Option(dataSeries(index + startPoint + order)), 1.0,Some(s"[AbsoluteChangeStrategy]: Change of $change is not in bounds [" +s"${maxRateDecrease.getOrElse(Double.MinValue)}, " +s"${maxRateIncrease.getOrElse(Double.MaxValue)}]. Order=$order")))}
}/**
RelativeRateOfChangeStrategy 的diff ,除法* Calculates the rate of change with respect to the specified order.* If the order is set to 1, the resulting value for a point at index i* is equal to dataSeries (i) / dataSeries(i - 1).* Note that this difference cannot be calculated for the first [[order]] elements in the vector.* The resulting vector is therefore smaller by [[order]] elements.** @param dataSeries The values contained in a DenseVector[Double]* @param order      The order of the derivative.* @return A vector with the resulting rates of change for all values*         except the first [[order]] elements.*/
override def diff(dataSeries: DenseVector[Double], order: Int): DenseVector[Double] = {require(order > 0, "Order of diff cannot be zero or negative")if (dataSeries.length == 0) {dataSeries} else {val valuesRight = dataSeries.slice(order, dataSeries.length)val valuesLeft = dataSeries.slice(0, dataSeries.length - order)valuesRight / valuesLeft}
}// AbsoluteChangeStrategy 使用super trait的diff:减法
def diff(dataSeries: DenseVector[Double], order: Int): DenseVector[Double] = {require(order >= 0, "Order of diff cannot be negative")if (order == 0 || dataSeries.length == 0) {dataSeries} else {val valuesRight = dataSeries.slice(1, dataSeries.length)val valuesLeft = dataSeries.slice(0, dataSeries.length - 1)diff(valuesRight - valuesLeft, order - 1)}
}

OnlineNormalStrategy 直接override def detect ,根据平均值和标准方差进行比较 mean and standard deviation.

SimpleThresholdStrategy : 值必须在指定范围内

BatchNormalStrategy :正太分布检测,所有数据在 mean - lowerDeviationFactor * stdDev 和 mean + upperDeviationFactor * stdDev之间

相关内容

热门资讯

杨字的含义 杨字的含义 扬:张扬,自得的意思【解释】:趾高:走路时脚抬得很高;气扬:意气扬扬。走路时脚抬得很...
有梦子的四字成语? 有梦子的四字成语?白日做梦、魂牵梦萦、如梦初醒、梦寐以求、酣然入梦、半梦半醒、重温旧梦、夜长梦多、同...
恶人自有恶人磨 恶人自有恶人磨恶人自有恶人磨 (è rén zì yǒu è rén mó)解释:凶恶成性的人自然...
相对论中,火车断桥问题的答案是... 相对论中,火车断桥问题的答案是什么?这个假设唯一只有一个问题。败伏什么叫做“同时”?“只有两个发射器...
虎什么熊的成语 虎什么熊的成语这不是闹经急转弯虎背熊腰hǔ bèi xióng yāo成语解释如虎般宽厚的背;似熊样...
《亡念之扎姆德》男主角最后跟谁... 《亡念之扎姆德》男主角最后跟谁在一起?男主石化了九年,女主每天都来和他说话,然后九年后的第二天男主解...
火影忍者动画和漫画貌似不一样,... 火影忍者动画和漫画貌似不一样,海贼王动画和漫画一样吗?总是有些偏差的吧。。个人比较忠实原作。海贼王没...
让人非我弱,得志莫离群 让人非我弱,得志莫离群像投鼠忌器一样的意思吧,我躲,不是我怕你,而是我心有顾忌.不是因为势力差距而起...
《北宋小厨师》这本书更到现在男... 《北宋小厨师》这本书更到现在男猪脚泡到李师师和李清照了吗没有0.0....还没有啊因为还没结局
路边油炸的小摊上的酱是怎么做的... 路边油炸的小摊上的酱是怎么做的!要是家用,那可以选择用芝麻浆来做主配料.芝麻浆和水要1:1(水最好是...
《超禁忌游戏-五十分之一》应该... 《超禁忌游戏-五十分之一》应该完结了吧你要的是完整版的,但负责任地告诉你,现在不可能有,有也是骗你的...
公共经济学 答案 公共经济学 答案这个真不知道~!~谢谢~!~1.D2.D3.C4.B5.C6.D7.C8.B9.B1...
证券投资学 跟投资学有什么区别 证券投资学 跟投资学有什么区别投资学包括证券投资学。投资学包括各方面的投资学,比如黄金投资,期货投资...
忘记名字了,就是男主得到系统打... 忘记名字了,就是男主得到系统打英雄联盟,在联盟里边开挂可以变身眼可以变成野怪可以身穿求这部小说名字你...
个性签名为了你我愿意变成魔于全... 个性签名为了你我愿意变成魔于全世界为敌不爱那么多,只爱一点点,别人眉来又眼去,我只偷看你一眼。不要走...
野钓实用技巧 黑坑钓鱼技巧? 野钓实用技巧 黑坑钓鱼技巧?钓什么鱼要了解鱼的习性,了解对象鱼生活在哪个水层,喜欢吃什么食物,然后根...
江哲是那本书的? 江哲是那本书的?字随云的是《随波逐流之一代军师》字守义的是《三国之宅行天下》呵呵……这两本小说的江哲...
满满的生活经历是啥意思? 满满的生活经历是啥意思?满满的生活经历,说明的是这个人的生活阅历很深。
哪部国产青春剧比较贴近现实? 哪部国产青春剧比较贴近现实?《最好的我们》比较贴近现实,讲述的就是校园爱情故事,说的就是真实的高中生...
天涯海角与君共度 出自哪首歌呢... 天涯海角与君共度 出自哪首歌呢。云中歌主题曲丝罗李宇春的丝罗你好。楼主。李宇春《丝罗》伊本丝萝愿托乔...