shunping commented on code in PR #34232: URL: https://github.com/apache/beam/pull/34232#discussion_r1987842803
########## sdks/python/apache_beam/ml/anomaly/detectors/robust_zscore.py: ########## @@ -0,0 +1,119 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import logging +import math +from typing import Optional + +import apache_beam as beam +from apache_beam.ml.anomaly.base import AnomalyDetector +from apache_beam.ml.anomaly.specifiable import specifiable +from apache_beam.ml.anomaly.thresholds import FixedThreshold +from apache_beam.ml.anomaly.univariate.base import EPSILON +from apache_beam.ml.anomaly.univariate.mad import MadTracker + + +# pylint: disable=line-too-long +@specifiable +class RobustZScore(AnomalyDetector): + """Robust Z-Score anomaly detector. + + This class implements an detection algorithm based on Robust Z-Score (also + known as Modified Z-Score), which is a robust alternative to the traditional + Z-score [#]_. It uses the median and Median Absolute Deviation (MAD) to + compute a score that is less sensitive to outliers. + + The score is calculated as: `|0.6745 * (value - median) / MAD|` + + Important: + In the streaming setting, we use the online version of median and MAD in the + calculation. Therefore, the score computed here does not exactly match its + batch counterpart. + + This implementation is adapted from the implementation within PySAD [#]_: + https://github.com/selimfirat/pysad/blob/master/pysad/models/median_absolute_deviation.py + + The batch version can be seen at PyOD [#]_: + https://github.com/yzhao062/pyod/blob/master/pyod/models/mad.py + + + Args: + mad_tracker: Optional `MadTracker` instance. If None, a default `MadTracker` + is created. + threshold_criterion: threshold_criterion: Optional `ThresholdFn` to apply on + the score. Defaults to `FixedThreshold(3)` due to the commonly used + 3-sigma rule. + **kwargs: Additional keyword arguments. + + .. [#] Hoaglin, David C.. (2013). Volume 16: How to Detect and Handle Outliers. + .. [#] Yilmaz, Selim & Kozat, Suleyman. (2020). PySAD: A Streaming Anomaly Detection Framework in Python. 10.48550/arXiv.2009.02572. + .. [#] Zhao, Y., Nasrullah, Z. and Li, Z.. (2019). PyOD: A Python Toolbox for Scalable Outlier Detection. Journal of machine learning research (JMLR), 20(96), pp.1-7. + """ + # pylint: enable=line-too-long + SCALE_FACTOR = 0.6745 + + def __init__(self, mad_tracker: Optional[MadTracker] = None, **kwargs): + if "threshold_criterion" not in kwargs: + kwargs["threshold_criterion"] = FixedThreshold(3) + super().__init__(**kwargs) + self._mad_tracker = mad_tracker or MadTracker() + + def learn_one(self, x: beam.Row) -> None: + """Updates the `MadTracker` with a new data point. + + Args: + x: A `beam.Row` containing a single numerical value. + """ + if len(x.__dict__) != 1: + logging.warning( + "RobustZScore.learn_one expected univariate input, but got %s", + str(x)) + return Review Comment: +1 -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
