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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to