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/02/14 21:08:38 UTC
[PR] [AnomalyDetection] Add univariate trackers [beam]
shunping opened a new pull request, #33994:
URL: https://github.com/apache/beam/pull/33994
**Please** add a meaningful description for your change here
------------------------
Thank you for your contribution! Follow this checklist to help us incorporate your contribution quickly and easily:
- [ ] Mention the appropriate issue in your description (for example: `addresses #123`), if applicable. This will automatically add a link to the pull request in the issue. If you would like the issue to automatically close on merging the pull request, comment `fixes #<ISSUE NUMBER>` instead.
- [ ] Update `CHANGES.md` with noteworthy changes.
- [ ] If this contribution is large, please file an Apache [Individual Contributor License Agreement](https://www.apache.org/licenses/icla.pdf).
See the [Contributor Guide](https://beam.apache.org/contribute) for more tips on [how to make review process smoother](https://github.com/apache/beam/blob/master/CONTRIBUTING.md#make-the-reviewers-job-easier).
To check the build health, please visit [https://github.com/apache/beam/blob/master/.test-infra/BUILD_STATUS.md](https://github.com/apache/beam/blob/master/.test-infra/BUILD_STATUS.md)
GitHub Actions Tests Status (on master branch)
------------------------------------------------------------------------------------------------
[](https://github.com/apache/beam/actions?query=workflow%3A%22Build+python+source+distribution+and+wheels%22+branch%3Amaster+event%3Aschedule)
[](https://github.com/apache/beam/actions?query=workflow%3A%22Python+Tests%22+branch%3Amaster+event%3Aschedule)
[](https://github.com/apache/beam/actions?query=workflow%3A%22Java+Tests%22+branch%3Amaster+event%3Aschedule)
[](https://github.com/apache/beam/actions?query=workflow%3A%22Go+tests%22+branch%3Amaster+event%3Aschedule)
See [CI.md](https://github.com/apache/beam/blob/master/CI.md) for more information about GitHub Actions CI or the [workflows README](https://github.com/apache/beam/blob/master/.github/workflows/README.md) to see a list of phrases to trigger workflows.
--
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 univariate trackers [beam]
Posted by "shunping (via GitHub)" <gi...@apache.org>.
shunping commented on PR #33994:
URL: https://github.com/apache/beam/pull/33994#issuecomment-2660722148
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 univariate trackers [beam]
Posted by "shunping (via GitHub)" <gi...@apache.org>.
shunping commented on PR #33994:
URL: https://github.com/apache/beam/pull/33994#issuecomment-2660757928
Run Python_Dataframes PreCommit 3.10
--
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 univariate trackers [beam]
Posted by "damccorm (via GitHub)" <gi...@apache.org>.
damccorm commented on code in PR #33994:
URL: https://github.com/apache/beam/pull/33994#discussion_r1960051738
##########
sdks/python/apache_beam/ml/anomaly/univariate/quantile.py:
##########
@@ -0,0 +1,171 @@
+#
+# 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.
+#
+
+"""Trackers for calculating quantiles in windowed fashion.
+
+This module defines different types of quantile trackers that operate on
+windows of data. It includes:
+
+ * `SimpleSlidingQuantileTracker`: Calculates quantile using numpy in a sliding
+ window.
+ * `BufferedLandmarkQuantileTracker`: Sortedlist based quantile tracker in
+ landmark window mode.
+ * `BufferedSlidingQuantileTracker`: Sortedlist based quantile tracker in
+ sliding window mode.
+"""
+
+import math
+import typing
+import warnings
+
+import numpy as np
+from sortedcontainers import SortedList
+
+from apache_beam.ml.anomaly.univariate.base import WindowedTracker
+from apache_beam.ml.anomaly.univariate.base import WindowMode
+
+
+class QuantileTracker(WindowedTracker):
+ """Abstract base class for quantile trackers.
+
+ Currently, it does not add any specific functionality but provides a type
+ hierarchy for quantile trackers.
+ """
+ pass
+
+
+class SimpleSlidingQuantileTracker(QuantileTracker):
+ """Sliding window quantile tracker using NumPy.
+
+ This tracker uses NumPy's `nanquantile` function to calculate the specified
+ quantile of the values currently in the sliding window. It's a simple,
+ non-incremental approach.
+
+ Args:
+ window_size: The size of the sliding window.
+ q: The quantile to calculate, a float between 0 and 1 (inclusive).
+ """
+ def __init__(self, window_size, q):
+ super().__init__(window_mode=WindowMode.SLIDING, window_size=window_size)
+ assert 0 <= q <= 1, "quantile argument should be between 0 and 1"
+ self._q = q
Review Comment:
Nit: does it make sense to abstract this check out to the base class?
##########
sdks/python/apache_beam/ml/anomaly/univariate/mean.py:
##########
@@ -0,0 +1,141 @@
+#
+# 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.
+#
+
+"""Trackers for calculating mean in windowed fashion.
+
+This module defines different types of mean trackers that operate on windows
+of data. It includes:
+
+ * `SimpleSlidingMeanTracker`: Calculates mean using numpy in a sliding window.
+ * `IncLandmarkMeanTracker`: Incremental mean tracker in landmark window mode.
+ * `IncSlidingMeanTracker`: Incremental mean tracker in sliding window mode.
+"""
+
+import math
+import warnings
+
+import numpy as np
+
+from apache_beam.ml.anomaly.univariate.base import WindowedTracker
+from apache_beam.ml.anomaly.univariate.base import WindowMode
+
+
+class MeanTracker(WindowedTracker):
+ """Abstract base class for mean trackers.
+
+ Currently, it does not add any specific functionality but provides a type
+ hierarchy for mean trackers.
+ """
+ pass
+
+
+class SimpleSlidingMeanTracker(MeanTracker):
+ """Sliding window mean tracker that calculates mean using NumPy.
+
+ This tracker uses NumPy's `nanmean` function to calculate the mean of the
+ values currently in the sliding window. It's a simple, non-incremental
+ approach.
+
+ Args:
+ window_size: The size of the sliding window.
+ """
+ def __init__(self, window_size):
+ super().__init__(window_mode=WindowMode.SLIDING, window_size=window_size)
+
+ def get(self):
+ """Calculates and returns the mean of the current sliding window.
+
+ Returns:
+ float: The mean of the values in the current sliding window.
+ Returns NaN if the window is empty.
+ """
+ if len(self._queue) == 0:
+ return float('nan')
+
+ with warnings.catch_warnings(record=False):
+ warnings.simplefilter("ignore")
+ return np.nanmean(self._queue)
+
+
+class IncMeanTracker(MeanTracker):
+ """Base class for incremental mean trackers.
+
+ This class implements incremental calculation of the mean, which is more
+ efficient for streaming data as it updates the mean with each new data point
+ instead of recalculating from scratch.
+
+ Args:
+ window_mode: A `WindowMode` enum specifying whether the window is `LANDMARK`
+ or `SLIDING`.
+ **kwargs: Keyword arguments passed to the parent class constructor.
+ """
+ def __init__(self, window_mode, **kwargs):
+ super().__init__(window_mode=window_mode, **kwargs)
+ self._mean = 0
+
+ def push(self, x):
+ """Pushes a new value and updates the incremental mean.
+
+ Args:
+ x: The new value to be pushed.
+ """
+ if not math.isnan(x):
+ self._n += 1
+ delta = x - self._mean
+ else:
+ delta = 0
Review Comment:
Should we just early return here? If `x` is not a number, I'd expect us to just ignore it (or maybe even throw)
##########
sdks/python/apache_beam/ml/anomaly/univariate/base.py:
##########
@@ -0,0 +1,88 @@
+#
+# 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 abc
+from collections import deque
+from enum import Enum
+
+
+class BaseTracker(abc.ABC):
+ """Abstract base class for all univariate trackers."""
+ @abc.abstractmethod
+ def push(self, x):
+ """Push a new value to the tracker.
+
+ Args:
+ x: The value to be pushed.
+ """
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def get(self):
+ """Get the current tracking value.
+
+ Returns:
+ The current tracked value, the type of which depends on the specific
+ tracker implementation.
+ """
+ raise NotImplementedError()
+
+
+class WindowMode(Enum):
+ """Enum representing the window mode for windowed trackers."""
+ #: operating on all data points from the beginning.
Review Comment:
I think reading other things, the answer is yes, but it would be good to be explicit here.
##########
sdks/python/apache_beam/ml/anomaly/univariate/base.py:
##########
@@ -0,0 +1,88 @@
+#
+# 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 abc
+from collections import deque
+from enum import Enum
+
+
+class BaseTracker(abc.ABC):
+ """Abstract base class for all univariate trackers."""
+ @abc.abstractmethod
+ def push(self, x):
+ """Push a new value to the tracker.
+
+ Args:
+ x: The value to be pushed.
+ """
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def get(self):
+ """Get the current tracking value.
+
+ Returns:
+ The current tracked value, the type of which depends on the specific
+ tracker implementation.
+ """
+ raise NotImplementedError()
+
+
+class WindowMode(Enum):
+ """Enum representing the window mode for windowed trackers."""
+ #: operating on all data points from the beginning.
Review Comment:
I assume this doesn't mean we're buffering all data points we've ever seen, right?
--
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 univariate trackers [beam]
Posted by "shunping (via GitHub)" <gi...@apache.org>.
shunping commented on code in PR #33994:
URL: https://github.com/apache/beam/pull/33994#discussion_r1960249091
##########
sdks/python/apache_beam/ml/anomaly/univariate/mean.py:
##########
@@ -0,0 +1,141 @@
+#
+# 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.
+#
+
+"""Trackers for calculating mean in windowed fashion.
+
+This module defines different types of mean trackers that operate on windows
+of data. It includes:
+
+ * `SimpleSlidingMeanTracker`: Calculates mean using numpy in a sliding window.
+ * `IncLandmarkMeanTracker`: Incremental mean tracker in landmark window mode.
+ * `IncSlidingMeanTracker`: Incremental mean tracker in sliding window mode.
+"""
+
+import math
+import warnings
+
+import numpy as np
+
+from apache_beam.ml.anomaly.univariate.base import WindowedTracker
+from apache_beam.ml.anomaly.univariate.base import WindowMode
+
+
+class MeanTracker(WindowedTracker):
+ """Abstract base class for mean trackers.
+
+ Currently, it does not add any specific functionality but provides a type
+ hierarchy for mean trackers.
+ """
+ pass
+
+
+class SimpleSlidingMeanTracker(MeanTracker):
+ """Sliding window mean tracker that calculates mean using NumPy.
+
+ This tracker uses NumPy's `nanmean` function to calculate the mean of the
+ values currently in the sliding window. It's a simple, non-incremental
+ approach.
+
+ Args:
+ window_size: The size of the sliding window.
+ """
+ def __init__(self, window_size):
+ super().__init__(window_mode=WindowMode.SLIDING, window_size=window_size)
+
+ def get(self):
+ """Calculates and returns the mean of the current sliding window.
+
+ Returns:
+ float: The mean of the values in the current sliding window.
+ Returns NaN if the window is empty.
+ """
+ if len(self._queue) == 0:
+ return float('nan')
+
+ with warnings.catch_warnings(record=False):
+ warnings.simplefilter("ignore")
+ return np.nanmean(self._queue)
+
+
+class IncMeanTracker(MeanTracker):
+ """Base class for incremental mean trackers.
+
+ This class implements incremental calculation of the mean, which is more
+ efficient for streaming data as it updates the mean with each new data point
+ instead of recalculating from scratch.
+
+ Args:
+ window_mode: A `WindowMode` enum specifying whether the window is `LANDMARK`
+ or `SLIDING`.
+ **kwargs: Keyword arguments passed to the parent class constructor.
+ """
+ def __init__(self, window_mode, **kwargs):
+ super().__init__(window_mode=window_mode, **kwargs)
+ self._mean = 0
+
+ def push(self, x):
+ """Pushes a new value and updates the incremental mean.
+
+ Args:
+ x: The new value to be pushed.
+ """
+ if not math.isnan(x):
+ self._n += 1
+ delta = x - self._mean
+ else:
+ delta = 0
Review Comment:
If we early return here (either discarding or ignoring), the result could have a subtle difference.
Let's say there is a variable called X and it has 10% of missing values. For every second, we receive a new X. If we want to compute the rolling mean for X in a sliding window of a minute (window_size = 60) , the current implementation will yield the correct result, because missing values will still be pushed in the sliding window.
On the other hand, if we ignore or discard these NaN, we will end up with a window of (non-NaN) data points that may include 6 (10%*60) data points on average that is outside the predefined one minute window.
Moreover, if users really want to ignore or discard or even more sophisticatedly, impute NaNs, they can easily prepend a preprocessing map step to the current implementation to handle them. The opposite direction is not easy, because if those NaNs are discarded or ignored in the first place, they cannot be recovered.
--
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 univariate trackers [beam]
Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #33994:
URL: https://github.com/apache/beam/pull/33994#issuecomment-2660722566
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 univariate trackers [beam]
Posted by "shunping (via GitHub)" <gi...@apache.org>.
shunping commented on PR #33994:
URL: https://github.com/apache/beam/pull/33994#issuecomment-2660757819
Run Python_ML PreCommit 3.10
--
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 univariate trackers [beam]
Posted by "damccorm (via GitHub)" <gi...@apache.org>.
damccorm merged PR #33994:
URL: https://github.com/apache/beam/pull/33994
--
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 univariate trackers [beam]
Posted by "shunping (via GitHub)" <gi...@apache.org>.
shunping commented on code in PR #33994:
URL: https://github.com/apache/beam/pull/33994#discussion_r1960191745
##########
sdks/python/apache_beam/ml/anomaly/univariate/base.py:
##########
@@ -0,0 +1,88 @@
+#
+# 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 abc
+from collections import deque
+from enum import Enum
+
+
+class BaseTracker(abc.ABC):
+ """Abstract base class for all univariate trackers."""
+ @abc.abstractmethod
+ def push(self, x):
+ """Push a new value to the tracker.
+
+ Args:
+ x: The value to be pushed.
+ """
+ raise NotImplementedError()
+
+ @abc.abstractmethod
+ def get(self):
+ """Get the current tracking value.
+
+ Returns:
+ The current tracked value, the type of which depends on the specific
+ tracker implementation.
+ """
+ raise NotImplementedError()
+
+
+class WindowMode(Enum):
+ """Enum representing the window mode for windowed trackers."""
+ #: operating on all data points from the beginning.
Review Comment:
It really depends on algorithms and what statistics we talk about here.
For example, we don't need to store all data points to compute the mean in a landmark window: an naive way is to only store the number of data points and their sum.
However, for quantile, we will have to store all the data to compute the exact answer. There are some approximate algorithms for quantile that does not need to store all data points, but they are outside the scope of this current implementation.
That's why in `WindowTracer`, we don't explicitly declare a list to store all data points, because it may or may not need all the data points.
--
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 univariate trackers [beam]
Posted by "damccorm (via GitHub)" <gi...@apache.org>.
damccorm commented on code in PR #33994:
URL: https://github.com/apache/beam/pull/33994#discussion_r1960470739
##########
sdks/python/apache_beam/ml/anomaly/univariate/mean.py:
##########
@@ -0,0 +1,141 @@
+#
+# 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.
+#
+
+"""Trackers for calculating mean in windowed fashion.
+
+This module defines different types of mean trackers that operate on windows
+of data. It includes:
+
+ * `SimpleSlidingMeanTracker`: Calculates mean using numpy in a sliding window.
+ * `IncLandmarkMeanTracker`: Incremental mean tracker in landmark window mode.
+ * `IncSlidingMeanTracker`: Incremental mean tracker in sliding window mode.
+"""
+
+import math
+import warnings
+
+import numpy as np
+
+from apache_beam.ml.anomaly.univariate.base import WindowedTracker
+from apache_beam.ml.anomaly.univariate.base import WindowMode
+
+
+class MeanTracker(WindowedTracker):
+ """Abstract base class for mean trackers.
+
+ Currently, it does not add any specific functionality but provides a type
+ hierarchy for mean trackers.
+ """
+ pass
+
+
+class SimpleSlidingMeanTracker(MeanTracker):
+ """Sliding window mean tracker that calculates mean using NumPy.
+
+ This tracker uses NumPy's `nanmean` function to calculate the mean of the
+ values currently in the sliding window. It's a simple, non-incremental
+ approach.
+
+ Args:
+ window_size: The size of the sliding window.
+ """
+ def __init__(self, window_size):
+ super().__init__(window_mode=WindowMode.SLIDING, window_size=window_size)
+
+ def get(self):
+ """Calculates and returns the mean of the current sliding window.
+
+ Returns:
+ float: The mean of the values in the current sliding window.
+ Returns NaN if the window is empty.
+ """
+ if len(self._queue) == 0:
+ return float('nan')
+
+ with warnings.catch_warnings(record=False):
+ warnings.simplefilter("ignore")
+ return np.nanmean(self._queue)
+
+
+class IncMeanTracker(MeanTracker):
+ """Base class for incremental mean trackers.
+
+ This class implements incremental calculation of the mean, which is more
+ efficient for streaming data as it updates the mean with each new data point
+ instead of recalculating from scratch.
+
+ Args:
+ window_mode: A `WindowMode` enum specifying whether the window is `LANDMARK`
+ or `SLIDING`.
+ **kwargs: Keyword arguments passed to the parent class constructor.
+ """
+ def __init__(self, window_mode, **kwargs):
+ super().__init__(window_mode=window_mode, **kwargs)
+ self._mean = 0
+
+ def push(self, x):
+ """Pushes a new value and updates the incremental mean.
+
+ Args:
+ x: The new value to be pushed.
+ """
+ if not math.isnan(x):
+ self._n += 1
+ delta = x - self._mean
+ else:
+ delta = 0
Review Comment:
> Moreover, if users really want to ignore or discard or even more sophisticatedly, impute NaNs, they can easily prepend a preprocessing map step to the current implementation to handle them. The opposite direction is not easy, because the information loss from early returns cannot be reversed.
This is a good point. I agree, 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 univariate trackers [beam]
Posted by "shunping (via GitHub)" <gi...@apache.org>.
shunping commented on code in PR #33994:
URL: https://github.com/apache/beam/pull/33994#discussion_r1960249091
##########
sdks/python/apache_beam/ml/anomaly/univariate/mean.py:
##########
@@ -0,0 +1,141 @@
+#
+# 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.
+#
+
+"""Trackers for calculating mean in windowed fashion.
+
+This module defines different types of mean trackers that operate on windows
+of data. It includes:
+
+ * `SimpleSlidingMeanTracker`: Calculates mean using numpy in a sliding window.
+ * `IncLandmarkMeanTracker`: Incremental mean tracker in landmark window mode.
+ * `IncSlidingMeanTracker`: Incremental mean tracker in sliding window mode.
+"""
+
+import math
+import warnings
+
+import numpy as np
+
+from apache_beam.ml.anomaly.univariate.base import WindowedTracker
+from apache_beam.ml.anomaly.univariate.base import WindowMode
+
+
+class MeanTracker(WindowedTracker):
+ """Abstract base class for mean trackers.
+
+ Currently, it does not add any specific functionality but provides a type
+ hierarchy for mean trackers.
+ """
+ pass
+
+
+class SimpleSlidingMeanTracker(MeanTracker):
+ """Sliding window mean tracker that calculates mean using NumPy.
+
+ This tracker uses NumPy's `nanmean` function to calculate the mean of the
+ values currently in the sliding window. It's a simple, non-incremental
+ approach.
+
+ Args:
+ window_size: The size of the sliding window.
+ """
+ def __init__(self, window_size):
+ super().__init__(window_mode=WindowMode.SLIDING, window_size=window_size)
+
+ def get(self):
+ """Calculates and returns the mean of the current sliding window.
+
+ Returns:
+ float: The mean of the values in the current sliding window.
+ Returns NaN if the window is empty.
+ """
+ if len(self._queue) == 0:
+ return float('nan')
+
+ with warnings.catch_warnings(record=False):
+ warnings.simplefilter("ignore")
+ return np.nanmean(self._queue)
+
+
+class IncMeanTracker(MeanTracker):
+ """Base class for incremental mean trackers.
+
+ This class implements incremental calculation of the mean, which is more
+ efficient for streaming data as it updates the mean with each new data point
+ instead of recalculating from scratch.
+
+ Args:
+ window_mode: A `WindowMode` enum specifying whether the window is `LANDMARK`
+ or `SLIDING`.
+ **kwargs: Keyword arguments passed to the parent class constructor.
+ """
+ def __init__(self, window_mode, **kwargs):
+ super().__init__(window_mode=window_mode, **kwargs)
+ self._mean = 0
+
+ def push(self, x):
+ """Pushes a new value and updates the incremental mean.
+
+ Args:
+ x: The new value to be pushed.
+ """
+ if not math.isnan(x):
+ self._n += 1
+ delta = x - self._mean
+ else:
+ delta = 0
Review Comment:
If we early return here (either discarding or ignoring), the result could have a subtle difference.
Let's say there is a variable called X and it has 10% of missing values. For every second, we receive a new X. If we want to compute the rolling mean for X in a sliding window of a minute (window_size = 60) , the current implementation will yield the correct result, because missing values will still be pushed in the sliding window.
On the other hand, if we ignore or discard these NaN, we will end up with a window of (non-NaN) data points that may include 6 (10%*60) data points on average that is outside the predefined one minute window.
Moreover, if users really want to ignore or discard or even more sophisticatedly, impute NaNs, they can easily prepend a preprocessing map step to the current implementation to handle them. The opposite direction is not easy, because the information loss from early returns cannot be reversed.
--
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 univariate trackers [beam]
Posted by "shunping (via GitHub)" <gi...@apache.org>.
shunping commented on code in PR #33994:
URL: https://github.com/apache/beam/pull/33994#discussion_r1960416493
##########
sdks/python/apache_beam/ml/anomaly/univariate/quantile.py:
##########
@@ -0,0 +1,171 @@
+#
+# 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.
+#
+
+"""Trackers for calculating quantiles in windowed fashion.
+
+This module defines different types of quantile trackers that operate on
+windows of data. It includes:
+
+ * `SimpleSlidingQuantileTracker`: Calculates quantile using numpy in a sliding
+ window.
+ * `BufferedLandmarkQuantileTracker`: Sortedlist based quantile tracker in
+ landmark window mode.
+ * `BufferedSlidingQuantileTracker`: Sortedlist based quantile tracker in
+ sliding window mode.
+"""
+
+import math
+import typing
+import warnings
+
+import numpy as np
+from sortedcontainers import SortedList
+
+from apache_beam.ml.anomaly.univariate.base import WindowedTracker
+from apache_beam.ml.anomaly.univariate.base import WindowMode
+
+
+class QuantileTracker(WindowedTracker):
+ """Abstract base class for quantile trackers.
+
+ Currently, it does not add any specific functionality but provides a type
+ hierarchy for quantile trackers.
+ """
+ pass
+
+
+class SimpleSlidingQuantileTracker(QuantileTracker):
+ """Sliding window quantile tracker using NumPy.
+
+ This tracker uses NumPy's `nanquantile` function to calculate the specified
+ quantile of the values currently in the sliding window. It's a simple,
+ non-incremental approach.
+
+ Args:
+ window_size: The size of the sliding window.
+ q: The quantile to calculate, a float between 0 and 1 (inclusive).
+ """
+ def __init__(self, window_size, q):
+ super().__init__(window_mode=WindowMode.SLIDING, window_size=window_size)
+ assert 0 <= q <= 1, "quantile argument should be between 0 and 1"
+ self._q = q
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