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

HyukjinKwon pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/spark-connect-rust.git


The following commit(s) were added to refs/heads/master by this push:
     new 7d77338b [SPARK-61334][CONNECT][PYTHON] Make the setters of the native 
pyspark.ml.connect classes set the value on the object and return it, as 
PySpark does
7d77338b is described below

commit 7d77338bba51ba7069b9d4b4d3295b9d38f83fab
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Tue Nov 10 17:34:41 2026 +0900

    [SPARK-61334][CONNECT][PYTHON] Make the setters of the native 
pyspark.ml.connect classes set the value on the object and return it, as 
PySpark does
    
    ### What changes were proposed in this pull request?
    
    [SPARK-61334](https://issues.apache.org/jira/browse/SPARK-61334): the 
setters of the native `pyspark.ml.connect` classes set the value on the object 
and return the object, as PySpark's do.
    
    - In `crates/pyspark-rs/src/ml.rs`, every setter of these classes now has 
the mutating form `fn set_x(mut slf: PyRefMut<Self>, value) -> PyRefMut<Self>`. 
That form is the one the native KMeans, LinearSVC and LinearRegression already 
use. The classes:
      - StandardScaler, MaxAbsScaler, StringIndexer, VectorAssembler
      - LogisticRegression
      - RegressionEvaluator, BinaryClassificationEvaluator, 
MulticlassClassificationEvaluator
      - Pipeline, CrossValidator
    - The argument is named `value`, as in PySpark's setters.
    
    ### Why are the changes needed?
    
    Those setters returned a new object and left the receiver unchanged. So a 
call whose result was not kept was silently ignored:
    - `ev = RegressionEvaluator(labelCol="label", predictionCol="pred"); 
ev.setMetricName("r2"); ev.evaluate(df)` returned the rmse.
    - `MulticlassClassificationEvaluator(...).setMetricName("accuracy")` gave 
the f1.
    - `BinaryClassificationEvaluator().setRawPredictionCol("score")`, then 
`evaluate`, failed with `FIELD_NOT_FOUND rawPrediction`.
    - `LogisticRegression().setLabelCol("y")`, then `fit`, failed on the column 
`label`.
    - `Pipeline().setStages([...])` kept no stages, and CrossValidator's 
`setNumFolds`/`setParallelism`/`setSeed` were ignored.
    
    PySpark's setters (`Params._set`, as in `pyspark.ml.connect`'s Pipeline and 
CrossValidator) set the value on the object and return it.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes, in the Python client: these setters now change the object they are 
called on, and return it, as in PySpark.
    
    ### How was this patch tested?
    
    - Offline (`python/tests/test_ml_offline.py`): 
`test_ml_connect_setters_set_the_params_of_their_receiver_as_pyspark`.
      - It covers every setter of each of the 14 native estimators, 
transformers and evaluators.
      - Each setter returns its receiver (called with the keyword `value`).
      - The next evaluate, fit or transform sends the new value, the same as an 
object built with the value in its constructor. It also checks that no setter 
of a class is left out.
      - It fails without the change.
    - Live (`python/tests/test_ml_e2e.py`): 
`test_ml_connect_setters_change_the_next_evaluate_and_fit_as_pyspark`.
    - A probe against official PySpark 4.3.0: `setMetricName`, 
`setRawPredictionCol`, `setLabelCol`, `setStages` and the CrossValidator 
setters now give official's results.
    - Checks: `test_ml_offline.py` 98 passed, `test_ml_e2e.py` 15 passed; the 
lib tests, the build of all tests (also `wasm-udf`, `datafusion,polars`) 
without warnings, `cargo fmt --all --check`, and clippy with no diagnostics on 
the changed lines.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Opus 5.5
    
    This pull request and its description were written by Isaac.
    
    Closes #460 from HyukjinKwon/s16-native-ml-setters.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/pyspark-rs/src/ml.rs     | 187 ++++++++++++++++++----------------------
 python/tests/test_ml_e2e.py     |  55 ++++++++++++
 python/tests/test_ml_offline.py | 106 +++++++++++++++++++++++
 3 files changed, 244 insertions(+), 104 deletions(-)

