You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@spark.apache.org by ru...@apache.org on 2025/02/02 01:15:18 UTC

(spark) branch branch-4.0 updated: [SPARK-50843][ML][PYTHON][CONNECT] Support return a new model from existing one

This is an automated email from the ASF dual-hosted git repository.

ruifengz pushed a commit to branch branch-4.0
in repository https://gitbox.apache.org/repos/asf/spark.git


The following commit(s) were added to refs/heads/branch-4.0 by this push:
     new 710059837aa4 [SPARK-50843][ML][PYTHON][CONNECT] Support return a new model from existing one
710059837aa4 is described below

commit 710059837aa4051c98cc66701a643f64e50210a0
Author: Ruifeng Zheng <ru...@apache.org>
AuthorDate: Sun Feb 2 09:14:44 2025 +0800

    [SPARK-50843][ML][PYTHON][CONNECT] Support return a new model from existing one
    
    ### What changes were proposed in this pull request?
    Support return a new model from existing one, e.g.
    1, `RandomForestClassificationModel.trees` -> get underlying decision tree models;
    2, `DistributedLDAModel.toLocal` -> get a `LocalLDAModel`
    
    ### Why are the changes needed?
    feature parity
    
    ### Does this PR introduce _any_ user-facing change?
    yes
    
    ### How was this patch tested?
    added tests
    
    ### Was this patch authored or co-authored using generative AI tooling?
    no
    
    Closes #49709 from zhengruifeng/ml_connect_model.
    
    Authored-by: Ruifeng Zheng <ru...@apache.org>
    Signed-off-by: Ruifeng Zheng <ru...@apache.org>
    (cherry picked from commit ba18f502efbf4788410df65ab4a4edea8c2ec2db)
    Signed-off-by: Ruifeng Zheng <ru...@apache.org>
---
 .../org/apache/spark/ml/tree/treeModels.scala      |  2 ++
 python/pyspark/ml/classification.py                | 13 +++++++++--
 python/pyspark/ml/clustering.py                    |  5 +++++
 python/pyspark/ml/regression.py                    | 12 ++++++++--
 python/pyspark/ml/tests/test_classification.py     | 25 +++++++++++++++++----
 python/pyspark/ml/tests/test_clustering.py         | 12 ++++++++++
 python/pyspark/ml/tests/test_regression.py         | 26 ++++++++++++++++++----
 python/pyspark/ml/util.py                          |  6 +++++
 .../apache/spark/sql/connect/ml/MLHandler.scala    |  9 ++++++++
 .../org/apache/spark/sql/connect/ml/MLUtils.scala  |  6 ++---
 10 files changed, 101 insertions(+), 15 deletions(-)

