shunping commented on code in PR #34234:
URL: https://github.com/apache/beam/pull/34234#discussion_r1989750811


##########
sdks/python/apache_beam/ml/anomaly/transforms.py:
##########
@@ -0,0 +1,381 @@
+#
+# 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 typing
+import uuid
+from typing import Any
+from typing import Callable
+from typing import Iterable
+from typing import Tuple
+from typing import TypeVar
+
+import apache_beam as beam
+from apache_beam.coders import DillCoder
+from apache_beam.ml.anomaly import aggregations
+from apache_beam.ml.anomaly.base import AggregationFn
+from apache_beam.ml.anomaly.base import AnomalyDetector
+from apache_beam.ml.anomaly.base import AnomalyPrediction
+from apache_beam.ml.anomaly.base import AnomalyResult
+from apache_beam.ml.anomaly.base import EnsembleAnomalyDetector
+from apache_beam.ml.anomaly.specifiable import Spec
+from apache_beam.ml.anomaly.specifiable import Specifiable
+from apache_beam.ml.anomaly.thresholds import StatefulThresholdDoFn
+from apache_beam.ml.anomaly.thresholds import StatelessThresholdDoFn
+from apache_beam.transforms.userstate import ReadModifyWriteRuntimeState
+from apache_beam.transforms.userstate import ReadModifyWriteStateSpec
+
+KeyT = TypeVar('KeyT')
+TempKeyT = TypeVar('TempKeyT', bound=int)
+InputT = Tuple[KeyT, beam.Row]
+KeyedInputT = Tuple[KeyT, Tuple[TempKeyT, beam.Row]]
+KeyedOutputT = Tuple[KeyT, Tuple[TempKeyT, AnomalyResult]]
+OutputT = Tuple[KeyT, AnomalyResult]
+
+
+class _ScoreAndLearnDoFn(beam.DoFn):
+  """Scores and learns from incoming data using an anomaly detection model.
+
+  This DoFn applies an anomaly detection model to score incoming data and
+  then updates the model with the same data. It maintains the model state
+  using Beam's state management.
+  """
+  MODEL_STATE_INDEX = ReadModifyWriteStateSpec('saved_model', DillCoder())
+
+  def __init__(self, detector_spec: Spec):
+    self._detector_spec = detector_spec
+    self._detector_spec.config["_run_init"] = True
+
+  def score_and_learn(self, data):
+    """Scores and learns from a single data point.
+
+    Args:
+      data: A `beam.Row` representing the input data point.
+
+    Returns:
+      float: The anomaly score predicted by the model.
+    """
+    assert self._underlying
+    if self._underlying._features is not None:
+      x = beam.Row(**{f: getattr(data, f) for f in self._underlying._features})
+    else:
+      x = beam.Row(**data._asdict())
+
+    # score the incoming data using the existing model
+    y_pred = self._underlying.score_one(x)
+
+    # then update the model with the same data
+    self._underlying.learn_one(x)
+
+    return y_pred
+
+  def process(
+      self,
+      element: KeyedInputT,
+      model_state=beam.DoFn.StateParam(MODEL_STATE_INDEX),
+      **kwargs) -> Iterable[KeyedOutputT]:
+
+    model_state = typing.cast(ReadModifyWriteRuntimeState, model_state)
+    k1, (k2, data) = element
+    self._underlying: AnomalyDetector = model_state.read()
+    if self._underlying is None:
+      self._underlying = typing.cast(
+          AnomalyDetector, Specifiable.from_spec(self._detector_spec))
+
+    yield k1, (k2,
+               AnomalyResult(
+                   example=data,
+                   predictions=[AnomalyPrediction(
+                       model_id=self._underlying._model_id,
+                       score=self.score_and_learn(data))]))
+
+    model_state.write(self._underlying)

Review Comment:
   Right, though I think in the implementation states will be cached and they 
are not committed to the backend per element.



-- 
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