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 bc20aaef [SPARK-61531][CONNECT][PYTHON] Let the native evaluators take 
the numeric and array columns and the pandas DataFrames that PySpark's 
evaluators take
bc20aaef is described below

commit bc20aaef99a4b86a4354d92d322cede4c7e00662
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Thu Nov 12 20:31:01 2026 +0900

    [SPARK-61531][CONNECT][PYTHON] Let the native evaluators take the numeric 
and array columns and the pandas DataFrames that PySpark's evaluators take
    
    ### What changes were proposed in this pull request?
    
    A follow-up of #550 (SPARK-61417), from a review of it. That commit fixed 
the docstring example of `BinaryClassificationEvaluator`, whose probabilities 
are doubles. Its sibling cases still failed.
    
    PySpark's `pyspark.ml.connect` evaluators compute with torch on the client, 
and read their columns as tensors:
    - int labels and predictions;
    - float32 or array probabilities. The column 1 of a 2-D array is the 
positive class (`evaluation.py`).
    - A pandas DataFrame is evaluated locally (`aggregate_dataframe`).
    
    The native evaluators of this client sent the DataFrame unchanged to 
Spark's JVM evaluators. Those require a double prediction, and a double or 
vector raw prediction.
    
    In `crates/pyspark-rs/src/ml.rs`, the `evaluate` of `RegressionEvaluator`, 
`BinaryClassificationEvaluator` and `MulticlassClassificationEvaluator` now:
    - takes `dataset`, PySpark's name of the argument, which was `df`. It 
accepts a DataFrame, or a pandas DataFrame, which is sent through 
`createDataFrame` of the active session, as these evaluators run on the server. 
Another object raises the `AttributeError` of the `select` that PySpark's 
`aggregate_dataframe` calls on it.
    - reads the schema of the dataset, and casts a prediction (regression, 
multiclass) or a probability (binary) of another numeric type to a double.
    - sends an array probability as a vector, by `array_to_vector`. The JVM 
evaluator reads the vector at its element 1, as PySpark's reads the column 1 of 
the array.
    
    Columns are found regardless of case, as Spark resolves them. Other types 
are sent as they are, for the JVM evaluator to check.
    
    `docs/compatibility.md`:
    - `setProbabilityCol` is a setter of this client, since PySpark's 
evaluators have none.
    - A model without a probability column, such as the native `LinearSVC`, is 
scored with `probabilityCol="rawPrediction"`.
    - The evaluators take pandas DataFrames and the column types above.
    - The values are the JVM's doubles: `0.6` where PySpark's float32 tensors 
give `0.6000000238418579`.
    - The native scalers take vector features, as the native estimators already 
do, where PySpark's take arrays.
    
    The comment of a setter test in `test_ml_offline.py` now says the same 
about the evaluators' setters.
    
    ### Why are the changes needed?
    
    PySpark's own inputs failed:
    - The docstring of `MulticlassClassificationEvaluator`, and 
`test_legacy_mode_evaluation.py`, use int columns: `IllegalArgumentException: 
requirement failed: Column prediction must be of type ... DoubleType ... but 
was actually ... LongType`.
    - The `prob2` array<double> column of its binary test, and a float32 
probability: `Column prob2 must be of type equal to one of the following types: 
[double, struct<...>] but was actually of type array<double>`.
    - A pandas DataFrame: `TypeError: argument 'df': 'DataFrame' object is not 
an instance of 'DataFrame'`.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes. These evaluators now evaluate int, float32 and array columns, and 
pandas DataFrames, as PySpark's do. `evaluate(dataset=...)` works by keyword.
    
    ### How was this patch tested?
    
    
`test_ml_connect_evaluators_take_the_columns_and_the_pandas_frames_of_pyspark_tests`
 (`python/tests/test_ml_e2e.py`, new) runs against a Spark 4.3.0 server. It 
uses the inputs of PySpark's tests and docstrings:
    - multiclass accuracy 0.6 on int columns, also from pandas;
    - regression MSE on an int prediction;
    - binary AUROC and AUPRC of the array `prob2` and of a float32 probability, 
