damccorm commented on code in PR #34018: URL: https://github.com/apache/beam/pull/34018#discussion_r1962302480
########## sdks/python/apache_beam/ml/anomaly/thresholds.py: ########## @@ -0,0 +1,319 @@ +# +# 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. +# + +from __future__ import annotations + +import dataclasses +from typing import Any +from typing import Iterable +from typing import Optional +from typing import Tuple +from typing import Union +from typing import cast + +import apache_beam as beam +from apache_beam.coders import DillCoder +from apache_beam.ml.anomaly.base import AnomalyResult +from apache_beam.ml.anomaly.base import ThresholdFn +from apache_beam.ml.anomaly.specifiable import Spec +from apache_beam.ml.anomaly.specifiable import Specifiable +from apache_beam.ml.anomaly.specifiable import specifiable +from apache_beam.ml.anomaly.univariate.quantile import BufferedSlidingQuantileTracker # pylint: disable=line-too-long +from apache_beam.ml.anomaly.univariate.quantile import QuantileTracker +from apache_beam.transforms.userstate import ReadModifyWriteRuntimeState +from apache_beam.transforms.userstate import ReadModifyWriteStateSpec + + +class BaseThresholdDoFn(beam.DoFn): + """Applies a ThresholdFn to anomaly detection results. + + This abstract base class defines the structure for DoFns that use a + `ThresholdFn` to convert anomaly scores into anomaly labels (e.g., normal + or outlier). It handles the core logic of applying the threshold function + and updating the prediction labels within `AnomalyResult` objects. + + Args: + threshold_fn_spec (Spec): Specification defining the `ThresholdFn` to be + used. + """ + def __init__(self, threshold_fn_spec: Spec): + self._threshold_fn_spec = threshold_fn_spec + self._threshold_fn: ThresholdFn + + def _apply_threshold_to_predictions( + self, result: AnomalyResult) -> AnomalyResult: + """Updates the prediction labels in an AnomalyResult using the ThresholdFn. + + Args: + result (AnomalyResult): The input `AnomalyResult` containing anomaly + scores. + + Returns: + AnomalyResult: A new `AnomalyResult` with updated prediction labels + and threshold values. + """ + predictions = [ + dataclasses.replace( + p, + label=self._threshold_fn.apply(p.score), + threshold=self._threshold_fn.threshold) for p in result.predictions + ] + return dataclasses.replace(result, predictions=predictions) + + +class StatelessThresholdDoFn(BaseThresholdDoFn): + """Applies a stateless ThresholdFn to anomaly detection results. + + This DoFn is designed for stateless `ThresholdFn` implementations. It + initializes the `ThresholdFn` once during setup and applies it to each + incoming element without maintaining any state across elements. + + Args: + threshold_fn_spec (Spec): Specification defining the `ThresholdFn` to be + used. + + Raises: + AssertionError: If the provided `threshold_fn_spec` leads to the + creation of a stateful `ThresholdFn`. + """ + def __init__(self, threshold_fn_spec: Spec): + threshold_fn_spec.config["_run_init"] = True + self._threshold_fn = cast( + ThresholdFn, Specifiable.from_spec(threshold_fn_spec)) Review Comment: Why do we need this cast? Is this a requirement for instantiating specs? ########## sdks/python/apache_beam/ml/anomaly/aggregations.py: ########## @@ -0,0 +1,263 @@ +# +# 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 collections +import math +import statistics +from typing import Callable +from typing import Iterable + +from apache_beam.ml.anomaly.base import AggregationFn +from apache_beam.ml.anomaly.base import AnomalyPrediction +from apache_beam.ml.anomaly.specifiable import specifiable + + +class LabelAggregation(AggregationFn): + """Aggregates anomaly predictions based on their labels. + + This is an abstract base class for `AggregationFn`s that combine multiple + `AnomalyPrediction` objects into a single `AnomalyPrediction` based on + the labels of the input predictions. + + Args: + agg_func (Callable[[Iterable[int]], int]): A function that aggregates + a collection of anomaly labels (integers) into a single label. + include_history (bool): If True, include the input predictions in the + `agg_history` of the output. Defaults to False. + """ + def __init__( + self, + agg_func: Callable[[Iterable[int]], int], + include_history: bool = False): + self._agg = agg_func + self._include_history = include_history + self._agg_model_id = None Review Comment: It seems like this is always None? What is the purpose of this variable? ########## sdks/python/apache_beam/ml/anomaly/aggregations.py: ########## @@ -0,0 +1,263 @@ +# +# 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 collections +import math +import statistics +from typing import Callable +from typing import Iterable + +from apache_beam.ml.anomaly.base import AggregationFn +from apache_beam.ml.anomaly.base import AnomalyPrediction +from apache_beam.ml.anomaly.specifiable import specifiable + + +class LabelAggregation(AggregationFn): + """Aggregates anomaly predictions based on their labels. + + This is an abstract base class for `AggregationFn`s that combine multiple + `AnomalyPrediction` objects into a single `AnomalyPrediction` based on + the labels of the input predictions. + + Args: + agg_func (Callable[[Iterable[int]], int]): A function that aggregates + a collection of anomaly labels (integers) into a single label. + include_history (bool): If True, include the input predictions in the + `agg_history` of the output. Defaults to False. Review Comment: Is history a standard term here or something we came up with? It seems a little odd to me if its not already a standard, to me it implies including historical predictions (e.g. what did I predict for the last data point). ########## sdks/python/apache_beam/ml/anomaly/aggregations.py: ########## @@ -0,0 +1,263 @@ +# +# 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 collections +import math +import statistics +from typing import Callable +from typing import Iterable + +from apache_beam.ml.anomaly.base import AggregationFn +from apache_beam.ml.anomaly.base import AnomalyPrediction +from apache_beam.ml.anomaly.specifiable import specifiable + + +class LabelAggregation(AggregationFn): + """Aggregates anomaly predictions based on their labels. + + This is an abstract base class for `AggregationFn`s that combine multiple + `AnomalyPrediction` objects into a single `AnomalyPrediction` based on + the labels of the input predictions. + + Args: + agg_func (Callable[[Iterable[int]], int]): A function that aggregates + a collection of anomaly labels (integers) into a single label. + include_history (bool): If True, include the input predictions in the + `agg_history` of the output. Defaults to False. + """ + def __init__( + self, + agg_func: Callable[[Iterable[int]], int], + include_history: bool = False): + self._agg = agg_func + self._include_history = include_history + self._agg_model_id = None + + def apply( + self, predictions: Iterable[AnomalyPrediction]) -> AnomalyPrediction: + """Applies the label aggregation function to a list of predictions. + + Args: + predictions (Iterable[AnomalyPrediction]): A collection of + `AnomalyPrediction` objects to be aggregated. + + Returns: + AnomalyPrediction: A single `AnomalyPrediction` object with the + aggregated label. + """ + labels = [ + prediction.label for prediction in predictions + if prediction.label is not None + ] + + if len(labels) == 0: + return AnomalyPrediction(model_id=self._agg_model_id) + + label = self._agg(labels) + + history = list(predictions) if self._include_history else None + + return AnomalyPrediction( + model_id=self._agg_model_id, label=label, agg_history=history) + + +class ScoreAggregation(AggregationFn): + """Aggregates anomaly predictions based on their scores. + + This is an abstract base class for `AggregationFn`s that combine multiple + `AnomalyPrediction` objects into a single `AnomalyPrediction` based on + the scores of the input predictions. + + Args: + agg_func (Callable[[Iterable[float]], float]): A function that aggregates + a collection of anomaly scores (floats) into a single score. + include_history (bool): If True, include the input predictions in the + `agg_history` of the output. Defaults to False. + """ + def __init__( + self, + agg_func: Callable[[Iterable[float]], float], + include_history: bool = False): + self._agg = agg_func + self._include_history = include_history + self._agg_model_id = None + + def apply( + self, predictions: Iterable[AnomalyPrediction]) -> AnomalyPrediction: + """Applies the score aggregation function to a list of predictions. + + Args: + predictions (Iterable[AnomalyPrediction]): A collection of + `AnomalyPrediction` objects to be aggregated. + + Returns: + AnomalyPrediction: A single `AnomalyPrediction` object with the + aggregated score. + """ + scores = [ + prediction.score for prediction in predictions + if prediction.score is not None and not math.isnan(prediction.score) Review Comment: I think it might make sense to define a score for predictions which have no score, but have a label (and vice versa). Or maybe we can just throw? I guess this relates to my above question - when would we expect this scoreless condition to happen. ########## sdks/python/apache_beam/ml/anomaly/aggregations.py: ########## @@ -0,0 +1,263 @@ +# +# 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 collections +import math +import statistics +from typing import Callable +from typing import Iterable + +from apache_beam.ml.anomaly.base import AggregationFn +from apache_beam.ml.anomaly.base import AnomalyPrediction +from apache_beam.ml.anomaly.specifiable import specifiable + + +class LabelAggregation(AggregationFn): + """Aggregates anomaly predictions based on their labels. + + This is an abstract base class for `AggregationFn`s that combine multiple + `AnomalyPrediction` objects into a single `AnomalyPrediction` based on + the labels of the input predictions. + + Args: + agg_func (Callable[[Iterable[int]], int]): A function that aggregates + a collection of anomaly labels (integers) into a single label. + include_history (bool): If True, include the input predictions in the + `agg_history` of the output. Defaults to False. + """ + def __init__( + self, + agg_func: Callable[[Iterable[int]], int], + include_history: bool = False): + self._agg = agg_func + self._include_history = include_history + self._agg_model_id = None + + def apply( + self, predictions: Iterable[AnomalyPrediction]) -> AnomalyPrediction: + """Applies the label aggregation function to a list of predictions. + + Args: + predictions (Iterable[AnomalyPrediction]): A collection of + `AnomalyPrediction` objects to be aggregated. + + Returns: + AnomalyPrediction: A single `AnomalyPrediction` object with the + aggregated label. + """ + labels = [ + prediction.label for prediction in predictions + if prediction.label is not None + ] + + if len(labels) == 0: Review Comment: I'm having a hard time reasoning about this - does this basically mean all subpredictors were inconclusive? ########## sdks/python/apache_beam/ml/anomaly/aggregations.py: ########## @@ -0,0 +1,263 @@ +# +# 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 collections +import math +import statistics +from typing import Callable +from typing import Iterable + +from apache_beam.ml.anomaly.base import AggregationFn +from apache_beam.ml.anomaly.base import AnomalyPrediction +from apache_beam.ml.anomaly.specifiable import specifiable + + +class LabelAggregation(AggregationFn): + """Aggregates anomaly predictions based on their labels. + + This is an abstract base class for `AggregationFn`s that combine multiple + `AnomalyPrediction` objects into a single `AnomalyPrediction` based on + the labels of the input predictions. + + Args: + agg_func (Callable[[Iterable[int]], int]): A function that aggregates + a collection of anomaly labels (integers) into a single label. + include_history (bool): If True, include the input predictions in the + `agg_history` of the output. Defaults to False. + """ + def __init__( + self, + agg_func: Callable[[Iterable[int]], int], + include_history: bool = False): + self._agg = agg_func + self._include_history = include_history + self._agg_model_id = None + + def apply( + self, predictions: Iterable[AnomalyPrediction]) -> AnomalyPrediction: + """Applies the label aggregation function to a list of predictions. + + Args: + predictions (Iterable[AnomalyPrediction]): A collection of + `AnomalyPrediction` objects to be aggregated. + + Returns: + AnomalyPrediction: A single `AnomalyPrediction` object with the + aggregated label. + """ + labels = [ + prediction.label for prediction in predictions + if prediction.label is not None + ] + + if len(labels) == 0: Review Comment: I wonder if inconclusive/None is still a useful input to the aggregation function - I could see someone wanting to treat inconclusive as an anomaly. -- 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]