diff --git a/mllib/src/main/scala/org/apache/spark/ml/tree/treeModels.scala b/mllib/src/main/scala/org/apache/spark/ml/tree/treeModels.scala
index 0fdf02e1da63..a001edf3e045 100644
--- a/mllib/src/main/scala/org/apache/spark/ml/tree/treeModels.scala
+++ b/mllib/src/main/scala/org/apache/spark/ml/tree/treeModels.scala
@@ -130,6 +130,8 @@ private[spark] trait TreeEnsembleModel[M <: DecisionTreeModel] {
   /** Trees in this ensemble. Warning: These have null parent Estimators. */
   def trees: Array[M]
 
+  private[ml] def getTree(i: Int): M = trees(i)
+
   /** Weights for each tree, zippable with [[trees]] */
   def treeWeights: Array[Double]
 
diff --git a/python/pyspark/ml/classification.py b/python/pyspark/ml/classification.py
index 63925dd8653f..c6e9a9c168d2 100644
--- a/python/pyspark/ml/classification.py
+++ b/python/pyspark/ml/classification.py
@@ -22,6 +22,7 @@ import uuid
 import warnings
 from abc import ABCMeta, abstractmethod
 from multiprocessing.pool import ThreadPool
+from functools import cached_property
 from typing import (
     Any,
     Dict,
@@ -2290,10 +2291,15 @@ class RandomForestClassificationModel(
         """
         return self._call_java("featureImportances")
 
-    @property
+    @cached_property
     @since("2.0.0")
     def trees(self) -> List[DecisionTreeClassificationModel]:
         """Trees in this ensemble. Warning: These have null parent Estimators."""
+        if is_remote():
+            n = self.getNumTrees
+            return [
+                DecisionTreeClassificationModel(self._call_java("getTree", i)) for i in range(n)
+            ]
         return [DecisionTreeClassificationModel(m) for m in list(self._call_java("trees"))]
 
     @property
@@ -2778,10 +2784,13 @@ class GBTClassificationModel(
         """
         return self._call_java("featureImportances")
 
-    @property
+    @cached_property
     @since("2.0.0")
     def trees(self) -> List[DecisionTreeRegressionModel]:
         """Trees in this ensemble. Warning: These have null parent Estimators."""
+        if is_remote():
+            n = self.getNumTrees
+            return [DecisionTreeRegressionModel(self._call_java("getTree", i)) for i in range(n)]
         return [DecisionTreeRegressionModel(m) for m in list(self._call_java("trees"))]
 
     def evaluateEachIteration(self, dataset: DataFrame) -> List[float]:
diff --git a/python/pyspark/ml/clustering.py b/python/pyspark/ml/clustering.py
index 74c9d8705796..d871cf3c0095 100644
--- a/python/pyspark/ml/clustering.py
+++ b/python/pyspark/ml/clustering.py
@@ -18,6 +18,7 @@
 import sys
 import warnings
 from typing import Any, Dict, List, Optional, TYPE_CHECKING
+import functools
 
 import numpy as np
 
@@ -51,6 +52,7 @@ from pyspark.ml.common import inherit_doc, _java2py
 from pyspark.ml.stat import MultivariateGaussian
 from pyspark.sql import DataFrame
 from pyspark.ml.linalg import Vector, Matrix
+from pyspark.sql.utils import is_remote
 
 if TYPE_CHECKING:
     from pyspark.ml._typing import M
@@ -1542,6 +1544,7 @@ class DistributedLDAModel(LDAModel, JavaMLReadable["DistributedLDAModel"], JavaM
     .. versionadded:: 2.0.0
     """
 
+    @functools.cache
     @since("2.0.0")
     def toLocal(self) -> "LocalLDAModel":
         """
@@ -1551,6 +1554,8 @@ class DistributedLDAModel(LDAModel, JavaMLReadable["DistributedLDAModel"], JavaM
         .. warning:: This involves collecting a large :py:func:`topicsMatrix` to the driver.
         """
         model = LocalLDAModel(self._call_java("toLocal"))
+        if is_remote():
+            return model
 
         # SPARK-10931: Temporary fix to be removed once LDAModel defines Params
         model._create_params_from_java()
diff --git a/python/pyspark/ml/regression.py b/python/pyspark/ml/regression.py
index 85800518473d..21080d90344a 100644
--- a/python/pyspark/ml/regression.py
+++ b/python/pyspark/ml/regression.py
@@ -18,6 +18,7 @@
 import sys
 from typing import Any, Dict, Generic, List, Optional, TypeVar, TYPE_CHECKING
 from abc import ABCMeta
+from functools import cached_property
 
 from pyspark import keyword_only, since
 from pyspark.ml import Predictor, PredictionModel
@@ -71,6 +72,7 @@ from pyspark.ml.wrapper import (
 )
 from pyspark.ml.common import inherit_doc
 from pyspark.sql import DataFrame
+from pyspark.sql.utils import is_remote
 
 if TYPE_CHECKING:
     from py4j.java_gateway import JavaObject
@@ -1601,10 +1603,13 @@ class RandomForestRegressionModel(
     .. versionadded:: 1.4.0
     """
 
-    @property
+    @cached_property
     @since("2.0.0")
     def trees(self) -> List[DecisionTreeRegressionModel]:
         """Trees in this ensemble. Warning: These have null parent Estimators."""
+        if is_remote():
+            n = self.getNumTrees
+            return [DecisionTreeRegressionModel(self._call_java("getTree", i)) for i in range(n)]
         return [DecisionTreeRegressionModel(m) for m in list(self._call_java("trees"))]
 
     @property
@@ -1990,10 +1995,13 @@ class GBTRegressionModel(
         """
         return self._call_java("featureImportances")
 
-    @property
+    @cached_property
     @since("2.0.0")
     def trees(self) -> List[DecisionTreeRegressionModel]:
         """Trees in this ensemble. Warning: These have null parent Estimators."""
+        if is_remote():
+            n = self.getNumTrees
+            return [DecisionTreeRegressionModel(self._call_java("getTree", i)) for i in range(n)]
         return [DecisionTreeRegressionModel(m) for m in list(self._call_java("trees"))]
 
     def evaluateEachIteration(self, dataset: DataFrame, loss: str) -> List[float]:
diff --git a/python/pyspark/ml/tests/test_classification.py b/python/pyspark/ml/tests/test_classification.py
index 0bcf680933ef..a5b4238b38ee 100644
--- a/python/pyspark/ml/tests/test_classification.py
+++ b/python/pyspark/ml/tests/test_classification.py
@@ -53,6 +53,7 @@ from pyspark.ml.classification import (
     MultilayerPerceptronClassificationSummary,
     MultilayerPerceptronClassificationTrainingSummary,
 )
+from pyspark.ml.regression import DecisionTreeRegressionModel
 
 
 class ClassificationTestsMixin:
@@ -683,6 +684,17 @@ class ClassificationTestsMixin:
         self.assertEqual(output.columns, expected_cols)
         self.assertEqual(output.count(), 4)
 
+        trees = model.trees
+        self.assertEqual(len(trees), 3)
+        for tree in trees:
+            self.assertIsInstance(tree, DecisionTreeRegressionModel)
+            self.assertTrue(tree.predict(vec) > -10)
+            self.assertEqual(tree.transform(df).count(), 4)
+            self.assertEqual(
+                tree.transform(df).columns,
+                ["label", "weight", "features", "prediction", "leaf"],
+            )
+
         # save & load
         with tempfile.TemporaryDirectory(prefix="gbt_classification") as d:
             gbt.write().overwrite().save(d)
@@ -726,8 +738,6 @@ class ClassificationTestsMixin:
         self.assertEqual(rf.uid, model.uid)
         self.assertEqual(model.numClasses, 2)
         self.assertEqual(model.numFeatures, 2)
-        # TODO(SPARK-50843): Support access submodel in TreeEnsembleModel
-        # model.trees
         self.assertEqual(model.treeWeights, [1.0, 1.0, 1.0])
         self.assertEqual(model.totalNumNodes, 9)
         self.assertTrue(np.allclose(model.featureImportances, [0.7778, 0.2222], atol=1e-4))
@@ -753,6 +763,14 @@ class ClassificationTestsMixin:
         self.assertEqual(output.columns, expected_cols)
         self.assertEqual(output.count(), 4)
 
+        trees = model.trees
+        self.assertEqual(len(trees), 3)
+        for tree in trees:
+            self.assertIsInstance(tree, DecisionTreeClassificationModel)
+            self.assertTrue(tree.predict(vec) > -10)
+            self.assertEqual(tree.transform(df).count(), 4)
+            self.assertEqual(tree.transform(df).columns, expected_cols)
+
         # model summary
         summary = model.summary
         self.assertTrue(isinstance(summary, BinaryRandomForestClassificationSummary))
@@ -813,8 +831,7 @@ class ClassificationTestsMixin:
         self.assertEqual(rf.uid, model.uid)
         self.assertEqual(model.numClasses, 3)
         self.assertEqual(model.numFeatures, 2)
-        # TODO(SPARK-50843): Support access submodel in TreeEnsembleModel
-        # model.trees
+        self.assertEqual(len(model.trees), 3)
         self.assertEqual(model.treeWeights, [1.0, 1.0, 1.0])
         self.assertEqual(model.totalNumNodes, 9)
         self.assertEqual(model.featureImportances, Vectors.sparse(2, [0], [1.0]))
diff --git a/python/pyspark/ml/tests/test_clustering.py b/python/pyspark/ml/tests/test_clustering.py
index 380342e337a0..b4c3c8d47e21 100644
--- a/python/pyspark/ml/tests/test_clustering.py
+++ b/python/pyspark/ml/tests/test_clustering.py
@@ -371,6 +371,7 @@ class ClusteringTestsMixin:
         self.assertIsInstance(model, LDAModel)
         self.assertNotIsInstance(model, LocalLDAModel)
         self.assertIsInstance(model, DistributedLDAModel)
+        self.assertTrue(model.isDistributed())
 
         dc = model.estimatedDocConcentration()
         self.assertTrue(np.allclose(dc.toArray(), [26.0, 26.0], atol=1e-4), dc)
@@ -403,6 +404,17 @@ class ClusteringTestsMixin:
         self.assertEqual(output.columns, expected_cols)
         self.assertEqual(output.count(), 2)
 
+        # Test toLocal()
+        localModel = model.toLocal()
+        self.assertIsInstance(localModel, LDAModel)
+        self.assertIsInstance(localModel, LocalLDAModel)
+        self.assertNotIsInstance(localModel, DistributedLDAModel)
+        self.assertFalse(localModel.isDistributed())
+        output = localModel.transform(df)
+        expected_cols = ["id", "features", "topicDistribution"]
+        self.assertEqual(output.columns, expected_cols)
+        self.assertEqual(output.count(), 2)
+
         # save & load
         with tempfile.TemporaryDirectory(prefix="distributed_lda") as d:
             lda.write().overwrite().save(d)
diff --git a/python/pyspark/ml/tests/test_regression.py b/python/pyspark/ml/tests/test_regression.py
index f07f75ebeb6c..d450cdf3d15c 100644
--- a/python/pyspark/ml/tests/test_regression.py
+++ b/python/pyspark/ml/tests/test_regression.py
@@ -508,8 +508,6 @@ class RegressionTestsMixin:
         model = gbt.fit(df)
         self.assertEqual(gbt.uid, model.uid)
         self.assertEqual(model.numFeatures, 2)
-        # TODO(SPARK-50843): Support access submodel in TreeEnsembleModel
-        # model.trees
         self.assertEqual(model.treeWeights, [1.0, 0.1, 0.1])
         self.assertEqual(model.totalNumNodes, 15)
 
@@ -554,6 +552,17 @@ class RegressionTestsMixin:
         self.assertEqual(output.columns, expected_cols)
         self.assertEqual(output.count(), 4)
 
+        trees = model.trees
+        self.assertEqual(len(trees), 3)
+        for tree in trees:
+            self.assertIsInstance(tree, DecisionTreeRegressionModel)
+            self.assertTrue(tree.predict(vec) > -10)
+            self.assertEqual(tree.transform(df).count(), 4)
+            self.assertEqual(
+                tree.transform(df).columns,
+                ["label", "weight", "features", "prediction", "leaf"],
+            )
+
         # save & load
         with tempfile.TemporaryDirectory(prefix="gbt_regression") as d:
             gbt.write().overwrite().save(d)
@@ -584,8 +593,6 @@ class RegressionTestsMixin:
         model = rf.fit(df)
         self.assertEqual(rf.uid, model.uid)
         self.assertEqual(model.numFeatures, 2)
-        # TODO(SPARK-50843): Support access submodel in TreeEnsembleModel
-        # model.trees
         self.assertEqual(model.treeWeights, [1.0, 1.0, 1.0])
         self.assertEqual(model.totalNumNodes, 11)
 
@@ -614,6 +621,17 @@ class RegressionTestsMixin:
         self.assertEqual(output.columns, expected_cols)
         self.assertEqual(output.count(), 4)
 
+        trees = model.trees
+        self.assertEqual(len(trees), 3)
+        for tree in trees:
+            self.assertIsInstance(tree, DecisionTreeRegressionModel)
+            self.assertTrue(tree.predict(vec) > -10)
+            self.assertEqual(tree.transform(df).count(), 4)
+            self.assertEqual(
+                tree.transform(df).columns,
+                ["label", "weight", "features", "prediction", "leaf"],
+            )
+
         with tempfile.TemporaryDirectory(prefix="random_forest_regression") as d:
             rf.write().overwrite().save(d)
             rf2 = RandomForestRegressor.load(d)
diff --git a/python/pyspark/ml/util.py b/python/pyspark/ml/util.py
index 34bee0599a02..04a91cf2f8b2 100644
--- a/python/pyspark/ml/util.py
+++ b/python/pyspark/ml/util.py
@@ -219,6 +219,12 @@ def try_remote_call(f: FuncT) -> FuncT:
                 summary = ml_command_result.summary
                 session.client.add_ml_cache(summary)
                 return summary
+            elif ml_command_result.HasField("operator_info"):
+                model_info = deserialize(properties)
+                session._client.add_ml_cache(model_info.obj_ref.id)
+                # get a new model ref id from the existing model,
+                # it is up to the caller to build the model
+                return model_info.obj_ref.id
             else:
                 return deserialize(properties)
         else:
diff --git a/sql/connect/server/src/main/scala/org/apache/spark/sql/connect/ml/MLHandler.scala b/sql/connect/server/src/main/scala/org/apache/spark/sql/connect/ml/MLHandler.scala
index 8f8713d89e67..b608b75218d9 100644
--- a/sql/connect/server/src/main/scala/org/apache/spark/sql/connect/ml/MLHandler.scala
+++ b/sql/connect/server/src/main/scala/org/apache/spark/sql/connect/ml/MLHandler.scala
@@ -139,6 +139,15 @@ private[connect] object MLHandler extends Logging {
           case s: Summary =>
             val id = mlCache.register(s)
             proto.MlCommandResult.newBuilder().setSummary(id).build()
+          case m: Model[_] =>
+            val id = mlCache.register(m)
+            proto.MlCommandResult
+              .newBuilder()
+              .setOperatorInfo(
+                proto.MlCommandResult.MlOperatorInfo
+                  .newBuilder()
+                  .setObjRef(proto.ObjectRef.newBuilder().setId(id)))
+              .build()
           case _ =>
             val param = Serializer.serializeParam(attrResult)
             proto.MlCommandResult.newBuilder().setParam(param).build()
diff --git a/sql/connect/server/src/main/scala/org/apache/spark/sql/connect/ml/MLUtils.scala b/sql/connect/server/src/main/scala/org/apache/spark/sql/connect/ml/MLUtils.scala
index 3d649ee01178..acf5abd938f7 100644
--- a/sql/connect/server/src/main/scala/org/apache/spark/sql/connect/ml/MLUtils.scala
+++ b/sql/connect/server/src/main/scala/org/apache/spark/sql/connect/ml/MLUtils.scala
@@ -510,12 +510,12 @@ private[ml] object MLUtils {
       classOf[TreeEnsembleModel[_]],
       Set(
         "predictLeaf",
-        "trees",
         "treeWeights",
         "javaTreeWeights",
         "getNumTrees",
         "totalNumNodes",
-        "toDebugString")),
+        "toDebugString",
+        "getTree")),
     (classOf[DecisionTreeClassificationModel], Set("featureImportances")),
     (classOf[RandomForestClassificationModel], Set("featureImportances", "evaluate")),
     (classOf[GBTClassificationModel], Set("featureImportances", "evaluateEachIteration")),
@@ -616,7 +616,7 @@ private[ml] object MLUtils {
     (classOf[LocalLDAModel], Set("vocabSize")),
     (
       classOf[DistributedLDAModel],
-      Set("trainingLogLikelihood", "logPrior", "getCheckpointFiles")),
+      Set("trainingLogLikelihood", "logPrior", "getCheckpointFiles", "toLocal")),
 
     // Recommendation Models
     (


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@spark.apache.org
For additional commands, e-mail: commits-help@spark.apache.org