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/01/24 15:35:54 UTC

[GitHub] [beam] jaxpr commented on a diff in pull request #24965: XGBoost modelhandler implementation

jaxpr commented on code in PR #24965:
URL: https://github.com/apache/beam/pull/24965#discussion_r1085502764


##########
sdks/python/apache_beam/ml/inference/xgboost_inference.py:
##########
@@ -0,0 +1,212 @@
+#
+# 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 sys
+from abc import ABC
+from typing import Any
+from typing import Callable
+from typing import Dict
+from typing import Iterable
+from typing import Optional
+from typing import Sequence
+from typing import Union
+
+import datatable
+import numpy
+import pandas
+import scipy
+import xgboost
+
+from apache_beam.ml.inference.base import ExampleT
+from apache_beam.ml.inference.base import ModelHandler
+from apache_beam.ml.inference.base import ModelT
+from apache_beam.ml.inference.base import PredictionResult
+from apache_beam.ml.inference.base import PredictionT
+
+
+class XGBoostModelHandler(ModelHandler[ExampleT, PredictionT, ModelT], ABC):

Review Comment:
   I have added the comment saying the class should not be instantiated directly as @AnandInguva suggested.



##########
sdks/python/apache_beam/ml/inference/xgboost_inference.py:
##########
@@ -0,0 +1,212 @@
+#
+# 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 sys
+from abc import ABC
+from typing import Any
+from typing import Callable
+from typing import Dict
+from typing import Iterable
+from typing import Optional
+from typing import Sequence
+from typing import Union
+
+import datatable
+import numpy
+import pandas
+import scipy
+import xgboost
+
+from apache_beam.ml.inference.base import ExampleT
+from apache_beam.ml.inference.base import ModelHandler
+from apache_beam.ml.inference.base import ModelT
+from apache_beam.ml.inference.base import PredictionResult
+from apache_beam.ml.inference.base import PredictionT
+
+
+class XGBoostModelHandler(ModelHandler[ExampleT, PredictionT, ModelT], ABC):
+  def __init__(
+      self,
+      model_class: Union[Callable[..., xgboost.Booster],
+                         Callable[..., xgboost.XGBModel]],
+      model_state: str):
+    self.model_class = model_class
+    self.model_state = model_state
+
+  def load_model(self) -> Union[xgboost.Booster, xgboost.XGBModel]:
+    model = self.model_class()
+    model.load_model(self.model_state)
+    return model
+
+  def get_metrics_namespace(self) -> str:
+    return 'BeamML_XGBoost'
+
+
+class XGBoostModelHandlerNumpy(XGBoostModelHandler[numpy.ndarray,
+                                                   PredictionResult,
+                                                   Union[xgboost.Booster,
+                                                         xgboost.XGBModel]]):
+  def run_inference(
+      self,
+      batch: Sequence[numpy.ndarray],
+      model: Union[xgboost.Booster, xgboost.XGBModel],
+      inference_args: Optional[Dict[str, Any]] = None) -> Iterable[PredictionT]:
+    """Runs inferences on a batch of 2d numpy arrays.
+
+        Args:
+          batch: A sequence of examples as 2d numpy arrays. Each
+            row in an array is a single example. The dimensions
+            must match the dimensions of the data used to train
+            the model.
+          model: XGBoost booster or XBGModel (sklearn interface). Must
+            implement predict(X). Where the parameter X is a 2d numpy array.
+          inference_args: Any additional arguments for an inference.
+
+        Returns:
+          An Iterable of type PredictionResult.
+        """
+    inference_args = {} if not inference_args else inference_args
+
+    if type(model) == xgboost.Booster:
+      batch = (xgboost.DMatrix(array) for array in batch)
+    predictions = [model.predict(el, **inference_args) for el in batch]

Review Comment:
   Good suggestion indeed as this seems possible using the XGBoost scipy api. I added a custom inference fn.



##########
sdks/python/container/py310/base_image_requirements.txt:
##########
@@ -154,4 +155,5 @@ urllib3==1.26.13
 websocket-client==1.4.2
 Werkzeug==2.2.2
 wrapt==1.14.1
+xgboost==1.7.1

Review Comment:
   I followed the suggestion by @AnandInguva as well over here



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