You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@beam.apache.org by "shunping (via GitHub)" <gi...@apache.org> on 2025/03/10 16:01:03 UTC
[PR] Add detectors and some necessary univariate trackers. [beam]
shunping opened a new pull request, #34232:
URL: https://github.com/apache/beam/pull/34232
- Add Z-score, robust Z-score and IQR detectors.
- Add median and mad trackers that are used in the detectors
- Add secondary quantile tracker that can share internal buffer with the primary.
--
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: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [AnomalyDetection] Add detectors and some necessary univariate trackers. [beam]
Posted by "shunping (via GitHub)" <gi...@apache.org>.
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: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [AnomalyDetection] Add detectors and some necessary univariate trackers. [beam]
Posted by "shunping (via GitHub)" <gi...@apache.org>.
shunping commented on code in PR #34232:
URL: https://github.com/apache/beam/pull/34232#discussion_r1987795493
##########
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|`
Review Comment:
Agree. It is a commonly used constant that has theoretical meaning: https://en.wikipedia.org/wiki/Median_absolute_deviation#Derivation.
Also, instead of letting users set a different scale factor here, they can achieve the same effect by using a different threshold function to say `FixedThreshold(4)`. This will make it consistent with how we do thresholding on traditional Z-score.
--
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: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [AnomalyDetection] Add detectors and some necessary univariate trackers. [beam]
Posted by "shunping (via GitHub)" <gi...@apache.org>.
shunping commented on code in PR #34232:
URL: https://github.com/apache/beam/pull/34232#discussion_r1987795493
##########
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|`
Review Comment:
Agree. It is a commonly used constant that has theoretical meaning: https://en.wikipedia.org/wiki/Median_absolute_deviation#Derivation.
Also, instead of letting users set a different scale factor here, they can achieve the same effect by using a different threshold function (e.g. `FixedThreshold(4)`). In this way, we can keep consistency between traditional Z-score and its robust version.
--
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: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [AnomalyDetection] Add detectors and some necessary univariate trackers. [beam]
Posted by "damccorm (via GitHub)" <gi...@apache.org>.
damccorm commented on code in PR #34232:
URL: https://github.com/apache/beam/pull/34232#discussion_r1987835737
##########
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:
> I am wondering whether it is possible (and how often it is) for a user to provide a collections of Rows while most of them has one variable, but some has multiple. In this case, we can treat the rows with multiple variables ill-formatted input and simply ignore it.
This shouldn't happen, type checking should keep this from happening. That's why I think this is a pretty exceptional case and indicates that their whole setup is kinda broken. For streaming it won't fail the job, but it will repeatedly raise errors until the job is updated/fixed.
--
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: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [AnomalyDetection] Add detectors and some necessary univariate trackers. [beam]
Posted by "damccorm (via GitHub)" <gi...@apache.org>.
damccorm merged PR #34232:
URL: https://github.com/apache/beam/pull/34232
--
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: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [AnomalyDetection] Add detectors and some necessary univariate trackers. [beam]
Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #34232:
URL: https://github.com/apache/beam/pull/34232#issuecomment-2711093038
Stopping reviewer notifications for this pull request: review requested by someone other than the bot, ceding control. If you'd like to restart, comment `assign set of reviewers`
--
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: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [AnomalyDetection] Add detectors and some necessary univariate trackers. [beam]
Posted by "shunping (via GitHub)" <gi...@apache.org>.
shunping commented on code in PR #34232:
URL: https://github.com/apache/beam/pull/34232#discussion_r1987795493
##########
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|`
Review Comment:
Agree. It is a commonly used constant that has theoretical meaning: https://en.wikipedia.org/wiki/Median_absolute_deviation#Derivation.
Also, instead of letting users set a different scale factor here, they can achieve the same result by using a differenet threshold function to say `FixedThreshold(4)`. This will make it consistent with how we do thresholding on traditional Z-score.
##########
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|`
Review Comment:
Agree. It is a commonly used constant that has theoretical meaning: https://en.wikipedia.org/wiki/Median_absolute_deviation#Derivation.
Also, instead of letting users set a different scale factor here, they can achieve the same result by using a different threshold function to say `FixedThreshold(4)`. This will make it consistent with how we do thresholding on traditional Z-score.
--
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: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [AnomalyDetection] Add detectors and some necessary univariate trackers. [beam]
Posted by "shunping (via GitHub)" <gi...@apache.org>.
shunping commented on code in PR #34232:
URL: https://github.com/apache/beam/pull/34232#discussion_r1987805477
##########
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:
Will that cause the entire transform to fail?
I am wondering whether it is possible for a user to provide a collections of `Row`s while most of them has one variable, but some has multiple. In this case, I just want to treat the rows with multiple variables ill-formatted input and simply ignore it.
--
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: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [AnomalyDetection] Add detectors and some necessary univariate trackers. [beam]
Posted by "shunping (via GitHub)" <gi...@apache.org>.
shunping commented on code in PR #34232:
URL: https://github.com/apache/beam/pull/34232#discussion_r1987859585
##########
sdks/python/apache_beam/ml/anomaly/detectors/iqr_test.py:
##########
@@ -0,0 +1,52 @@
+#
+# 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
+import unittest
+
+import apache_beam as beam
+from apache_beam.ml.anomaly.detectors.iqr import IQR
+
+
+class IQRTest(unittest.TestCase):
+ input = [
+ beam.Row(x=1),
+ beam.Row(x=1),
+ beam.Row(x=5),
+ beam.Row(x=9),
+ beam.Row(x=20),
+ beam.Row(x=10),
+ beam.Row(x=1)
+ ]
+
+ def test_with_default_trackers(self):
+ iqr = IQR()
+
+ scores = []
+ for row in IQRTest.input:
+ scores.append(iqr.score_one(row))
+ iqr.learn_one(row)
+
+ self.assertTrue(math.isnan(scores[0]))
+ self.assertEqual(
+ scores[1:], [0.0, 0.0, 3.0, 2.8, 0.125, 0.12903225806451613])
Review Comment:
Now I begin to think if we should switch the meaning of 'NaN' and None given the property of 'NaN' in the equal function. Because in a decent pipeline, we should always see missing values and the error values will be very rare. For comparison purpose, 'None' value is more friendly than 'NaN'.
--
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: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [AnomalyDetection] Add detectors and some necessary univariate trackers. [beam]
Posted by "shunping (via GitHub)" <gi...@apache.org>.
shunping commented on code in PR #34232:
URL: https://github.com/apache/beam/pull/34232#discussion_r1987805477
##########
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:
Will that cause the entire transform to fail?
I am wondering whether it is possible (and how often it is) for a user to provide a collections of `Row`s while most of them has one variable, but some has multiple. In this case, we can treat the rows with multiple variables ill-formatted input and simply ignore it.
But this can only happen if users do not provide a feature list when calling the anomaly detection transform...
--
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: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [AnomalyDetection] Add detectors and some necessary univariate trackers. [beam]
Posted by "shunping (via GitHub)" <gi...@apache.org>.
shunping commented on code in PR #34232:
URL: https://github.com/apache/beam/pull/34232#discussion_r1987859585
##########
sdks/python/apache_beam/ml/anomaly/detectors/iqr_test.py:
##########
@@ -0,0 +1,52 @@
+#
+# 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
+import unittest
+
+import apache_beam as beam
+from apache_beam.ml.anomaly.detectors.iqr import IQR
+
+
+class IQRTest(unittest.TestCase):
+ input = [
+ beam.Row(x=1),
+ beam.Row(x=1),
+ beam.Row(x=5),
+ beam.Row(x=9),
+ beam.Row(x=20),
+ beam.Row(x=10),
+ beam.Row(x=1)
+ ]
+
+ def test_with_default_trackers(self):
+ iqr = IQR()
+
+ scores = []
+ for row in IQRTest.input:
+ scores.append(iqr.score_one(row))
+ iqr.learn_one(row)
+
+ self.assertTrue(math.isnan(scores[0]))
+ self.assertEqual(
+ scores[1:], [0.0, 0.0, 3.0, 2.8, 0.125, 0.12903225806451613])
Review Comment:
Now I begin to think if we should switch the meaning of 'NaN' and None now given the property of 'NaN', because in a decent pipeline, we should always see missing values and the error values will be very rare. For comparison purpose, 'None' value is more friendly than 'NaN'.
--
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: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [AnomalyDetection] Add detectors and some necessary univariate trackers. [beam]
Posted by "damccorm (via GitHub)" <gi...@apache.org>.
damccorm commented on code in PR #34232:
URL: https://github.com/apache/beam/pull/34232#discussion_r1987788125
##########
sdks/python/apache_beam/ml/anomaly/detectors/iqr_test.py:
##########
@@ -0,0 +1,52 @@
+#
+# 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
+import unittest
+
+import apache_beam as beam
+from apache_beam.ml.anomaly.detectors.iqr import IQR
+
+
+class IQRTest(unittest.TestCase):
+ input = [
+ beam.Row(x=1),
+ beam.Row(x=1),
+ beam.Row(x=5),
+ beam.Row(x=9),
+ beam.Row(x=20),
+ beam.Row(x=10),
+ beam.Row(x=1)
+ ]
+
+ def test_with_default_trackers(self):
+ iqr = IQR()
+
+ scores = []
+ for row in IQRTest.input:
+ scores.append(iqr.score_one(row))
+ iqr.learn_one(row)
+
+ self.assertTrue(math.isnan(scores[0]))
+ self.assertEqual(
+ scores[1:], [0.0, 0.0, 3.0, 2.8, 0.125, 0.12903225806451613])
Review Comment:
Got it - that is gross, but kinda makes sense. Thanks for the explanation, lets leave this as is.
--
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: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [AnomalyDetection] Add detectors and some necessary univariate trackers. [beam]
Posted by "damccorm (via GitHub)" <gi...@apache.org>.
damccorm commented on code in PR #34232:
URL: https://github.com/apache/beam/pull/34232#discussion_r1987724727
##########
sdks/python/apache_beam/ml/anomaly/detectors/iqr_test.py:
##########
@@ -0,0 +1,52 @@
+#
+# 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
+import unittest
+
+import apache_beam as beam
+from apache_beam.ml.anomaly.detectors.iqr import IQR
+
+
+class IQRTest(unittest.TestCase):
+ input = [
+ beam.Row(x=1),
+ beam.Row(x=1),
+ beam.Row(x=5),
+ beam.Row(x=9),
+ beam.Row(x=20),
+ beam.Row(x=10),
+ beam.Row(x=1)
+ ]
+
+ def test_with_default_trackers(self):
+ iqr = IQR()
+
+ scores = []
+ for row in IQRTest.input:
+ scores.append(iqr.score_one(row))
+ iqr.learn_one(row)
+
+ self.assertTrue(math.isnan(scores[0]))
+ self.assertEqual(
+ scores[1:], [0.0, 0.0, 3.0, 2.8, 0.125, 0.12903225806451613])
Review Comment:
This applies for all the tests, but I am ok leaving as is if it seems more helpful to you.
##########
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|`
Review Comment:
Is this worth parameterizing? I lean towards no unless folks ask for it, but wanted to at least raise it. Seems like 0.6745 is an effective constant for normal data (1/1.4826 from https://arxiv.org/pdf/1704.07706), but others might be better for different distributions?
Asking people to provide the right parameters seems like a mistake since this seems quite hard, so I think I like it how you have it.
##########
sdks/python/apache_beam/ml/anomaly/detectors/iqr_test.py:
##########
@@ -0,0 +1,52 @@
+#
+# 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
+import unittest
+
+import apache_beam as beam
+from apache_beam.ml.anomaly.detectors.iqr import IQR
+
+
+class IQRTest(unittest.TestCase):
+ input = [
+ beam.Row(x=1),
+ beam.Row(x=1),
+ beam.Row(x=5),
+ beam.Row(x=9),
+ beam.Row(x=20),
+ beam.Row(x=10),
+ beam.Row(x=1)
+ ]
+
+ def test_with_default_trackers(self):
+ iqr = IQR()
+
+ scores = []
+ for row in IQRTest.input:
+ scores.append(iqr.score_one(row))
+ iqr.learn_one(row)
+
+ self.assertTrue(math.isnan(scores[0]))
+ self.assertEqual(
+ scores[1:], [0.0, 0.0, 3.0, 2.8, 0.125, 0.12903225806451613])
Review Comment:
```suggestion
scores, [0.0, 0.0, 0.0, 3.0, 2.8, 0.125, 0.12903225806451613])
```
Optional nit: I found it more confusing than helpful to not include the first element
##########
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:
Same applies elsewhere
##########
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:
Rather than just returning, should we be throwing here?
--
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: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [AnomalyDetection] Add detectors and some necessary univariate trackers. [beam]
Posted by "shunping (via GitHub)" <gi...@apache.org>.
shunping commented on code in PR #34232:
URL: https://github.com/apache/beam/pull/34232#discussion_r1987805477
##########
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:
Will that cause the entire transform to fail?
I am wondering whether it is possible for a user to provide a collections of `Row`s while most of them has one variable, but some has multiple. In this case, we can treat the rows with multiple variables ill-formatted input and simply ignore it.
--
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: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [AnomalyDetection] Add detectors and some necessary univariate trackers. [beam]
Posted by "shunping (via GitHub)" <gi...@apache.org>.
shunping commented on code in PR #34232:
URL: https://github.com/apache/beam/pull/34232#discussion_r1987874627
##########
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:
Done.
--
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: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Add detectors and some necessary univariate trackers. [beam]
Posted by "shunping (via GitHub)" <gi...@apache.org>.
shunping commented on PR #34232:
URL: https://github.com/apache/beam/pull/34232#issuecomment-2711088846
r: @damccorm
--
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: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [AnomalyDetection] Add detectors and some necessary univariate trackers. [beam]
Posted by "shunping (via GitHub)" <gi...@apache.org>.
shunping commented on code in PR #34232:
URL: https://github.com/apache/beam/pull/34232#discussion_r1987785615
##########
sdks/python/apache_beam/ml/anomaly/detectors/iqr_test.py:
##########
@@ -0,0 +1,52 @@
+#
+# 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
+import unittest
+
+import apache_beam as beam
+from apache_beam.ml.anomaly.detectors.iqr import IQR
+
+
+class IQRTest(unittest.TestCase):
+ input = [
+ beam.Row(x=1),
+ beam.Row(x=1),
+ beam.Row(x=5),
+ beam.Row(x=9),
+ beam.Row(x=20),
+ beam.Row(x=10),
+ beam.Row(x=1)
+ ]
+
+ def test_with_default_trackers(self):
+ iqr = IQR()
+
+ scores = []
+ for row in IQRTest.input:
+ scores.append(iqr.score_one(row))
+ iqr.learn_one(row)
+
+ self.assertTrue(math.isnan(scores[0]))
+ self.assertEqual(
+ scores[1:], [0.0, 0.0, 3.0, 2.8, 0.125, 0.12903225806451613])
Review Comment:
The first element is float('NaN') and equal sign does not work there.
```python
x = float('nan')
print(x == x) # Output: False
```
--
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: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [AnomalyDetection] Add detectors and some necessary univariate trackers. [beam]
Posted by "shunping (via GitHub)" <gi...@apache.org>.
shunping commented on code in PR #34232:
URL: https://github.com/apache/beam/pull/34232#discussion_r1987805477
##########
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:
Will that cause the entire transform to fail?
I am wondering whether it is possible for a user to provide a collections of `Row`s while most of them has one variable, but some has multiple. In this case, we can treat the rows with multiple variables ill-formatted input and simply ignore it.
But this can only happen if users do not provide a feature list when calling the anomaly detection transform...
--
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: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [AnomalyDetection] Add detectors and some necessary univariate trackers. [beam]
Posted by "damccorm (via GitHub)" <gi...@apache.org>.
damccorm commented on code in PR #34232:
URL: https://github.com/apache/beam/pull/34232#discussion_r1987836417
##########
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:
I would lean towards enforcing this the more I think about it, I can't really think of a case where this doesn't represent a broken pipeline configuration
--
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: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [AnomalyDetection] Add detectors and some necessary univariate trackers. [beam]
Posted by "shunping (via GitHub)" <gi...@apache.org>.
shunping commented on code in PR #34232:
URL: https://github.com/apache/beam/pull/34232#discussion_r1987795493
##########
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|`
Review Comment:
Agree. It is a commonly used constant that has theoretical meaning: https://en.wikipedia.org/wiki/Median_absolute_deviation#Derivation.
Also, instead of letting users set a different scale factor here, they can achieve the same effect by using a different threshold function to say `FixedThreshold(4)`. In this way, we can keep consistency with how we do thresholding on traditional Z-score.
--
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: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [AnomalyDetection] Add detectors and some necessary univariate trackers. [beam]
Posted by "shunping (via GitHub)" <gi...@apache.org>.
shunping commented on code in PR #34232:
URL: https://github.com/apache/beam/pull/34232#discussion_r1987795493
##########
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|`
Review Comment:
Agree. It is a commonly used constant that has theoretical meaning: https://en.wikipedia.org/wiki/Median_absolute_deviation#Derivation.
Also, instead of letting users set a different scale factor here, they can achieve the same effect by using a different threshold function (e.g. `FixedThreshold(4)`). In this way, we can keep consistency with how we do thresholding on traditional Z-score.
--
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: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [AnomalyDetection] Add detectors and some necessary univariate trackers. [beam]
Posted by "damccorm (via GitHub)" <gi...@apache.org>.
damccorm commented on code in PR #34232:
URL: https://github.com/apache/beam/pull/34232#discussion_r1987879689
##########
sdks/python/apache_beam/ml/anomaly/detectors/iqr_test.py:
##########
@@ -0,0 +1,52 @@
+#
+# 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
+import unittest
+
+import apache_beam as beam
+from apache_beam.ml.anomaly.detectors.iqr import IQR
+
+
+class IQRTest(unittest.TestCase):
+ input = [
+ beam.Row(x=1),
+ beam.Row(x=1),
+ beam.Row(x=5),
+ beam.Row(x=9),
+ beam.Row(x=20),
+ beam.Row(x=10),
+ beam.Row(x=1)
+ ]
+
+ def test_with_default_trackers(self):
+ iqr = IQR()
+
+ scores = []
+ for row in IQRTest.input:
+ scores.append(iqr.score_one(row))
+ iqr.learn_one(row)
+
+ self.assertTrue(math.isnan(scores[0]))
+ self.assertEqual(
+ scores[1:], [0.0, 0.0, 3.0, 2.8, 0.125, 0.12903225806451613])
Review Comment:
It might be a bit more friendly, though I'm not sure how big of a difference it will make. I think it will be rare for users to compare values like we do here, more likely they'd be doing comparisons like `math.isnan(x)` and `x is None`. But it might make testing a little more annoying.
I'd say lets scope it out of this PR, but if you want to flip the meaning back I am fine with that.
--
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: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [AnomalyDetection] Add detectors and some necessary univariate trackers. [beam]
Posted by "shunping (via GitHub)" <gi...@apache.org>.
shunping commented on code in PR #34232:
URL: https://github.com/apache/beam/pull/34232#discussion_r1987859585
##########
sdks/python/apache_beam/ml/anomaly/detectors/iqr_test.py:
##########
@@ -0,0 +1,52 @@
+#
+# 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
+import unittest
+
+import apache_beam as beam
+from apache_beam.ml.anomaly.detectors.iqr import IQR
+
+
+class IQRTest(unittest.TestCase):
+ input = [
+ beam.Row(x=1),
+ beam.Row(x=1),
+ beam.Row(x=5),
+ beam.Row(x=9),
+ beam.Row(x=20),
+ beam.Row(x=10),
+ beam.Row(x=1)
+ ]
+
+ def test_with_default_trackers(self):
+ iqr = IQR()
+
+ scores = []
+ for row in IQRTest.input:
+ scores.append(iqr.score_one(row))
+ iqr.learn_one(row)
+
+ self.assertTrue(math.isnan(scores[0]))
+ self.assertEqual(
+ scores[1:], [0.0, 0.0, 3.0, 2.8, 0.125, 0.12903225806451613])
Review Comment:
Now I begin to think if we should switch the meaning of 'NaN' and None given the property of 'NaN' in the equal function. Because in a decent pipeline, we should always see missing values (at least at the beginning of the model) and the error values will be very rare. For comparison purpose, 'None' value is more friendly than 'NaN'.
--
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: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [AnomalyDetection] Add detectors and some necessary univariate trackers. [beam]
Posted by "shunping (via GitHub)" <gi...@apache.org>.
shunping commented on code in PR #34232:
URL: https://github.com/apache/beam/pull/34232#discussion_r1987887503
##########
sdks/python/apache_beam/ml/anomaly/detectors/iqr_test.py:
##########
@@ -0,0 +1,52 @@
+#
+# 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
+import unittest
+
+import apache_beam as beam
+from apache_beam.ml.anomaly.detectors.iqr import IQR
+
+
+class IQRTest(unittest.TestCase):
+ input = [
+ beam.Row(x=1),
+ beam.Row(x=1),
+ beam.Row(x=5),
+ beam.Row(x=9),
+ beam.Row(x=20),
+ beam.Row(x=10),
+ beam.Row(x=1)
+ ]
+
+ def test_with_default_trackers(self):
+ iqr = IQR()
+
+ scores = []
+ for row in IQRTest.input:
+ scores.append(iqr.score_one(row))
+ iqr.learn_one(row)
+
+ self.assertTrue(math.isnan(scores[0]))
+ self.assertEqual(
+ scores[1:], [0.0, 0.0, 3.0, 2.8, 0.125, 0.12903225806451613])
Review Comment:
SG. It is definitely cumbersome to write a special equal method in our tests for these NaNs.
I will put down a PR after all these are merged. Then we can discuss if the change is worthwhile. Thanks!
--
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: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [AnomalyDetection] Add detectors and some necessary univariate trackers. [beam]
Posted by "damccorm (via GitHub)" <gi...@apache.org>.
damccorm commented on PR #34232:
URL: https://github.com/apache/beam/pull/34232#issuecomment-2711588419
Waiting on checks to complete, then will merge
--
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: github-unsubscribe@beam.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org