diff --git a/crates/pyspark-rs/src/ml.rs b/crates/pyspark-rs/src/ml.rs
index 08651bfd..a064efd1 100644
--- a/crates/pyspark-rs/src/ml.rs
+++ b/crates/pyspark-rs/src/ml.rs
@@ -2,8 +2,9 @@
 //!
 //! The core estimators/transformers/evaluators use consuming builder setters 
and
 //! `&mut self` fit/transform; every concrete type is `Clone`, so each wrapper 
holds
-//! the value and clones it for the fluent setters and for 
fit/transform/evaluate,
-//! keeping the Python objects reusable.
+//! the value and clones it for fit/transform/evaluate, keeping the Python 
objects
+//! reusable. A setter replaces the value with the result of the core setter 
and
+//! returns the wrapper itself, as PySpark's `Params._set` does.
 
 use pyo3::prelude::*;
 use spark_connect::ml::{
@@ -56,16 +57,14 @@ impl PyStandardScaler {
         PyStandardScaler { inner: e }
     }
     #[pyo3(name = "setInputCol")]
-    fn set_input_col(&self, col: &str) -> Self {
-        PyStandardScaler {
-            inner: self.inner.clone().set_input_col(col),
-        }
+    fn set_input_col<'py>(mut slf: PyRefMut<'py, Self>, value: &str) -> 
PyRefMut<'py, Self> {
+        slf.inner = slf.inner.clone().set_input_col(value);
+        slf
     }
     #[pyo3(name = "setOutputCol")]
-    fn set_output_col(&self, col: &str) -> Self {
-        PyStandardScaler {
-            inner: self.inner.clone().set_output_col(col),
-        }
+    fn set_output_col<'py>(mut slf: PyRefMut<'py, Self>, value: &str) -> 
PyRefMut<'py, Self> {
+        slf.inner = slf.inner.clone().set_output_col(value);
+        slf
     }
     fn fit(&self, py: Python<'_>, df: &PyDataFrame) -> PyResult<PyMLModel> {
         let mut e = self.inner.clone();
@@ -98,16 +97,14 @@ impl PyMaxAbsScaler {
         PyMaxAbsScaler { inner: e }
     }
     #[pyo3(name = "setInputCol")]
-    fn set_input_col(&self, col: &str) -> Self {
-        PyMaxAbsScaler {
-            inner: self.inner.clone().set_input_col(col),
-        }
+    fn set_input_col<'py>(mut slf: PyRefMut<'py, Self>, value: &str) -> 
PyRefMut<'py, Self> {
+        slf.inner = slf.inner.clone().set_input_col(value);
+        slf
     }
     #[pyo3(name = "setOutputCol")]
-    fn set_output_col(&self, col: &str) -> Self {
-        PyMaxAbsScaler {
-            inner: self.inner.clone().set_output_col(col),
-        }
+    fn set_output_col<'py>(mut slf: PyRefMut<'py, Self>, value: &str) -> 
PyRefMut<'py, Self> {
+        slf.inner = slf.inner.clone().set_output_col(value);
+        slf
     }
     fn fit(&self, py: Python<'_>, df: &PyDataFrame) -> PyResult<PyMLModel> {
         let mut e = self.inner.clone();
@@ -140,16 +137,14 @@ impl PyStringIndexer {
         PyStringIndexer { inner: e }
     }
     #[pyo3(name = "setInputCol")]
-    fn set_input_col(&self, col: &str) -> Self {
-        PyStringIndexer {
-            inner: self.inner.clone().set_input_col(col),
-        }
+    fn set_input_col<'py>(mut slf: PyRefMut<'py, Self>, value: &str) -> 
PyRefMut<'py, Self> {
+        slf.inner = slf.inner.clone().set_input_col(value);
+        slf
     }
     #[pyo3(name = "setOutputCol")]