equal to those of the double probability. AUROC is 2/3, also from pandas.
    - the `AttributeError` of a list.
    
    It fails without the change with the `LongType` error above. Also run: 
`test_ml_offline.py` (118 passed), the other e2e evaluator tests, `cargo build 
-p pyspark-rs --release`, `cargo fmt --all --check` and `ruff check`.
    
    ### 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 #563 from HyukjinKwon/SPARK-61531-ml-evaluators.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/pyspark-rs/src/ml.rs     | 124 +++++++++++++++++++++++++++++++++++++---
 docs/compatibility.md           |  18 ++++--
 python/tests/test_ml_e2e.py     |  54 +++++++++++++++++
 python/tests/test_ml_offline.py |   3 +-
 4 files changed, 185 insertions(+), 14 deletions(-)

diff --git a/crates/pyspark-rs/src/ml.rs b/crates/pyspark-rs/src/ml.rs
index b2d5969c..07f90d7f 100644
--- a/crates/pyspark-rs/src/ml.rs
+++ b/crates/pyspark-rs/src/ml.rs
@@ -295,17 +295,108 @@ fn fit_core<C: Estimator>(
     })
 }
 
-fn evaluate_native<T>(slf: &Bound<'_, T>, df: &PyDataFrame) -> PyResult<f64>
+/// The input columns of an evaluator, as the JVM evaluator reads them: 
`doubles`, a prediction
+/// that it reads as a double only, and `score`, a probability that it reads 
as a double or a
+/// vector, where PySpark's evaluators read any numeric column, and an array, 
as a tensor.
+struct EvaluatorInputs {
+    doubles: Vec<String>,
+    score: Option<String>,
+}
+
+/// Evaluate `dataset` with the JVM evaluator of `slf`, whose input columns 
`inputs` gives, as
+/// PySpark's evaluators evaluate it (see [`evaluation_dataset`] and 
[`evaluator_input`]).
+fn evaluate_native<T>(
+    slf: &Bound<'_, T>,
+    dataset: &Bound<'_, PyAny>,
+    inputs: impl FnOnce(&T::Core) -> EvaluatorInputs,
+) -> PyResult<f64>
 where
     T: Native + PyClass,
     T::Core: Evaluator,
 {
+    let py = slf.py();
     let evaluator = snapshot(slf)?;
-    interruptible(slf.py(), &df.dataframe.spark_session(), || {
-        evaluator.evaluate(&df.dataframe).map_err(Box::new)
+    let df = evaluation_dataset(dataset)?;
+    let df = evaluator_input(py, df, inputs(&evaluator))?;
+    interruptible(py, &df.spark_session(), || {
+        evaluator.evaluate(&df).map_err(Box::new)
     })
 }
 
+/// The dataset of `evaluate`, as PySpark's evaluators take it: a DataFrame, 
or a pandas DataFrame,
+/// which PySpark evaluates locally, and which is sent here with 
`createDataFrame` of the active
+/// session, as the evaluators of this client run on the server. Another 
object raises the
+/// `AttributeError` of the `select` that PySpark's `aggregate_dataframe` 
calls on it.
+fn evaluation_dataset(dataset: &Bound<'_, PyAny>) -> PyResult<DataFrame> {
+    let py = dataset.py();
+    if let Ok(df) = dataset.extract::<PyRef<'_, PyDataFrame>>() {
+        return Ok(df.dataframe.clone());
+    }
+    // A pandas DataFrame is of an imported pandas.
+    let pandas = py
+        .import("sys")?
+        .getattr("modules")?
+        .get_item("pandas")
+        .ok();
+    if let Some(pandas) = pandas {
+        if dataset.is_instance(&pandas.getattr("DataFrame")?)? {
+            let df = py
+                .import("pyspark.sql")?
+                .getattr("SparkSession")?
+                .call_method0("active")?
+                .call_method1("createDataFrame", (dataset,))?;
+            return Ok(df.extract::<PyRef<'_, 
PyDataFrame>>()?.dataframe.clone());
+        }
+    }
+    dataset.getattr("select")?;
+    Err(PyTypeError::new_err(format!(
+        "evaluate() takes a DataFrame or a pandas DataFrame, not '{}'",
+        dataset.get_type().name()?
+    )))
+}
+
+/// `df` as the JVM evaluator reads it, with its columns of `inputs` 
converted: a prediction
+/// (`inputs.doubles`) of another numeric type is cast to a double, and a 
score (`inputs.score`) of
+/// another numeric type too, while an array score is sent as a vector by 
`array_to_vector`, which
+/// the JVM evaluator reads at its element 1, as PySpark's reads the column 1 
of an array. The
+/// columns are found in the schema of `df` regardless of case, as Spark 
resolves them; another
+/// type is sent as it is, which the JVM evaluator checks.
+fn evaluator_input(py: Python<'_>, df: DataFrame, inputs: EvaluatorInputs) -> 
PyResult<DataFrame> {
+    use spark_connect::types::DataType;
+
+    let schema = interruptible(py, &df.spark_session(), || 
df.schema().map_err(Box::new))?;
+    let DataType::Struct { fields } = schema else {
+        return Ok(df);
+    };
+    let mut df = df;
+    for field in fields {
+        let named = |name: &String| name.eq_ignore_ascii_case(&field.name);
+        let score = inputs.score.as_ref().is_some_and(named);
+        if !score && !inputs.doubles.iter().any(named) {
+            continue;
+        }
+        // The column of this name exactly, a name with a dot too.
+        let column = spark_connect::column::col(&format!("`{}`", 
field.name.replace('`', "``")));
+        let converted = match &field.data_type {
+            DataType::Byte
+            | DataType::Short
+            | DataType::Integer
+            | DataType::Long
+            | DataType::Float
+            | DataType::Decimal { .. } => column.cast(DataType::Double),
+            DataType::Array { .. } if score => {
+                
spark_connect::Column::new(spark_connect::expression::Expression::function(
+                    "array_to_vector",
+                    vec![column.expression().clone()],
+                ))
+            }
+            _ => continue,
+        };
+        df = df.with_column(&field.name, converted);
+    }
+    Ok(df)
+}
+
 /// A fitted ML model (result of `Estimator.fit`), wrapping a boxed core 
`Model`.
 #[pyclass(name = "MLModel", module = "pyspark.ml.connect")]
 pub struct PyMLModel {
@@ -2164,8 +2255,13 @@ impl PyRegressionEvaluator {
     ) -> PyResult<Bound<'py, Self>> {
         set_param(slf, "metricName", Kind::Str, value)
     }
-    fn evaluate(slf: &Bound<'_, Self>, df: &PyDataFrame) -> PyResult<f64> {
-        evaluate_native(slf, df)
+    /// Evaluate `dataset`, a DataFrame or a pandas DataFrame, as PySpark's 
evaluator, which reads a
+    /// prediction of any numeric type.
+    fn evaluate(slf: &Bound<'_, Self>, dataset: &Bound<'_, PyAny>) -> 
PyResult<f64> {
+        evaluate_native(slf, dataset, |evaluator| EvaluatorInputs {
+            doubles: vec![evaluator.prediction_col().to_string()],
+            score: None,
+        })
     }
 }
 
@@ -2263,8 +2359,13 @@ impl PyBinaryClassificationEvaluator {
     ) -> PyResult<Bound<'py, Self>> {
         set_param(slf, "metricName", Kind::Str, value)
     }
-    fn evaluate(slf: &Bound<'_, Self>, df: &PyDataFrame) -> PyResult<f64> {
-        evaluate_native(slf, df)
+    /// Evaluate `dataset`, a DataFrame or a pandas DataFrame, as PySpark's 
evaluator, which reads a
+    /// probability of any numeric type, or an array of the probabilities of 
the classes.
+    fn evaluate(slf: &Bound<'_, Self>, dataset: &Bound<'_, PyAny>) -> 
PyResult<f64> {
+        evaluate_native(slf, dataset, |evaluator| EvaluatorInputs {
+            doubles: Vec::new(),
+            score: Some(evaluator.raw_prediction_col().to_string()),
+        })
     }
 }
 
@@ -2368,8 +2469,13 @@ impl PyMulticlassClassificationEvaluator {
     ) -> PyResult<Bound<'py, Self>> {
         set_param(slf, "metricName", Kind::Str, value)
     }
