damccorm commented on code in PR #34218: URL: https://github.com/apache/beam/pull/34218#discussion_r1987520868
########## sdks/python/apache_beam/ml/anomaly/thresholds.py: ########## @@ -17,172 +17,13 @@ from __future__ import annotations -import dataclasses import math -from typing import Any -from typing import Iterable from typing import Optional -from typing import Tuple -from typing import Union -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 = None - - 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: Any = Specifiable.from_spec(threshold_fn_spec) - assert not self._threshold_fn.is_stateful, \ - "This DoFn can only take stateless function as threshold_fn" - - def process(self, element: Tuple[Any, Tuple[Any, AnomalyResult]], - **kwargs) -> Iterable[Tuple[Any, Tuple[Any, AnomalyResult]]]: - """Processes a batch of anomaly results using a stateless ThresholdFn. - - Args: - element (Tuple[Any, Tuple[Any, AnomalyResult]]): A tuple representing - an element in the Beam pipeline. It is expected to be in the format - `(key1, (key2, AnomalyResult))`, where key1 is the original input key, - and key2 is a disambiguating key for distinct data points. - **kwargs: Additional keyword arguments passed to the `process` method - in Beam DoFns. - - Yields: - Iterable[Tuple[Any, Tuple[Any, AnomalyResult]]]: An iterable containing - a single output element with the same structure as the input, but with - the `AnomalyResult` having updated prediction labels based on the - stateless `ThresholdFn`. - """ - k1, (k2, result) = element - yield k1, (k2, self._apply_threshold_to_predictions(result)) - - -class StatefulThresholdDoFn(BaseThresholdDoFn): Review Comment: Is there a reason to move this out of thresholds.py? It seems more natural here. If it is just a refactor, could we split that into a separate PR? This one is already quite large -- 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]
