You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@beam.apache.org by "jaxpr (via GitHub)" <gi...@apache.org> on 2023/03/13 15:19:29 UTC

[GitHub] [beam] jaxpr opened a new pull request, #25823: Featue/online clustering

jaxpr opened a new pull request, #25823:
URL: https://github.com/apache/beam/pull/25823

   Implementation of the K-Means clustering transform.
   
   ------------------------
   
   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://beam.apache.org/contribute/get-started-contributing/#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)
   ------------------------------------------------------------------------------------------------
   [![Build python source distribution and wheels](https://github.com/apache/beam/workflows/Build%20python%20source%20distribution%20and%20wheels/badge.svg?branch=master&event=schedule)](https://github.com/apache/beam/actions?query=workflow%3A%22Build+python+source+distribution+and+wheels%22+branch%3Amaster+event%3Aschedule)
   [![Python tests](https://github.com/apache/beam/workflows/Python%20tests/badge.svg?branch=master&event=schedule)](https://github.com/apache/beam/actions?query=workflow%3A%22Python+Tests%22+branch%3Amaster+event%3Aschedule)
   [![Java tests](https://github.com/apache/beam/workflows/Java%20Tests/badge.svg?branch=master&event=schedule)](https://github.com/apache/beam/actions?query=workflow%3A%22Java+Tests%22+branch%3Amaster+event%3Aschedule)
   [![Go tests](https://github.com/apache/beam/workflows/Go%20tests/badge.svg?branch=master&event=schedule)](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.
   


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


[GitHub] [beam] github-actions[bot] commented on pull request #25823: Featue/online clustering

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #25823:
URL: https://github.com/apache/beam/pull/25823#issuecomment-1508412929

   Reminder, please take a look at this pr: @AnandInguva 


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


[GitHub] [beam] damccorm commented on a diff in pull request #25823: Featue/online clustering

Posted by "damccorm (via GitHub)" <gi...@apache.org>.
damccorm commented on code in PR #25823:
URL: https://github.com/apache/beam/pull/25823#discussion_r1200514293


##########
sdks/python/apache_beam/examples/california_housing_clustering.py:
##########
@@ -26,20 +26,20 @@
 transform assigns a cluster to each record in the dataset. This
 transform makes use of the RunInference API under the hood.
 
-In order to set this example up, you will need one thing.
+In order to run this example up:

Review Comment:
   ```suggestion
   In order to run this example:
   ```



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


[GitHub] [beam] github-actions[bot] commented on pull request #25823: Featue/online clustering

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #25823:
URL: https://github.com/apache/beam/pull/25823#issuecomment-1552966254

   Reminder, please take a look at this pr: @AnandInguva 


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


[GitHub] [beam] damccorm commented on pull request #25823: Featue/online clustering

Posted by "damccorm (via GitHub)" <gi...@apache.org>.
damccorm commented on PR #25823:
URL: https://github.com/apache/beam/pull/25823#issuecomment-1557295826

   Run Python_Transforms PreCommit


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


[GitHub] [beam] jaxpr commented on pull request #25823: Featue/online clustering

Posted by "jaxpr (via GitHub)" <gi...@apache.org>.
jaxpr commented on PR #25823:
URL: https://github.com/apache/beam/pull/25823#issuecomment-1557026550

   @damccorm I have updated the PR, your proposed changes are now implemented


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


[GitHub] [beam] github-actions[bot] commented on pull request #25823: Featue/online clustering

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #25823:
URL: https://github.com/apache/beam/pull/25823#issuecomment-1485412790

   Assigning reviewers. If you would like to opt out of this review, comment `assign to next reviewer`:
   
   R: @AnandInguva for label python.
   
   Available commands:
   - `stop reviewer notifications` - opt out of the automated review tooling
   - `remind me after tests pass` - tag the comment author after tests pass
   - `waiting on author` - shift the attention set back to the author (any comment or push by the author will return the attention set to the reviewers)
   
   The PR bot will only process comments in the main thread (not review comments).


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


[GitHub] [beam] damccorm commented on a diff in pull request #25823: Featue/online clustering

Posted by "damccorm (via GitHub)" <gi...@apache.org>.
damccorm commented on code in PR #25823:
URL: https://github.com/apache/beam/pull/25823#discussion_r1187468031


##########
sdks/python/apache_beam/examples/california_housing_clustering.py:
##########
@@ -1,16 +1,50 @@
+#
+# 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.
+#
+
+"""A pipeline that uses OnlineClustering transform to group houses
+with a similar value together.
+
+This example uses the California Housing Prices dataset from kaggle.
+https://www.kaggle.com/datasets/camnugent/california-housing-prices
+
+In the first step of the pipeline, the clustering model is trained
+using the OnlineKMeans transform, then the AssignClusterLabels
+transform assigns a cluster to each record in the dataset. This
+transform makes use of the RunInference API under the hood.
+
+In order to set this example up, you will need one thing.
+1. Download the data from kaggle as csv
+
+california_housing_clustering.py --input /tmp/housing.csv

Review Comment:
   ```suggestion
   In order to run this example up:
   1. Download the data from kaggle as csv
   2. Run `python california_housing_clustering.py --input <path/to/housing.csv>`
   ```



##########
sdks/python/apache_beam/examples/california_housing_clustering.py:
##########
@@ -40,17 +74,30 @@ def run(
   if not test_pipeline:
     pipeline = beam.Pipeline(options=pipeline_options)
 
-  data = (pipeline | read_csv(known_args.input))
+  data = pipeline | read_csv(known_args.input)
 
   features = ['longitude', 'latitude', 'median_income']
 
   housing_features = to_pcollection(data[features])
 
+  # 1. Calculate clustering centers and save model to persistent storage
   _ = (
       housing_features
       | beam.Map(lambda record: list(record))
-      | OnlineClustering(
-          OnlineKMeans, n_clusters=6, batch_size=256, cluster_args={})
+      | "Train clustering model" >> OnlineClustering(
+          OnlineKMeans,
+          n_clusters=6,
+          batch_size=256,
+          cluster_args={},
+          checkpoints_path='/tmp/checkpoints'))

Review Comment:
   Can we make the checkpoints path configurable as a pipeline option? This will allow the pipeline to be run on remote runners (e.g. dataflow)



##########
sdks/python/apache_beam/examples/online_clustering.py:
##########
@@ -1,20 +1,65 @@
+#
+# 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 datetime
 from operator import itemgetter
-from typing import Optional
 
+import joblib
 import numpy as np
 import pandas as pd
 from sklearn.cluster import MiniBatchKMeans
 
 import apache_beam as beam
-from apache_beam import pvalue
-
-from apache_beam.coders import PickleCoder, VarIntCoder
-from apache_beam.ml.inference.base import PredictionResult
+from apache_beam.coders import PickleCoder
+from apache_beam.coders import VarIntCoder
+from apache_beam.io.filesystems import FileSystems
+from apache_beam.ml.inference.base import RunInference
+from apache_beam.ml.inference.sklearn_inference import ModelFileType
+from apache_beam.ml.inference.sklearn_inference import SklearnModelHandlerNumpy
 from apache_beam.transforms import core
 from apache_beam.transforms import ptransform
 from apache_beam.transforms.userstate import ReadModifyWriteStateSpec
 
 
+class SaveModel(beam.DoFn):
+  """Saves trained clustering model to persistent storage"""
+  def __init__(self, checkpoints_path: str):
+    self.checkpoints_path = checkpoints_path
+
+  def process(self, model):
+    # generate ISO 8601
+    iso_timestamp = datetime.datetime.utcnow().strftime("%Y%m%dT%H%M%SZ")
+    checkpoint_name = f'{self.checkpoints_path}/{iso_timestamp}.checkpoint'
+    latest_checkpoint = f'{self.checkpoints_path}/latest.checkpoint'
+    # rename previous checkpoint
+    if FileSystems.exists(latest_checkpoint):
+      FileSystems.rename([latest_checkpoint], [checkpoint_name])
+    file = FileSystems.create(latest_checkpoint, 'wb')
+    if not joblib:
+      raise ImportError(
+          'Could not import joblib in this execution environment. '
+          'For help with managing dependencies on Python workers.'
+          'see https://beam.apache.org/documentation/sdks/python-pipeline-dependencies/'  # pylint: disable=line-too-long
+      )
+
+    joblib.dump(model, file)
+
+    yield checkpoint_name

Review Comment:
   I think we should yield `(checkpoint_name, model)` to give users the ability to use the model directly if they want to.



##########
sdks/python/apache_beam/examples/california_housing_clustering.py:
##########
@@ -40,17 +74,30 @@ def run(
   if not test_pipeline:
     pipeline = beam.Pipeline(options=pipeline_options)
 
-  data = (pipeline | read_csv(known_args.input))
+  data = pipeline | read_csv(known_args.input)
 
   features = ['longitude', 'latitude', 'median_income']
 
   housing_features = to_pcollection(data[features])
 
+  # 1. Calculate clustering centers and save model to persistent storage
   _ = (
       housing_features
       | beam.Map(lambda record: list(record))
-      | OnlineClustering(
-          OnlineKMeans, n_clusters=6, batch_size=256, cluster_args={})
+      | "Train clustering model" >> OnlineClustering(
+          OnlineKMeans,
+          n_clusters=6,
+          batch_size=256,
+          cluster_args={},
+          checkpoints_path='/tmp/checkpoints'))
+
+  # 2. Calculate labels for all records in the dataset
+  # using the trained clustering model
+  _ = (

Review Comment:
   We can just call out that this introduces the problem of not classifying any data until all data has passed through and say that this could be resolved with the use of windowing and side inputs



##########
sdks/python/apache_beam/examples/california_housing_clustering.py:
##########
@@ -40,17 +74,30 @@ def run(
   if not test_pipeline:
     pipeline = beam.Pipeline(options=pipeline_options)
 
-  data = (pipeline | read_csv(known_args.input))
+  data = pipeline | read_csv(known_args.input)
 
   features = ['longitude', 'latitude', 'median_income']
 
   housing_features = to_pcollection(data[features])
 
+  # 1. Calculate clustering centers and save model to persistent storage
   _ = (
       housing_features
       | beam.Map(lambda record: list(record))
-      | OnlineClustering(
-          OnlineKMeans, n_clusters=6, batch_size=256, cluster_args={})
+      | "Train clustering model" >> OnlineClustering(
+          OnlineKMeans,
+          n_clusters=6,
+          batch_size=256,
+          cluster_args={},
+          checkpoints_path='/tmp/checkpoints'))
+
+  # 2. Calculate labels for all records in the dataset
+  # using the trained clustering model
+  _ = (

Review Comment:
   I don't think having 2 totally separate transforms is what we want. This transform should still be dependent on the first transform, and probably shouldn't use RunInference (since RunInference won't reload the model over time). Otherwise, this likely either won't work at all (and will throw when loading the model), or it will only ever use the cluster generated by the first few datapoints (and won't update over time)



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


[GitHub] [beam] damccorm commented on pull request #25823: Featue/online clustering

Posted by "damccorm (via GitHub)" <gi...@apache.org>.
damccorm commented on PR #25823:
URL: https://github.com/apache/beam/pull/25823#issuecomment-1557217790

   Run Python_Coverage PreCommit


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


[GitHub] [beam] AnandInguva commented on pull request #25823: Featue/online clustering

Posted by "AnandInguva (via GitHub)" <gi...@apache.org>.
AnandInguva commented on PR #25823:
URL: https://github.com/apache/beam/pull/25823#issuecomment-1509024174

   waiting on author


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


[GitHub] [beam] codecov[bot] commented on pull request #25823: Featue/online clustering

Posted by "codecov[bot] (via GitHub)" <gi...@apache.org>.
codecov[bot] commented on PR #25823:
URL: https://github.com/apache/beam/pull/25823#issuecomment-1466407357

   ## [Codecov](https://codecov.io/gh/apache/beam/pull/25823?src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation) Report
   > Merging [#25823](https://codecov.io/gh/apache/beam/pull/25823?src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation) (8b51a4c) into [master](https://codecov.io/gh/apache/beam/commit/4da602517292adcd9ffcd7cc0acb8b0c1155aa02?el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation) (4da6025) will **decrease** coverage by `0.16%`.
   > The diff coverage is `0.00%`.
   
   ```diff
   @@            Coverage Diff             @@
   ##           master   #25823      +/-   ##
   ==========================================
   - Coverage   72.83%   72.67%   -0.16%     
   ==========================================
     Files         775      779       +4     
     Lines      102928   103151     +223     
   ==========================================
     Hits        74963    74963              
   - Misses      26511    26734     +223     
     Partials     1454     1454              
   ```
   
   | Flag | Coverage Δ | |
   |---|---|---|
   | python | `81.71% <0.00%> (-0.27%)` | :arrow_down: |
   
   Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#carryforward-flags-in-the-pull-request-comment) to find out more.
   
   | [Impacted Files](https://codecov.io/gh/apache/beam/pull/25823?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation) | Coverage Δ | |
   |---|---|---|
   | [...che\_beam/examples/california\_housing\_clustering.py](https://codecov.io/gh/apache/beam/pull/25823?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-c2Rrcy9weXRob24vYXBhY2hlX2JlYW0vZXhhbXBsZXMvY2FsaWZvcm5pYV9ob3VzaW5nX2NsdXN0ZXJpbmcucHk=) | `0.00% <0.00%> (ø)` | |
   | [...python/apache\_beam/transforms/online\_clustering.py](https://codecov.io/gh/apache/beam/pull/25823?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-c2Rrcy9weXRob24vYXBhY2hlX2JlYW0vdHJhbnNmb3Jtcy9vbmxpbmVfY2x1c3RlcmluZy5weQ==) | `0.00% <0.00%> (ø)` | |
   
   ... and [12 files with indirect coverage changes](https://codecov.io/gh/apache/beam/pull/25823/indirect-changes?src=pr&el=tree-more&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation)
   
   :mega: We’re building smart automated test selection to slash your CI/CD build times. [Learn more](https://about.codecov.io/iterative-testing/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation)
   


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


[GitHub] [beam] damccorm commented on a diff in pull request #25823: Featue/online clustering

Posted by "damccorm (via GitHub)" <gi...@apache.org>.
damccorm commented on code in PR #25823:
URL: https://github.com/apache/beam/pull/25823#discussion_r1156262232


##########
sdks/python/apache_beam/examples/california_housing_clustering.py:
##########
@@ -0,0 +1,62 @@
+import argparse

Review Comment:
   Could you please:
   
   1) Add apache headers to these files
   2) Add a writeup of how to run this?



##########
sdks/python/apache_beam/transforms/online_clustering.py:
##########
@@ -0,0 +1,218 @@
+from operator import itemgetter
+from typing import Optional
+
+import numpy as np
+import pandas as pd
+from sklearn.cluster import MiniBatchKMeans
+
+import apache_beam as beam
+from apache_beam import pvalue
+
+from apache_beam.coders import PickleCoder, VarIntCoder
+from apache_beam.ml.inference.base import PredictionResult
+from apache_beam.transforms import core
+from apache_beam.transforms import ptransform
+from apache_beam.transforms.userstate import ReadModifyWriteStateSpec
+
+
+class SelectLatestModelState(beam.CombineFn):
+  """Selects that latest version of a model after training"""
+  def create_accumulator(self):
+    # create and initialise accumulator
+    return None, 0
+
+  def add_input(self, accumulator, element):
+    # accumulates each element from input in accumulator
+    if element[1] > accumulator[1]:
+      return element
+    return accumulator
+
+  def merge_accumulators(self, accumulators):
+    # Multiple accumulators could be processed in parallel,
+    # this function merges them
+    return max(accumulators, key=itemgetter(1))
+
+  def extract_output(self, accumulator):
+    # Only output the tracker
+    return accumulator[0]
+
+
+class AssignClusterLabels(core.DoFn):
+  """Takes a trained model and input data and labels all data instances using the trained model."""
+  def process(self, keyed_batch, model, model_id):
+    # 1. Remove the temporary assigned key
+    _, batch = keyed_batch
+
+    # 2. Calculate cluster predictions
+    cluster_labels = model.predict(batch)
+
+    for e, i in zip(batch, cluster_labels):
+      yield PredictionResult(example=e, inference=i, model_id=model_id)
+
+
+class ClusteringAlgorithm(core.DoFn):
+  """Abstract class with the interface that clustering algorithms need to follow."""
+
+  MODEL_SPEC = ReadModifyWriteStateSpec("clustering_model", PickleCoder())
+  ITERATION_SPEC = ReadModifyWriteStateSpec(
+      'training_iterations', VarIntCoder())
+  MODEL_ID = 'ClusteringAlgorithm'
+
+  def __init__(self, n_clusters: int, cluster_args: dict):
+    super().__init__()
+    self.n_clusters = n_clusters
+    self.cluster_args = cluster_args
+
+  def process(
+      self,
+      keyed_batch,
+      model_state=core.DoFn.StateParam(MODEL_SPEC),
+      iteration_state=core.DoFn.StateParam(ITERATION_SPEC)):
+    raise NotImplementedError
+
+
+class OnlineKMeans(ClusteringAlgorithm):
+  """Online K-Means function. Used the MiniBatchKMeans from sklearn
+    More information: https://scikit-learn.org/stable/modules/generated/sklearn.cluster.MiniBatchKMeans.html"""
+  MODEL_SPEC = ReadModifyWriteStateSpec("clustering_model", PickleCoder())
+  ITERATION_SPEC = ReadModifyWriteStateSpec(
+      'training_iterations', VarIntCoder())
+  MODEL_ID = 'OnlineKmeans'
+
+  def process(
+      self,
+      keyed_batch,
+      model_state=core.DoFn.StateParam(MODEL_SPEC),
+      iteration_state=core.DoFn.StateParam(ITERATION_SPEC)):
+    # 1. Initialise or load states
+    clustering = model_state.read() or MiniBatchKMeans(
+        n_clusters=self.n_clusters, **self.cluster_args)
+    iteration = iteration_state.read() or 0
+
+    iteration += 1
+
+    # 2. Remove the temporary assigned keys
+    _, batch = keyed_batch
+
+    # 3. Calculate cluster centroids
+    clustering.partial_fit(batch)
+
+    # 4. Store the training set and model
+    model_state.write(clustering)
+    iteration_state.write(iteration)
+
+    yield clustering, iteration
+
+
+class TypeConversion(core.DoFn):
+  """Helper function to convert incoming data to numpy arrays that are accepted by sklearn"""
+  def process(self, element, *args, **kwargs):
+    if isinstance(element, (tuple, list)):
+      yield np.array(element)
+    elif isinstance(element, np.ndarray):
+      yield element
+    elif isinstance(element, (pd.DataFrame, pd.Series)):
+      yield element.to_numpy()
+    else:
+      raise ValueError(f"Unsupported type: {type(element)}")
+
+
+class ClusteringPreprocessing(ptransform.PTransform):
+  def __init__(
+      self, n_clusters: int, batch_size: int, is_batched: bool = False):
+    """ Preprocessing for Clustering Transformation
+        The clustering transform expects batches for performance reasons,
+        therefore this batches the data and converts it to numpy arrays,
+        which are accepted by sklearn. This transform also adds the same key
+        to all batches, such that only 1 state is created and updated during
+        clustering updates.
+
+          Example Usage::
+
+            pcoll | RunInference(
+                        XGBoostModelHandlerNumpy(
+                            model_class="XGBoost Model Class",
+                            model_state="my_model_state.json")))
+
+          Args:
+          n_clusters: number of clusters used by the algorithm
+          batch_size: size of the data batches
+          is_batched: boolean value that marks if the collection is already batched
+           and thus doesn't need to be batched by this transform
+          """
+    super().__init__()
+    self.n_clusters = n_clusters
+    self.batch_size = batch_size
+    self.is_batched = is_batched
+
+  def expand(self, pcoll):
+    pcoll = (
+        pcoll
+        | "Convert element to numpy arrays" >> beam.ParDo(TypeConversion()))
+
+    if not self.is_batched:
+      pcoll = (
+          pcoll
+          | "Create batches of elements" >> beam.BatchElements(
+              min_batch_size=self.n_clusters, max_batch_size=self.batch_size))
+
+    return (pcoll | "Add a key" >> beam.Map(lambda record: (1, record)))
+
+
+class OnlineClustering(ptransform.PTransform):
+  def __init__(
+      self,
+      clustering_algorithm,
+      n_clusters: int,
+      cluster_args: dict,
+      batch_size: int = 1024,
+      is_batched: bool = False):
+    """ Clustering transformation itself, it first preprocesses the data,
+        then it applies the clustering transformation step by step on each
+        of the batches.
+
+          Example Usage::
+
+            pcoll | OnlineClustering(
+                        clustering_algorithm=OnlineKMeansClustering
+                        batch_size=1024,
+                        n_clusters=6
+                        cluster_args={}))
+
+          Args:
+          clustering_algorithm: Clustering algorithm (DoFn)
+          n_clusters: Number of clusters
+          cluster_args: Arguments for the sklearn clustering algorithm (check sklearn documentation for more information)
+          batch_size: size of the data batches
+          is_batched: boolean value that marks if the collection is already batched
+           and thus doesn't need to be batched by this transform
+          """
+    super().__init__()
+    self.clustering_algorithm = clustering_algorithm
+    self.n_clusters = n_clusters
+    self.batch_size = batch_size
+    self.cluster_args = cluster_args
+    self.is_batched = is_batched
+
+  def expand(self, pcoll):
+    data = (
+        pcoll
+        | ClusteringPreprocessing(
+            n_clusters=self.n_clusters,
+            batch_size=self.batch_size,
+            is_batched=self.is_batched))
+
+    model = (
+        data
+        | 'Cluster' >> core.ParDo(
+            self.clustering_algorithm(
+                n_clusters=self.n_clusters, cluster_args=self.cluster_args))
+        | 'Select latest model state' >> core.CombineGlobally(
+            SelectLatestModelState()))

Review Comment:
   I'm a little concerned with how this approach will interact with Beam's windowing. Specifically, in the scenario where you have multiple windows, since state is scoped to key/window we will discard all progress when we enter a new window (and we'll start a new clustering algorithm).
   
   I think a better approach here might be to repeatedly emit the newly trained model and pick that value up in our side input - that way the data is always being labeled by the most recent version of the clustering algorithm.
   
   This has some drawbacks - specifically, it will label data with potentially unknown versions of the model because side inputs aren't guaranteed to update before we process the data used to train the side input.



##########
sdks/python/apache_beam/transforms/online_clustering.py:
##########
@@ -0,0 +1,218 @@
+from operator import itemgetter
+from typing import Optional
+
+import numpy as np
+import pandas as pd
+from sklearn.cluster import MiniBatchKMeans
+
+import apache_beam as beam
+from apache_beam import pvalue
+
+from apache_beam.coders import PickleCoder, VarIntCoder
+from apache_beam.ml.inference.base import PredictionResult
+from apache_beam.transforms import core
+from apache_beam.transforms import ptransform
+from apache_beam.transforms.userstate import ReadModifyWriteStateSpec
+
+
+class SelectLatestModelState(beam.CombineFn):
+  """Selects that latest version of a model after training"""
+  def create_accumulator(self):
+    # create and initialise accumulator
+    return None, 0
+
+  def add_input(self, accumulator, element):
+    # accumulates each element from input in accumulator
+    if element[1] > accumulator[1]:
+      return element
+    return accumulator
+
+  def merge_accumulators(self, accumulators):
+    # Multiple accumulators could be processed in parallel,
+    # this function merges them
+    return max(accumulators, key=itemgetter(1))
+
+  def extract_output(self, accumulator):
+    # Only output the tracker
+    return accumulator[0]
+
+
+class AssignClusterLabels(core.DoFn):
+  """Takes a trained model and input data and labels all data instances using the trained model."""
+  def process(self, keyed_batch, model, model_id):
+    # 1. Remove the temporary assigned key
+    _, batch = keyed_batch
+
+    # 2. Calculate cluster predictions
+    cluster_labels = model.predict(batch)
+
+    for e, i in zip(batch, cluster_labels):
+      yield PredictionResult(example=e, inference=i, model_id=model_id)
+
+
+class ClusteringAlgorithm(core.DoFn):
+  """Abstract class with the interface that clustering algorithms need to follow."""
+
+  MODEL_SPEC = ReadModifyWriteStateSpec("clustering_model", PickleCoder())
+  ITERATION_SPEC = ReadModifyWriteStateSpec(
+      'training_iterations', VarIntCoder())
+  MODEL_ID = 'ClusteringAlgorithm'
+
+  def __init__(self, n_clusters: int, cluster_args: dict):
+    super().__init__()
+    self.n_clusters = n_clusters
+    self.cluster_args = cluster_args
+
+  def process(
+      self,
+      keyed_batch,
+      model_state=core.DoFn.StateParam(MODEL_SPEC),
+      iteration_state=core.DoFn.StateParam(ITERATION_SPEC)):
+    raise NotImplementedError
+
+
+class OnlineKMeans(ClusteringAlgorithm):
+  """Online K-Means function. Used the MiniBatchKMeans from sklearn
+    More information: https://scikit-learn.org/stable/modules/generated/sklearn.cluster.MiniBatchKMeans.html"""
+  MODEL_SPEC = ReadModifyWriteStateSpec("clustering_model", PickleCoder())
+  ITERATION_SPEC = ReadModifyWriteStateSpec(
+      'training_iterations', VarIntCoder())
+  MODEL_ID = 'OnlineKmeans'
+
+  def process(
+      self,
+      keyed_batch,
+      model_state=core.DoFn.StateParam(MODEL_SPEC),
+      iteration_state=core.DoFn.StateParam(ITERATION_SPEC)):
+    # 1. Initialise or load states
+    clustering = model_state.read() or MiniBatchKMeans(
+        n_clusters=self.n_clusters, **self.cluster_args)
+    iteration = iteration_state.read() or 0
+
+    iteration += 1
+
+    # 2. Remove the temporary assigned keys
+    _, batch = keyed_batch
+
+    # 3. Calculate cluster centroids
+    clustering.partial_fit(batch)
+
+    # 4. Store the training set and model
+    model_state.write(clustering)
+    iteration_state.write(iteration)
+
+    yield clustering, iteration
+
+
+class TypeConversion(core.DoFn):
+  """Helper function to convert incoming data to numpy arrays that are accepted by sklearn"""
+  def process(self, element, *args, **kwargs):
+    if isinstance(element, (tuple, list)):
+      yield np.array(element)
+    elif isinstance(element, np.ndarray):
+      yield element
+    elif isinstance(element, (pd.DataFrame, pd.Series)):
+      yield element.to_numpy()
+    else:
+      raise ValueError(f"Unsupported type: {type(element)}")
+
+
+class ClusteringPreprocessing(ptransform.PTransform):
+  def __init__(
+      self, n_clusters: int, batch_size: int, is_batched: bool = False):
+    """ Preprocessing for Clustering Transformation
+        The clustering transform expects batches for performance reasons,
+        therefore this batches the data and converts it to numpy arrays,
+        which are accepted by sklearn. This transform also adds the same key
+        to all batches, such that only 1 state is created and updated during
+        clustering updates.
+
+          Example Usage::
+
+            pcoll | RunInference(
+                        XGBoostModelHandlerNumpy(
+                            model_class="XGBoost Model Class",
+                            model_state="my_model_state.json")))
+
+          Args:
+          n_clusters: number of clusters used by the algorithm
+          batch_size: size of the data batches
+          is_batched: boolean value that marks if the collection is already batched
+           and thus doesn't need to be batched by this transform
+          """
+    super().__init__()
+    self.n_clusters = n_clusters
+    self.batch_size = batch_size
+    self.is_batched = is_batched
+
+  def expand(self, pcoll):
+    pcoll = (
+        pcoll
+        | "Convert element to numpy arrays" >> beam.ParDo(TypeConversion()))
+
+    if not self.is_batched:
+      pcoll = (
+          pcoll
+          | "Create batches of elements" >> beam.BatchElements(
+              min_batch_size=self.n_clusters, max_batch_size=self.batch_size))
+
+    return (pcoll | "Add a key" >> beam.Map(lambda record: (1, record)))
+
+
+class OnlineClustering(ptransform.PTransform):
+  def __init__(
+      self,
+      clustering_algorithm,
+      n_clusters: int,
+      cluster_args: dict,
+      batch_size: int = 1024,
+      is_batched: bool = False):
+    """ Clustering transformation itself, it first preprocesses the data,
+        then it applies the clustering transformation step by step on each
+        of the batches.
+
+          Example Usage::
+
+            pcoll | OnlineClustering(
+                        clustering_algorithm=OnlineKMeansClustering
+                        batch_size=1024,
+                        n_clusters=6
+                        cluster_args={}))
+
+          Args:
+          clustering_algorithm: Clustering algorithm (DoFn)
+          n_clusters: Number of clusters
+          cluster_args: Arguments for the sklearn clustering algorithm (check sklearn documentation for more information)
+          batch_size: size of the data batches
+          is_batched: boolean value that marks if the collection is already batched
+           and thus doesn't need to be batched by this transform
+          """
+    super().__init__()
+    self.clustering_algorithm = clustering_algorithm
+    self.n_clusters = n_clusters
+    self.batch_size = batch_size
+    self.cluster_args = cluster_args
+    self.is_batched = is_batched
+
+  def expand(self, pcoll):
+    data = (
+        pcoll
+        | ClusteringPreprocessing(
+            n_clusters=self.n_clusters,
+            batch_size=self.batch_size,
+            is_batched=self.is_batched))
+
+    model = (
+        data
+        | 'Cluster' >> core.ParDo(
+            self.clustering_algorithm(
+                n_clusters=self.n_clusters, cluster_args=self.cluster_args))
+        | 'Select latest model state' >> core.CombineGlobally(
+            SelectLatestModelState()))

Review Comment:
   Another option would be to add the clustering transform and the AssignClusterLabels transform as independent transforms that can be linked together (but aren't inherently linked outside the context of an example). That gives users the full expressiveness of being able to define whatever implementation they desire. That's probably actually what I'd recommend here - have them be independent transforms linked together by the california_housing_clustering examples).



##########
sdks/python/apache_beam/transforms/online_clustering.py:
##########
@@ -0,0 +1,218 @@
+from operator import itemgetter
+from typing import Optional
+
+import numpy as np
+import pandas as pd
+from sklearn.cluster import MiniBatchKMeans
+
+import apache_beam as beam
+from apache_beam import pvalue
+
+from apache_beam.coders import PickleCoder, VarIntCoder
+from apache_beam.ml.inference.base import PredictionResult
+from apache_beam.transforms import core
+from apache_beam.transforms import ptransform
+from apache_beam.transforms.userstate import ReadModifyWriteStateSpec
+
+
+class SelectLatestModelState(beam.CombineFn):
+  """Selects that latest version of a model after training"""
+  def create_accumulator(self):
+    # create and initialise accumulator
+    return None, 0
+
+  def add_input(self, accumulator, element):
+    # accumulates each element from input in accumulator
+    if element[1] > accumulator[1]:
+      return element
+    return accumulator
+
+  def merge_accumulators(self, accumulators):
+    # Multiple accumulators could be processed in parallel,
+    # this function merges them
+    return max(accumulators, key=itemgetter(1))
+
+  def extract_output(self, accumulator):
+    # Only output the tracker
+    return accumulator[0]
+
+
+class AssignClusterLabels(core.DoFn):
+  """Takes a trained model and input data and labels all data instances using the trained model."""
+  def process(self, keyed_batch, model, model_id):
+    # 1. Remove the temporary assigned key
+    _, batch = keyed_batch
+
+    # 2. Calculate cluster predictions
+    cluster_labels = model.predict(batch)
+
+    for e, i in zip(batch, cluster_labels):
+      yield PredictionResult(example=e, inference=i, model_id=model_id)
+
+
+class ClusteringAlgorithm(core.DoFn):
+  """Abstract class with the interface that clustering algorithms need to follow."""
+
+  MODEL_SPEC = ReadModifyWriteStateSpec("clustering_model", PickleCoder())
+  ITERATION_SPEC = ReadModifyWriteStateSpec(
+      'training_iterations', VarIntCoder())
+  MODEL_ID = 'ClusteringAlgorithm'
+
+  def __init__(self, n_clusters: int, cluster_args: dict):
+    super().__init__()
+    self.n_clusters = n_clusters
+    self.cluster_args = cluster_args
+
+  def process(
+      self,
+      keyed_batch,
+      model_state=core.DoFn.StateParam(MODEL_SPEC),
+      iteration_state=core.DoFn.StateParam(ITERATION_SPEC)):
+    raise NotImplementedError
+
+
+class OnlineKMeans(ClusteringAlgorithm):
+  """Online K-Means function. Used the MiniBatchKMeans from sklearn
+    More information: https://scikit-learn.org/stable/modules/generated/sklearn.cluster.MiniBatchKMeans.html"""
+  MODEL_SPEC = ReadModifyWriteStateSpec("clustering_model", PickleCoder())
+  ITERATION_SPEC = ReadModifyWriteStateSpec(
+      'training_iterations', VarIntCoder())
+  MODEL_ID = 'OnlineKmeans'
+
+  def process(
+      self,
+      keyed_batch,
+      model_state=core.DoFn.StateParam(MODEL_SPEC),
+      iteration_state=core.DoFn.StateParam(ITERATION_SPEC)):
+    # 1. Initialise or load states
+    clustering = model_state.read() or MiniBatchKMeans(
+        n_clusters=self.n_clusters, **self.cluster_args)
+    iteration = iteration_state.read() or 0
+
+    iteration += 1
+
+    # 2. Remove the temporary assigned keys
+    _, batch = keyed_batch
+
+    # 3. Calculate cluster centroids
+    clustering.partial_fit(batch)
+
+    # 4. Store the training set and model
+    model_state.write(clustering)
+    iteration_state.write(iteration)
+
+    yield clustering, iteration
+
+
+class TypeConversion(core.DoFn):
+  """Helper function to convert incoming data to numpy arrays that are accepted by sklearn"""
+  def process(self, element, *args, **kwargs):
+    if isinstance(element, (tuple, list)):
+      yield np.array(element)
+    elif isinstance(element, np.ndarray):
+      yield element
+    elif isinstance(element, (pd.DataFrame, pd.Series)):
+      yield element.to_numpy()
+    else:
+      raise ValueError(f"Unsupported type: {type(element)}")
+
+
+class ClusteringPreprocessing(ptransform.PTransform):
+  def __init__(
+      self, n_clusters: int, batch_size: int, is_batched: bool = False):
+    """ Preprocessing for Clustering Transformation
+        The clustering transform expects batches for performance reasons,
+        therefore this batches the data and converts it to numpy arrays,
+        which are accepted by sklearn. This transform also adds the same key
+        to all batches, such that only 1 state is created and updated during
+        clustering updates.
+
+          Example Usage::
+
+            pcoll | RunInference(
+                        XGBoostModelHandlerNumpy(
+                            model_class="XGBoost Model Class",
+                            model_state="my_model_state.json")))
+
+          Args:
+          n_clusters: number of clusters used by the algorithm
+          batch_size: size of the data batches
+          is_batched: boolean value that marks if the collection is already batched
+           and thus doesn't need to be batched by this transform
+          """
+    super().__init__()
+    self.n_clusters = n_clusters
+    self.batch_size = batch_size
+    self.is_batched = is_batched
+
+  def expand(self, pcoll):
+    pcoll = (
+        pcoll
+        | "Convert element to numpy arrays" >> beam.ParDo(TypeConversion()))
+
+    if not self.is_batched:
+      pcoll = (
+          pcoll
+          | "Create batches of elements" >> beam.BatchElements(
+              min_batch_size=self.n_clusters, max_batch_size=self.batch_size))
+
+    return (pcoll | "Add a key" >> beam.Map(lambda record: (1, record)))
+
+
+class OnlineClustering(ptransform.PTransform):
+  def __init__(
+      self,
+      clustering_algorithm,
+      n_clusters: int,
+      cluster_args: dict,
+      batch_size: int = 1024,
+      is_batched: bool = False):
+    """ Clustering transformation itself, it first preprocesses the data,
+        then it applies the clustering transformation step by step on each
+        of the batches.
+
+          Example Usage::
+
+            pcoll | OnlineClustering(
+                        clustering_algorithm=OnlineKMeansClustering
+                        batch_size=1024,
+                        n_clusters=6
+                        cluster_args={}))
+
+          Args:
+          clustering_algorithm: Clustering algorithm (DoFn)
+          n_clusters: Number of clusters
+          cluster_args: Arguments for the sklearn clustering algorithm (check sklearn documentation for more information)
+          batch_size: size of the data batches
+          is_batched: boolean value that marks if the collection is already batched
+           and thus doesn't need to be batched by this transform
+          """
+    super().__init__()
+    self.clustering_algorithm = clustering_algorithm
+    self.n_clusters = n_clusters
+    self.batch_size = batch_size
+    self.cluster_args = cluster_args
+    self.is_batched = is_batched
+
+  def expand(self, pcoll):
+    data = (
+        pcoll
+        | ClusteringPreprocessing(
+            n_clusters=self.n_clusters,
+            batch_size=self.batch_size,
+            is_batched=self.is_batched))
+
+    model = (
+        data
+        | 'Cluster' >> core.ParDo(
+            self.clustering_algorithm(
+                n_clusters=self.n_clusters, cluster_args=self.cluster_args))
+        | 'Select latest model state' >> core.CombineGlobally(
+            SelectLatestModelState()))

Review Comment:
   I think regardless, we should probably move this to the examples directory for now (it can sit next to california_housing_clustering) since this story isn't fully fleshed out. I'd still request that we unlink the 2 pieces of the transform since I think its a better/more expressive pattern.
   
   Putting it in the examples directory is probably for the best until we have a fuller suite of these algorithms anyways.



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


[GitHub] [beam] AnandInguva commented on pull request #25823: Featue/online clustering

Posted by "AnandInguva (via GitHub)" <gi...@apache.org>.
AnandInguva commented on PR #25823:
URL: https://github.com/apache/beam/pull/25823#issuecomment-1494844959

   Ah sorry. I missed this PR review. It got missed in the pile of notifications. 


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


[GitHub] [beam] damccorm merged pull request #25823: Featue/online clustering

Posted by "damccorm (via GitHub)" <gi...@apache.org>.
damccorm merged PR #25823:
URL: https://github.com/apache/beam/pull/25823


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