-    fn set_output_col(&self, col: &str) -> Self {
-        PyStringIndexer {
-            inner: self.inner.clone().set_output_col(col),
-        }
+    fn set_output_col<'py>(mut slf: PyRefMut<'py, Self>, value: &str) -> 
PyRefMut<'py, Self> {
+        slf.inner = slf.inner.clone().set_output_col(value);
+        slf
     }
     fn fit(&self, py: Python<'_>, df: &PyDataFrame) -> PyResult<PyMLModel> {
         let mut e = self.inner.clone();
@@ -183,17 +178,15 @@ impl PyVectorAssembler {
         PyVectorAssembler { inner: t }
     }
     #[pyo3(name = "setInputCols")]
-    fn set_input_cols(&self, cols: Vec<String>) -> Self {
-        let refs: Vec<&str> = cols.iter().map(|s| s.as_str()).collect();
-        PyVectorAssembler {
-            inner: self.inner.clone().set_input_cols(refs),
-        }
+    fn set_input_cols(mut slf: PyRefMut<'_, Self>, value: Vec<String>) -> 
PyRefMut<'_, Self> {
+        let refs: Vec<&str> = value.iter().map(|s| s.as_str()).collect();
+        slf.inner = slf.inner.clone().set_input_cols(refs);
+        slf
     }
     #[pyo3(name = "setOutputCol")]
-    fn set_output_col(&self, col: &str) -> Self {
-        PyVectorAssembler {
-            inner: self.inner.clone().set_output_col(col),
-        }
+    fn set_output_col<'py>(mut slf: PyRefMut<'py, Self>, value: &str) -> 
PyRefMut<'py, Self> {
+        slf.inner = slf.inner.clone().set_output_col(value);
+        slf
     }
     fn transform(&self, py: Python<'_>, df: &PyDataFrame) -> 
PyResult<PyDataFrame> {
         let mut t = self.inner.clone();
@@ -240,28 +233,24 @@ impl PyLogisticRegression {
         PyLogisticRegression { inner: e }
     }
     #[pyo3(name = "setFeaturesCol")]
-    fn set_features_col(&self, col: &str) -> Self {
-        PyLogisticRegression {
-            inner: self.inner.clone().set_feature_col(col),
-        }
+    fn set_features_col<'py>(mut slf: PyRefMut<'py, Self>, value: &str) -> 
PyRefMut<'py, Self> {
+        slf.inner = slf.inner.clone().set_feature_col(value);
+        slf
     }
     #[pyo3(name = "setLabelCol")]
-    fn set_label_col(&self, col: &str) -> Self {
-        PyLogisticRegression {
-            inner: self.inner.clone().set_label_col(col),
-        }
+    fn set_label_col<'py>(mut slf: PyRefMut<'py, Self>, value: &str) -> 
PyRefMut<'py, Self> {
+        slf.inner = slf.inner.clone().set_label_col(value);
+        slf
     }
     #[pyo3(name = "setPredictionCol")]
-    fn set_prediction_col(&self, col: &str) -> Self {
-        PyLogisticRegression {
-            inner: self.inner.clone().set_prediction_col(col),
-        }
+    fn set_prediction_col<'py>(mut slf: PyRefMut<'py, Self>, value: &str) -> 
PyRefMut<'py, Self> {
+        slf.inner = slf.inner.clone().set_prediction_col(value);
+        slf
     }
     #[pyo3(name = "setMaxIter")]
