-
Notifications
You must be signed in to change notification settings - Fork 4.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[AnomalyDetection] Add univariate trackers #33994
Merged
Merged
Changes from 4 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
46945de
Change prediction in AnomalyResult to predictions which is now an ite…
shunping 510754e
Add mean, stdev and quantile trackers with tests.
shunping b2ffec8
Add docstrings
shunping 09d4cdc
Fix lints
shunping de94168
Make trackers specifiable.
shunping 5b3e643
Adjust class structures in trackers. Minor fix per feedback.
shunping File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
# | ||
# 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. | ||
# |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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. | ||
LANDMARK = 1 | ||
#: operating on a fixed-size sliding window of recent data points. | ||
SLIDING = 2 | ||
|
||
|
||
class WindowedTracker(BaseTracker): | ||
"""Abstract base class for trackers that operate on a data window. | ||
|
||
This class provides a foundation for trackers that maintain a window of data, | ||
either as a landmark window or a sliding window. It provides basic push and | ||
pop operations. | ||
|
||
Args: | ||
window_mode: A `WindowMode` enum specifying whether the window is `LANDMARK` | ||
or `SLIDING`. | ||
**kwargs: Keyword arguments. | ||
For `SLIDING` window mode, `window_size` can be specified to set the | ||
maximum size of the sliding window. Defaults to 100. | ||
""" | ||
def __init__(self, window_mode, **kwargs): | ||
if window_mode == WindowMode.SLIDING: | ||
self._window_size = kwargs.get("window_size", 100) | ||
self._queue = deque(maxlen=self._window_size) | ||
self._n = 0 | ||
self._window_mode = window_mode | ||
|
||
def push(self, x): | ||
"""Adds a new value to the data window. | ||
|
||
Args: | ||
x: The value to be added to the window. | ||
""" | ||
self._queue.append(x) | ||
|
||
def pop(self): | ||
"""Removes and returns the oldest value from the data window (FIFO). | ||
|
||
Returns: | ||
The oldest value from the window. | ||
""" | ||
return self._queue.popleft() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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 | ||
damccorm marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
if self._window_mode == WindowMode.SLIDING: | ||
if len(self._queue) >= self._window_size and \ | ||
not math.isnan(old_x := self.pop()): | ||
self._n -= 1 | ||
delta += (self._mean - old_x) | ||
|
||
super().push(x) | ||
|
||
if self._n > 0: | ||
self._mean += delta / self._n | ||
else: | ||
self._mean = 0 | ||
|
||
def get(self): | ||
"""Returns the current incremental mean. | ||
|
||
Returns: | ||
float: The current incremental mean value. | ||
Returns NaN if no valid (non-NaN) values have been pushed. | ||
""" | ||
if self._n < 1: | ||
# keep it consistent with numpy | ||
return float("nan") | ||
return self._mean | ||
|
||
|
||
class IncLandmarkMeanTracker(IncMeanTracker): | ||
"""Landmark window mean tracker using incremental calculation.""" | ||
def __init__(self): | ||
super().__init__(window_mode=WindowMode.LANDMARK) | ||
|
||
|
||
class IncSlidingMeanTracker(IncMeanTracker): | ||
"""Sliding window mean tracker using incremental calculation. | ||
|
||
Args: | ||
window_size: The size of the sliding window. | ||
""" | ||
def __init__(self, window_size): | ||
super().__init__(window_mode=WindowMode.SLIDING, window_size=window_size) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I assume this doesn't mean we're buffering all data points we've ever seen, right?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think reading other things, the answer is yes, but it would be good to be explicit here.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.