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之间

相关内容

热门资讯

通达信如何看美元指数 通达信如何看美元指数一、先查看公式公式名称:CYQKL公式描述:博弈K线长度公式具体:KL:100*...
都说土豆不是蔬菜,如果用土豆代... 都说土豆不是蔬菜,如果用土豆代替米饭做主食能减肥吗?都说土豆不是蔬菜,如果用土豆代替米饭做主食的话,...
有些事情我只猜对了前面结局却没... 有些事情我只猜对了前面结局却没有猜到是什么意思 ?那是你没有看清,跟你打个比方吧!好理解,比如一个人...
郑州荥阳市一小区被外卖骑手“孤... 郑州荥阳市一小区被外卖骑手“孤立”,外卖小哥与业主之间产生了哪些矛盾?肯定是由于外卖小哥的服务态度不...
考古 探险 考古 探险江苏镇江附近有什么适合的地方吗wu````````````````
浓浓药香里 和美乡村入画来 转自:河北新闻网全国文明村镇安国市北段村乡瓦子里村——浓浓药香里 和美乡村入画来游客畅游药博园花海。...
4400mAh:三星 Gala...   炒股就看金麒麟分析师研报,权威,专业,及时,全面,助您挖掘潜力主题机会! IT之家 7 月 1...
人工智能领域国际(地区)合作研... 转自:钦州发布原标题:人工智能领域国际(地区)合作研究与交流合作项目研讨会在钦举行钱锋作主题报告 刘...
近200名实习生转正!上海迪士... 转自:上观新闻毕业季的华特迪士尼大剧院里,近200名毕业生接过了特殊的“毕业证书”——他们从上海迪士...
第一观察|“多样文明是世界的本... 转自:北京日报客户端“多样文明是世界的本色。”7月10日,习近平主席在致全球文明对话部长级会议的贺信...