-    fn set_max_iter(&self, max_iter: i64) -> Self {
-        PyLogisticRegression {
-            inner: self.inner.clone().set_max_iter(max_iter),
-        }
+    fn set_max_iter(mut slf: PyRefMut<'_, Self>, value: i64) -> PyRefMut<'_, 
Self> {
+        slf.inner = slf.inner.clone().set_max_iter(value);
+        slf
     }
     fn fit(&self, py: Python<'_>, df: &PyDataFrame) -> PyResult<PyMLModel> {
         let mut e = self.inner.clone();
@@ -710,22 +699,19 @@ impl PyRegressionEvaluator {
         PyRegressionEvaluator { inner: e }
     }
     #[pyo3(name = "setLabelCol")]
-    fn set_label_col(&self, col: &str) -> Self {
-        PyRegressionEvaluator {
-            inner: self.inner.clone().set_label_col(col),
-        }
+    fn set_label_col<'py>(mut slf: PyRefMut<'py, Self>, value: &str) -> 
PyRefMut<'py, Self> {
+        slf.inner = slf.inner.clone().set_label_col(value);
+        slf
     }
     #[pyo3(name = "setPredictionCol")]
-    fn set_prediction_col(&self, col: &str) -> Self {
-        PyRegressionEvaluator {
-            inner: self.inner.clone().set_prediction_col(col),
-        }
+    fn set_prediction_col<'py>(mut slf: PyRefMut<'py, Self>, value: &str) -> 
PyRefMut<'py, Self> {
+        slf.inner = slf.inner.clone().set_prediction_col(value);
+        slf
     }
     #[pyo3(name = "setMetricName")]
-    fn set_metric_name(&self, metric: &str) -> Self {
-        PyRegressionEvaluator {
-            inner: self.inner.clone().set_metric_name(metric),
-        }
+    fn set_metric_name<'py>(mut slf: PyRefMut<'py, Self>, value: &str) -> 
PyRefMut<'py, Self> {
+        slf.inner = slf.inner.clone().set_metric_name(value);
+        slf
     }
     fn evaluate(&self, py: Python<'_>, df: &PyDataFrame) -> PyResult<f64> {
         interruptible(py, &df.dataframe.spark_session(), || {
@@ -766,22 +752,22 @@ impl PyBinaryClassificationEvaluator {
         PyBinaryClassificationEvaluator { inner: e }
     }
     #[pyo3(name = "setLabelCol")]
-    fn set_label_col(&self, col: &str) -> Self {
-        PyBinaryClassificationEvaluator {
-            inner: self.inner.clone().set_label_col(col),
-        }
+    fn set_label_col<'py>(mut slf: PyRefMut<'py, Self>, value: &str) -> 
PyRefMut<'py, Self> {
+        slf.inner = slf.inner.clone().set_label_col(value);
+        slf
     }
     #[pyo3(name = "setRawPredictionCol")]
-    fn set_raw_prediction_col(&self, col: &str) -> Self {
-        PyBinaryClassificationEvaluator {
-            inner: self.inner.clone().set_raw_prediction_col(col),
-        }
+    fn set_raw_prediction_col<'py>(
+        mut slf: PyRefMut<'py, Self>,
+        value: &str,
+    ) -> PyRefMut<'py, Self> {
+        slf.inner = slf.inner.clone().set_raw_prediction_col(value);
+        slf
     }
     #[pyo3(name = "setMetricName")]
-    fn set_metric_name(&self, metric: &str) -> Self {
-        PyBinaryClassificationEvaluator {
-            inner: self.inner.clone().set_metric_name(metric),
-        }
+    fn set_metric_name<'py>(mut slf: PyRefMut<'py, Self>, value: &str) -> 
PyRefMut<'py, Self> {
+        slf.inner = slf.inner.clone().set_metric_name(value);
+        slf
     }
     fn evaluate(&self, py: Python<'_>, df: &PyDataFrame) -> PyResult<f64> {
         interruptible(py, &df.dataframe.spark_session(), || {
@@ -809,11 +795,10 @@ impl PyPipeline {
         PyPipeline { inner: p }
     }
     #[pyo3(name = "setStages")]
-    fn set_stages(&self, stages: Vec<String>) -> Self {
-        let refs: Vec<&str> = stages.iter().map(|x| x.as_str()).collect();
-        PyPipeline {
-            inner: self.inner.clone().set_stages(refs),
-        }
+    fn set_stages(mut slf: PyRefMut<'_, Self>, value: Vec<String>) -> 
PyRefMut<'_, Self> {
+        let refs: Vec<&str> = value.iter().map(|x| x.as_str()).collect();
+        slf.inner = slf.inner.clone().set_stages(refs);
+        slf
     }
     fn fit(&self, py: Python<'_>, df: &PyDataFrame) -> PyResult<PyMLModel> {
         let mut e = self.inner.clone();
@@ -856,22 +841,19 @@ impl PyMulticlassClassificationEvaluator {
         PyMulticlassClassificationEvaluator { inner: e }
     }
     #[pyo3(name = "setLabelCol")]
-    fn set_label_col(&self, col: &str) -> Self {
-        PyMulticlassClassificationEvaluator {
-            inner: self.inner.clone().set_label_col(col),
-        }
+    fn set_label_col<'py>(mut slf: PyRefMut<'py, Self>, value: &str) -> 
PyRefMut<'py, Self> {
+        slf.inner = slf.inner.clone().set_label_col(value);
+        slf
     }
     #[pyo3(name = "setPredictionCol")]
-    fn set_prediction_col(&self, col: &str) -> Self {
-        PyMulticlassClassificationEvaluator {
-            inner: self.inner.clone().set_prediction_col(col),
-        }
+    fn set_prediction_col<'py>(mut slf: PyRefMut<'py, Self>, value: &str) -> 
PyRefMut<'py, Self> {
+        slf.inner = slf.inner.clone().set_prediction_col(value);
+        slf
     }
     #[pyo3(name = "setMetricName")]
-    fn set_metric_name(&self, metric: &str) -> Self {
-        PyMulticlassClassificationEvaluator {
-            inner: self.inner.clone().set_metric_name(metric),
-        }
+    fn set_metric_name<'py>(mut slf: PyRefMut<'py, Self>, value: &str) -> 
PyRefMut<'py, Self> {
+        slf.inner = slf.inner.clone().set_metric_name(value);
+        slf
     }
     fn evaluate(&self, py: Python<'_>, df: &PyDataFrame) -> PyResult<f64> {
         interruptible(py, &df.dataframe.spark_session(), || {
@@ -905,22 +887,19 @@ impl PyCrossValidator {
         PyCrossValidator { inner: e }
     }
     #[pyo3(name = "setNumFolds")]
-    fn set_num_folds(&self, num_folds: i32) -> Self {
-        PyCrossValidator {
-            inner: self.inner.clone().set_num_folds(num_folds),
-        }
+    fn set_num_folds(mut slf: PyRefMut<'_, Self>, value: i32) -> PyRefMut<'_, 
Self> {
+        slf.inner = slf.inner.clone().set_num_folds(value);
+        slf
     }
     #[pyo3(name = "setParallelism")]
-    fn set_parallelism(&self, parallelism: i32) -> Self {
-        PyCrossValidator {
-            inner: self.inner.clone().set_parallelism(parallelism),
-        }
+    fn set_parallelism(mut slf: PyRefMut<'_, Self>, value: i32) -> 
PyRefMut<'_, Self> {
+        slf.inner = slf.inner.clone().set_parallelism(value);
+        slf
     }
     #[pyo3(name = "setSeed")]
-    fn set_seed(&self, seed: i64) -> Self {
-        PyCrossValidator {
-            inner: self.inner.clone().set_seed(seed),
-        }
+    fn set_seed(mut slf: PyRefMut<'_, Self>, value: i64) -> PyRefMut<'_, Self> 
{
+        slf.inner = slf.inner.clone().set_seed(value);
+        slf
     }
     fn fit(&self, py: Python<'_>, df: &PyDataFrame) -> PyResult<PyMLModel> {
         let mut e = self.inner.clone();
diff --git a/python/tests/test_ml_e2e.py b/python/tests/test_ml_e2e.py
index 5bfac6a4..28cbc4f9 100644
--- a/python/tests/test_ml_e2e.py
+++ b/python/tests/test_ml_e2e.py
@@ -214,6 +214,61 @@ def 
test_ml_connect_vector_assembler_and_evaluator_as_pyspark(session):
     assert pr.evaluate(raw) == pytest.approx(0.7916666666666666)
 
 
+def 
test_ml_connect_setters_change_the_next_evaluate_and_fit_as_pyspark(session):
+    # As PySpark's Params._set: a setter of pyspark.ml.connect sets the param 
of the evaluator or
+    # estimator itself and returns it, so the next evaluate or fit uses the 
value of a setter whose
+    # result is dropped, with the values of PySpark 4.3.0.
+    import pyspark.sql.connect.proto as pb2
+    from pyspark.ml.connect.classification import LogisticRegression
+    from pyspark.ml.connect.evaluation import (
+        BinaryClassificationEvaluator,
+        MulticlassClassificationEvaluator,
+        RegressionEvaluator,
+    )
+    from pyspark.ml.connect.pipeline import Pipeline
+    from pyspark.ml.linalg import Vectors
+
+    scored = session.createDataFrame(
+        [
+            (Vectors.dense([0.9, 0.1]), 0.0, 0.0),
+            (Vectors.dense([0.6, 0.4]), 0.0, 1.0),
+            (Vectors.dense([0.65, 0.35]), 1.0, 1.0),
+            (Vectors.dense([0.2, 0.8]), 1.0, 1.0),
+        ],
+        ["score", "label", "pred"],
+    )
+    regression = RegressionEvaluator(labelCol="label", predictionCol="pred")
+    assert regression.setMetricName("r2") is regression
+    assert regression.evaluate(scored) == pytest.approx(0.0, abs=1e-9)  # The 
rmse is 0.5.
+    multiclass = MulticlassClassificationEvaluator(predictionCol="pred")
+    assert multiclass.setMetricName("accuracy") is multiclass
+    assert multiclass.evaluate(scored) == 0.75  # The f1 is 0.733.
+    binary = BinaryClassificationEvaluator()
+    assert binary.setRawPredictionCol("score") is binary  # No rawPrediction 
column is there.
+    assert binary.evaluate(scored) == 0.75
+    assert binary.setMetricName("areaUnderPR") is binary
+    assert binary.evaluate(scored) == pytest.approx(0.7916666666666666)
+
+    features = [[0.0, 1.0], [1.0, 0.0], [2.0, 1.5], [0.5, 0.2]]
+    labels = [0.0, 1.0, 1.0, 0.0]
+    labeled = session.createDataFrame(
+        [(i, y, Vectors.dense(f)) for i, (y, f) in enumerate(zip(labels, 
features))],
+        ["id", "y", "features"],
+    )
+    estimator = LogisticRegression()
+    assert estimator.setLabelCol("y") is estimator  # No label column is there.
+    predictions = 
estimator.fit(labeled).transform(labeled).orderBy("id").collect()
+    assert [r.prediction for r in predictions] == labels
+
+    # The server transforms no native Pipeline of stage names: the stages of 
the setter are
+    # those that the transform of its model sends.
+    pipeline = Pipeline()
+    assert pipeline.setStages(["a", "b"]) is pipeline
+    relation = 
pb2.Relation.FromString(pipeline.fit(labeled).transform(labeled)._relation_bytes())
+    stages = 
relation.ml_relation.transform.params.params["stages"].array.elements
+    assert [stage.string for stage in stages] == ["a", "b"]
+
+
 def test_ml_statistics_as_pyspark(session):
     from pyspark.ml.stat import ChiSquareTest, Correlation, Summarizer
 
diff --git a/python/tests/test_ml_offline.py b/python/tests/test_ml_offline.py
index f6102c7e..ee93947f 100644
--- a/python/tests/test_ml_offline.py
+++ b/python/tests/test_ml_offline.py
@@ -181,6 +181,112 @@ def 
test_ml_connect_fitted_scalers_transform_the_cached_model(ml_mock):
         assert transform.params.params["outputCol"] == 
pb2.Expression.Literal(string="o")
 
 
+def 
test_ml_connect_setters_set_the_params_of_their_receiver_as_pyspark(ml_mock):
+    # As PySpark's Params._set: every setter of the native pyspark.ml.connect 
estimators,
+    # transformers and evaluators sets its param on the object itself and 
returns the object, so
+    # the next fit, transform or evaluate sends the value of a setter whose 
result is dropped,
+    # as the object of the constructor of the same params sends it.
+    from pyspark.ml.connect import (
+        BinaryClassificationEvaluator,
+        CrossValidator,
+        KMeans,
+        LinearRegression,
+        LinearSVC,
+        LogisticRegression,
+        MaxAbsScaler,
+        MulticlassClassificationEvaluator,
+        Pipeline,
+        RegressionEvaluator,
+        StandardScaler,
+        StringIndexer,
+        VectorAssembler,
+    )
+
+    spark, service = ml_mock
+    df = spark.range(1)
+    models = []  # Kept alive, so that no model is released during the checks.
+
+    def value(literal):
+        kind = literal.WhichOneof("literal_type")
+        if kind == "array":
+            return [value(element) for element in literal.array.elements]
+        return getattr(literal, kind)
+
+    def sent_params(obj):
+        # The values of the params that the next evaluate, fit or transform of 
obj sends.
+        sent = len(service.execute_requests)
+        if hasattr(obj, "evaluate"):
+            service.execute_payload = 
_ml_result(param=pb2.Expression.Literal(double=0.5))
+            assert obj.evaluate(df) == 0.5
+            params = _commands(service)[sent].ml_command.evaluate.params
+        elif hasattr(obj, "fit"):
+            service.execute_payload = _operator_info("model-1")
+            models.append(obj.fit(df))
+            if len(service.execute_requests) > sent:
+                params = _commands(service)[sent].ml_command.fit.params
+            else:
+                # Pipeline and CrossValidator fit no object of the server: the 
transform of their
+                # model sends the params.
+                params = 
_relation(models[-1].transform(df)).ml_relation.transform.params
+        else:
+            params = _relation(obj.transform(df)).ml_relation.transform.params
+        return {name: value(literal) for name, literal in 
params.params.items()}
+
+    for cls, values in [
+        (StandardScaler, dict(inputCol="in", outputCol="out")),
+        (MaxAbsScaler, dict(inputCol="in", outputCol="out")),
+        (StringIndexer, dict(inputCol="in", outputCol="out")),
+        (VectorAssembler, dict(inputCols=["a", "b"], outputCol="out")),
+        (LogisticRegression, dict(featuresCol="f", labelCol="y", 
predictionCol="p", maxIter=7)),
+        (
+            LinearSVC,
+            dict(
+                featuresCol="f", labelCol="y", predictionCol="p", maxIter=7, 
regParam=0.5,
+                tol=0.25, rawPredictionCol="r", fitIntercept=False, 
standardization=False,
+                threshold=0.5, weightCol="w", aggregationDepth=3, 
maxBlockSizeInMB=1.5,
+            ),
+        ),
+        (
+            LinearRegression,
+            dict(
+                featuresCol="f", labelCol="y", predictionCol="p", maxIter=7, 
regParam=0.5,
+                elasticNetParam=0.25, tol=0.125, fitIntercept=False, 
standardization=False,
+                solver="normal", weightCol="w", aggregationDepth=3, 
loss="huber", epsilon=1.5,
+                maxBlockSizeInMB=1.5,
+            ),
+        ),
+        (
+            KMeans,
+            dict(
+                featuresCol="f", predictionCol="p", k=3, initMode="random", 
initSteps=3,
+                tol=0.5, maxIter=7, seed=5, distanceMeasure="cosine", 
weightCol="w",
+                solver="row", maxBlockSizeInMB=1.5,
+            ),
+        ),
+        (RegressionEvaluator, dict(labelCol="y", predictionCol="p", 
metricName="r2")),
+        (
+            BinaryClassificationEvaluator,
+            dict(labelCol="y", rawPredictionCol="r", metricName="areaUnderPR"),
+        ),
+        (
+            MulticlassClassificationEvaluator,
+            dict(labelCol="y", predictionCol="p", metricName="accuracy"),
+        ),
+        (Pipeline, dict(stages=["a", "b"])),
+        (CrossValidator, dict(numFolds=5, parallelism=2, seed=7)),
+    ]:
+        setters = {"set" + name[0].upper() + name[1:]: name for name in values}
+        # Every setter of the class is checked.
+        assert sorted(n for n in dir(cls) if n.startswith("set")) == 
sorted(setters)
+        receiver = cls()
+        for setter, name in setters.items():
+            # By the name of the argument of PySpark's setters, value.
+            assert getattr(receiver, setter)(value=values[name]) is receiver, 
(cls, setter)
+        params = sent_params(receiver)
+        assert {name: params.get(name) for name in values} == values, cls
+        assert params == sent_params(cls(**values)), cls
+
+
 @pytest.mark.parametrize(
     "value, expected",
     [


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to