-    fn evaluate(slf: &Bound<'_, Self>, df: &PyDataFrame) -> PyResult<f64> {
-        evaluate_native(slf, df)
+    /// Evaluate `dataset`, a DataFrame or a pandas DataFrame, as PySpark's 
evaluator, which reads a
+    /// prediction of any numeric type.
+    fn evaluate(slf: &Bound<'_, Self>, dataset: &Bound<'_, PyAny>) -> 
PyResult<f64> {
+        evaluate_native(slf, dataset, |evaluator| EvaluatorInputs {
+            doubles: vec![evaluator.prediction_col().to_string()],
+            score: None,
+        })
     }
 }
 
diff --git a/docs/compatibility.md b/docs/compatibility.md
index e9fc17f6..16e8b8c0 100644
--- a/docs/compatibility.md
+++ b/docs/compatibility.md
@@ -24,9 +24,11 @@ Python `timedelta` map keys are not yet supported.
 `scoreCol=` argument and `setScoreCol` of v4.2.0 are removed, without an alias:
 Spark's evaluator has no `scoreCol` param, so no value of it worked on the 
server.
 Use `set_raw_prediction_col` and `raw_prediction_col` in Rust, the column of 
raw prediction
-vectors that the evaluator scores. In Python, as in PySpark, it is 
`probabilityCol=` and
-`setProbabilityCol`, the column of probabilities, which the server reads as 
its raw prediction
-column.
+vectors that the evaluator scores. In Python it is `probabilityCol=`, as in 
PySpark, and
+`setProbabilityCol`, a setter of this client (PySpark's evaluators have none): 
the column of
+probabilities, which the server reads as its raw prediction column. A model 
without a
+probability column, such as the native `LinearSVC`, is scored with
+`probabilityCol="rawPrediction"`.
 
 The native ML classes take a JVM `Int` param as an `i32`: 
`LogisticRegression::set_max_iter`,
 `LinearSVC::set_max_iter` and `LinearSVC::set_aggregation_depth` take an 
`i32`, and
@@ -185,7 +187,15 @@ which takes `metricName`, `labelCol` and `predictionCol` 
by position as well, as
 PySpark's does; its `metricName` is `accuracy` by default, as in PySpark, 
where the JVM
 evaluator and the Rust API default to `f1`. The `probabilityCol` of
 `BinaryClassificationEvaluator` is `probability` by default, as in PySpark, 
and is sent as the
-`rawPredictionCol` that the JVM evaluator scores. Each value is converted by 
the `TypeConverters` of its param in
+`rawPredictionCol` that the JVM evaluator scores. The evaluators take a 
DataFrame or a pandas
+DataFrame, as PySpark's do, and run on the server: a pandas DataFrame is sent 
through
+`createDataFrame` of the active session. A prediction or a probability of 
another numeric type
+is cast to a double, and an array of probabilities is sent as a vector 
(`array_to_vector`),
+whose element 1 is scored, as PySpark's evaluator reads the column 1 of an 
array. The values
+are the JVM evaluators' doubles, where PySpark's are of float32 tensors (`0.6` 
where PySpark
+returns `0.6000000238418579`). The native scalers, as the native estimators, 
take ML vector
+features, where PySpark's take arrays: convert an array column with 
`array_to_vector`.
+Each value is converted by the `TypeConverters` of its param in
 PySpark (an integral float for an int param, for example), and a value that the
 converter rejects raises its `TypeError`. A fit, transform or evaluate sends 
only the
 params that the constructor or a setter set, so the server applies its 
defaults to
diff --git a/python/tests/test_ml_e2e.py b/python/tests/test_ml_e2e.py
index 682880e1..9ea0f3b7 100644
--- a/python/tests/test_ml_e2e.py
+++ b/python/tests/test_ml_e2e.py
@@ -419,6 +419,60 @@ def 
test_ml_connect_binary_evaluator_scores_the_probability_of_pyspark_docstring
     assert BinaryClassificationEvaluator().evaluate(dataset) == 
pytest.approx(5 / 6, abs=1e-9)
 
 
+def 
test_ml_connect_evaluators_take_the_columns_and_the_pandas_frames_of_pyspark_tests(session):
+    # The inputs of PySpark's own evaluator tests 
(test_legacy_mode_evaluation.py) and docstrings,
+    # which its torch evaluators read as tensors: int labels and predictions, 
a float32 or an
+    # array probability, whose column 1 is the positive class, and pandas 
DataFrames, which are
+    # sent through createDataFrame here, as the evaluators run on the server. 
The JVM evaluators
+    # give doubles, 0.6 where PySpark's float32 tensors give 
0.6000000238418579.
+    from pyspark.ml.connect.evaluation import (
+        BinaryClassificationEvaluator,
+        MulticlassClassificationEvaluator,
+        RegressionEvaluator,
+    )
+    from pyspark.sql import functions as F
+
+    multiclass = session.createDataFrame(
+        [(1, 1), (1, 1), (2, 3), (0, 0), (0, 1), (3, 1), (3, 3), (2, 2), (1, 
0), (2, 2)],
+        schema=["label", "prediction"],
+    )
+    accuracy = MulticlassClassificationEvaluator(metricName="accuracy")
+    assert accuracy.evaluate(multiclass) == pytest.approx(0.6)
+    assert accuracy.evaluate(dataset=multiclass.toPandas()) == 
pytest.approx(0.6)
+    docstring = session.createDataFrame(
+        [(1, 1), (0, 0), (2, 2), (1, 0), (2, 1)], schema=["label", 
"prediction"])
+    assert MulticlassClassificationEvaluator().evaluate(docstring) == 
pytest.approx(0.6)
+
+    regression = session.createDataFrame(
+        [(1.0, 2), (-1.0, -1), (2.0, 3)], schema=["label", "prediction"])
+    mse = RegressionEvaluator(metricName="mse")
+    assert mse.evaluate(regression) == pytest.approx(2 / 3)
+    assert mse.evaluate(regression.toPandas()) == pytest.approx(2 / 3)
+
+    binary = session.createDataFrame(
+        [
+            (1, 0.2, [0.8, 0.2]),
+            (0, 0.6, [0.4, 0.6]),
+            (1, 0.8, [0.2, 0.8]),
+            (1, 0.7, [0.3, 0.7]),
+            (0, 0.4, [0.6, 0.4]),
+            (0, 0.3, [0.7, 0.3]),
+        ],
+        schema=["label", "prob", "prob2"],
+    ).withColumn("prob32", F.col("prob").cast("float"))
+    for metric in ("areaUnderROC", "areaUnderPR"):
+        expected = BinaryClassificationEvaluator(
+            metricName=metric, probabilityCol="prob").evaluate(binary)
+        for column in ("prob2", "prob32"):
+            evaluator = BinaryClassificationEvaluator(metricName=metric, 
probabilityCol=column)
+            assert evaluator.evaluate(binary) == pytest.approx(expected), 
(metric, column)
+            assert evaluator.evaluate(binary.toPandas()) == 
pytest.approx(expected), (metric, column)
+    auroc = 
BinaryClassificationEvaluator(probabilityCol="prob2").evaluate(binary)
+    assert auroc == pytest.approx(2 / 3)
+    with pytest.raises(AttributeError, match="'list' object has no attribute 
'select'"):
+        accuracy.evaluate([(1, 1)])
+
+
 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
diff --git a/python/tests/test_ml_offline.py b/python/tests/test_ml_offline.py
index 330b95c4..89615a2b 100644
--- a/python/tests/test_ml_offline.py
+++ b/python/tests/test_ml_offline.py
@@ -286,7 +286,8 @@ def 
test_ml_connect_setters_set_the_params_of_their_receiver_as_pyspark(ml_mock)
         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.
+            # By the name of the argument of PySpark's setters, value. The 
evaluators' setters are
+            # of this client, as PySpark's evaluators have none, with the same 
argument.
             assert getattr(receiver, setter)(value=values[name]) is receiver, 
(cls, setter)
         params = sent_params(receiver)
         sent_values = {_sent_name(cls.__name__, name): value for name, value 
in values.items()}


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

Reply via email to