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

相关内容

热门资讯

中证A500ETF摩根(560... 8月22日,截止午间收盘,中证A500ETF摩根(560530)涨1.19%,报1.106元,成交额...
A500ETF易方达(1593... 8月22日,截止午间收盘,A500ETF易方达(159361)涨1.28%,报1.104元,成交额1...
何小鹏斥资约2.5亿港元增持小... 每经记者|孙磊    每经编辑|裴健如 8月21日晚间,小鹏汽车发布公告称,公司联...
中证500ETF基金(1593... 8月22日,截止午间收盘,中证500ETF基金(159337)涨0.94%,报1.509元,成交额2...
中证A500ETF华安(159... 8月22日,截止午间收盘,中证A500ETF华安(159359)涨1.15%,报1.139元,成交额...
科创AIETF(588790)... 8月22日,截止午间收盘,科创AIETF(588790)涨4.83%,报0.760元,成交额6.98...
创业板50ETF嘉实(1593... 8月22日,截止午间收盘,创业板50ETF嘉实(159373)涨2.61%,报1.296元,成交额1...
港股异动丨航空股大幅走低 中国... 港股航空股大幅下跌,其中,中国国航跌近7%表现最弱,中国东方航空跌近5%,中国南方航空跌超3%,美兰...
电网设备ETF(159326)... 8月22日,截止午间收盘,电网设备ETF(159326)跌0.25%,报1.198元,成交额409....
红利ETF国企(530880)... 8月22日,截止午间收盘,红利ETF国企(530880)跌0.67%,报1.034元,成交额29.0...