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 86a43a67 [SPARK-61324][CONNECT][PYTHON] Send the native ML list params 
as arrays and score BinaryClassificationEvaluator on rawPredictionCol, as 
PySpark does
86a43a67 is described below

commit 86a43a67c2bb6abe1319ee21c6abf963290ddd3e
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Tue Nov 10 10:21:24 2026 +0900

    [SPARK-61324][CONNECT][PYTHON] Send the native ML list params as arrays and 
score BinaryClassificationEvaluator on rawPredictionCol, as PySpark does
    
    ### What changes were proposed in this pull request?
    
    [SPARK-61324](https://issues.apache.org/jira/browse/SPARK-61324): Send the 
native ML list params as arrays and score the native 
BinaryClassificationEvaluator on rawPredictionCol, as PySpark does.
    
    - `VectorAssembler` `inputCols` and `Pipeline` `stages` are sent as an 
array literal of `string` elements, the encoding PySpark gives a Python list, 
instead of the Rust `Debug` text. Official `pyspark.ml.feature.VectorAssembler` 
on `x, y` gives `[[1.0, 2.0], [4.0, 5.0]]`; the native `VectorAssembler` (Rust 
and `pyspark.ml.connect.feature`) now gives the same.
    - `BinaryClassificationEvaluator` takes `rawPredictionCol` (default 
`rawPrediction`, the JVM default) instead of the `scoreCol` the JVM does not 
have. Rust: `set_raw_prediction_col` / `raw_prediction_col`. PyO3: the 
`rawPredictionCol=` keyword and `setRawPredictionCol`, as official names them. 
The scores 0.1, 0.4 (label 0) and 0.35, 0.8 (label 1) give AUC 0.75, and PR-AUC 
0.7916666666666666, as official gives.
    - The Int params `maxIter` (LogisticRegression, LinearSVC), 
`aggregationDepth` (LinearSVC) and `numFolds`, `parallelism` (CrossValidator) 
are sent as `Integer` literals when they fit 32 bits, as PySpark sends a Python 
int and as the JVM `IntParam` expects. The Rust signatures do not change.
    - Public Rust API: `BinaryClassificationEvaluator::set_score_col` and 
`score_col` are removed and replaced by `set_raw_prediction_col` and 
`raw_prediction_col`. There is no deprecated alias, because the old name never 
worked: the server rejects `scoreCol` for every value. Callers in the workspace 
are updated.
    - The `e2e_coverage` checks that hid both failures with `let _ = ...` now 
assert the assembled vectors and the AUC.
    
    Pipeline `fit` and `transform` still fail on the server with the known 
`AssertionError` (the Pipeline follow-up); this PR changes only the encoding of 
`stages`.
    
    ### Why are the changes needed?
    
    - `VectorAssembler(inputCols=["x", "y"]).transform(df)` fails on every 
call, in `pyspark.ml.connect.feature` and in the Rust 
`VectorAssembler::set_input_cols(...).transform(...)`, with 
`IllegalArgumentException: Argument is not an array`. The server needs an array 
of strings for `inputCols`.
    - `BinaryClassificationEvaluator(scoreCol="rawPrediction").evaluate(df)` 
fails with `Param scoreCol does not exist`, so the score column cannot be 
chosen at all. The Rust default `prediction` was never used by the server 
either.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes. `VectorAssembler` and `Pipeline` work with the server (the list params 
are accepted). The native `BinaryClassificationEvaluator` takes 
`rawPredictionCol` / `setRawPredictionCol` instead of `scoreCol` / 
`setScoreCol`, and its default score column is `rawPrediction`. The Rust 
`BinaryClassificationEvaluator::set_score_col` and `score_col` are removed 
(replaced by `set_raw_prediction_col` and `raw_prediction_col`).
    
    ### How was this patch tested?
    
    - `e2e_coverage::ml_estimators_and_transformers` (live): the 
`VectorAssembler` output is `[i, 2i]` for each row, and the evaluator AUC on 
`rawPrediction` is `0.75`. Both fail with the master encodings (`Argument is 
not an array`, `Param scoreCol does not exist`); I checked each by temporarily 
restoring its master encoding.
    - `ml::tests::list_and_int_params_use_the_jvm_literal_types` (offline, 
placed before `params_int_and_proto_roundtrip`): the `inputCols` and `stages` 
params are `Array` literals of `string` elements, and `maxIter` and `numFolds` 
are `Integer` literals. It fails on master.
    - `test_ml_connect_vector_assembler_and_evaluator_as_pyspark` in 
`python/tests/test_ml_e2e.py` (live, placed before 
`test_ml_statistics_as_pyspark`): the drop-in `VectorAssembler` and the native 
evaluator with `rawPredictionCol`, with the values official PySpark 4.3.0 gives 
(`[[1.0, 2.0], [4.0, 5.0]]`, AUC 0.75, PR-AUC 0.7916666666666666). It fails on 
master.
    - The offline tests that asserted the old encodings are updated: 
`linear_svc_parameters_use_the_spark_names_and_literal_types` (`Integer` for 
`maxIter` and `aggregationDepth`), and the `score_col` callers in 
`coverage_ml_extra`, `ml_coverage` and `ml_extra_golden`.
    - The lib tests (533 passed) and the transport crate's tests, the build of 
all tests (also with `RUSTFLAGS=-D warnings`), the offline Python suites (2937 
passed, 8 skipped) with the rebuilt extension, the live Rust tests 
`e2e_coverage` (25 passed), `e2e_kmeans` (5), `ml_coverage` (1), 
`coverage_ml_extra` (4) and `ml_extra_golden` (13), and `tests/test_ml_e2e.py` 
(14 passed; the new test also under pytest 9.2) against a local Spark 4.3.0 
server.
    
    ### 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 #446 from HyukjinKwon/SPARK-61324-ml-param-encoding.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/pyspark-rs/src/ml.rs                     |  18 ++--
 crates/spark-connect/src/ml.rs                  | 116 ++++++++++++++++++++----
 crates/spark-connect/tests/coverage_ml_extra.rs |   4 +-
 crates/spark-connect/tests/e2e_coverage.rs      |  62 +++++++++++--
 crates/spark-connect/tests/ml_coverage.rs       |   4 +-
 crates/spark-connect/tests/ml_extra_golden.rs   |   2 +-
 python/tests/test_ml_e2e.py                     |  28 ++++++
 7 files changed, 195 insertions(+), 39 deletions(-)

diff --git a/crates/pyspark-rs/src/ml.rs b/crates/pyspark-rs/src/ml.rs
index 4c0ff717..8c54c2f4 100644
--- a/crates/pyspark-rs/src/ml.rs
+++ b/crates/pyspark-rs/src/ml.rs
@@ -731,15 +731,19 @@ pub struct PyBinaryClassificationEvaluator {
 #[pymethods]
 impl PyBinaryClassificationEvaluator {
     #[new]
-    #[pyo3(signature = (labelCol=None, scoreCol=None, metricName=None))]
+    #[pyo3(signature = (labelCol=None, rawPredictionCol=None, 
metricName=None))]
     #[allow(non_snake_case)]
-    fn new(labelCol: Option<String>, scoreCol: Option<String>, metricName: 
Option<String>) -> Self {
+    fn new(
+        labelCol: Option<String>,
+        rawPredictionCol: Option<String>,
+        metricName: Option<String>,
+    ) -> Self {
         let mut e = BinaryClassificationEvaluator::new();
         if let Some(c) = labelCol {
             e = e.set_label_col(&c);
         }
-        if let Some(c) = scoreCol {
-            e = e.set_score_col(&c);
+        if let Some(c) = rawPredictionCol {
+            e = e.set_raw_prediction_col(&c);
         }
         if let Some(m) = metricName {
             e = e.set_metric_name(&m);
@@ -752,10 +756,10 @@ impl PyBinaryClassificationEvaluator {
             inner: self.inner.clone().set_label_col(col),
         }
     }
-    #[pyo3(name = "setScoreCol")]
-    fn set_score_col(&self, col: &str) -> Self {
+    #[pyo3(name = "setRawPredictionCol")]
+    fn set_raw_prediction_col(&self, col: &str) -> Self {
         PyBinaryClassificationEvaluator {
-            inner: self.inner.clone().set_score_col(col),
+            inner: self.inner.clone().set_raw_prediction_col(col),
         }
     }
     #[pyo3(name = "setMetricName")]
diff --git a/crates/spark-connect/src/ml.rs b/crates/spark-connect/src/ml.rs
index 12c1500e..d7d05ffa 100644
--- a/crates/spark-connect/src/ml.rs
+++ b/crates/spark-connect/src/ml.rs
@@ -12,8 +12,10 @@ use std::sync::Arc;
 use uuid::Uuid;
 
 use crate::dataframe::DataFrame;
+use crate::expression::LiteralExpression;
 use crate::plan::{LogicalPlan, RelationOwner};
 use crate::session::SparkSession;
+use crate::types::DataType;
 
 /// ML parameter handling: stores name -> literal value mappings.
 ///
@@ -58,6 +60,39 @@ impl Params {
         self
     }
 
+    /// Encode an ML parameter whose JVM type is `Int` from a 64-bit value: an 
`Integer` literal
+    /// when it fits 32 bits, as PySpark sends a Python int, else a `Long`.
+    fn set_param_int_narrow(self, name: &str, value: i64) -> Self {
+        match i32::try_from(value) {
+            Ok(value) => self.set_param_int32(name, value),
+            Err(_) => self.set_param_int(name, value),
+        }
+    }
+
+    /// Encode an ML parameter whose JVM type is `Array[String]` (such as 
`inputCols`), as PySpark
+    /// sends a list of strings: an array literal of `string` elements.
+    fn set_param_string_array(mut self, name: &str, values: &[String]) -> Self 
{
+        let elements = values
+            .iter()
+            .map(|v| LiteralExpression::String(v.clone()))
+            .collect();
+        let literal = LiteralExpression::Array {
+            element_type: Box::new(DataType::String {
+                collation: String::new(),
+            }),
+            elements,
+        }
+        .to_literal_proto();
+        self.params.insert(
+            name.to_string(),
+            proto::Expression {
+                expr_type: Some(proto::expression::ExprType::Literal(literal)),
+                ..Default::default()
+            },
+        );
+        self
+    }
+
     /// Set a parameter to a double value.
     pub fn set_param_double(mut self, name: &str, value: f64) -> Self {
         let mut literal = proto::Expression::default();
@@ -517,7 +552,7 @@ impl VectorAssembler {
         self.input_cols = cols.iter().map(|c| c.to_string()).collect();
         self.params = self
             .params
-            .set_param_string("inputCols", &format!("{:?}", self.input_cols));
+            .set_param_string_array("inputCols", &self.input_cols);
         self
     }
 
@@ -1007,7 +1042,7 @@ impl LogisticRegression {
 
     pub fn set_max_iter(mut self, max_iter: i64) -> Self {
         self.max_iter = max_iter;
-        self.params = self.params.set_param_int("maxIter", max_iter);
+        self.params = self.params.set_param_int_narrow("maxIter", max_iter);
         self
     }
 
@@ -1173,7 +1208,7 @@ impl LinearSVC {
 
     /// Maximum number of optimizer iterations.
     pub fn set_max_iter(mut self, value: i64) -> Self {
-        self.params = self.params.set_param_int("maxIter", value);
+        self.params = self.params.set_param_int_narrow("maxIter", value);
         self
     }
 
@@ -1215,7 +1250,7 @@ impl LinearSVC {
 
     /// Tree aggregation depth.
     pub fn set_aggregation_depth(mut self, value: i64) -> Self {
-        self.params = self.params.set_param_int("aggregationDepth", value);
+        self.params = self.params.set_param_int_narrow("aggregationDepth", 
value);
         self
     }
 
@@ -1764,7 +1799,7 @@ pub struct BinaryClassificationEvaluator {
     operator: MlOperator,
     params: Params,
     label_col: String,
-    score_col: String,
+    raw_prediction_col: String,
     metric_name: String,
 }
 
@@ -1777,7 +1812,7 @@ impl BinaryClassificationEvaluator {
             ),
             params: Params::new(),
             label_col: "label".to_string(),
-            score_col: "prediction".to_string(),
+            raw_prediction_col: "rawPrediction".to_string(),
             metric_name: "areaUnderROC".to_string(),
         }
     }
@@ -1788,9 +1823,10 @@ impl BinaryClassificationEvaluator {
         self
     }
 
-    pub fn set_score_col(mut self, col: &str) -> Self {
-        self.score_col = col.to_string();
-        self.params = self.params.set_param_string("scoreCol", col);
+    /// Set the column of the scores (a vector of raw predictions), the JVM 
`rawPredictionCol`.
+    pub fn set_raw_prediction_col(mut self, col: &str) -> Self {
+        self.raw_prediction_col = col.to_string();
+        self.params = self.params.set_param_string("rawPredictionCol", col);
         self
     }
 
@@ -1804,8 +1840,8 @@ impl BinaryClassificationEvaluator {
         &self.label_col
     }
 
-    pub fn score_col(&self) -> &str {
-        &self.score_col
+    pub fn raw_prediction_col(&self) -> &str {
+        &self.raw_prediction_col
     }
 
     pub fn metric_name(&self) -> &str {
@@ -1852,9 +1888,7 @@ impl Pipeline {
 
     pub fn set_stages(mut self, stage_names: Vec<&str>) -> Self {
         self.stages = stage_names.iter().map(|s| s.to_string()).collect();
-        self.params = self
-            .params
-            .set_param_string("stages", &format!("{:?}", self.stages));
+        self.params = self.params.set_param_string_array("stages", 
&self.stages);
         self
     }
 
@@ -2043,12 +2077,12 @@ impl CrossValidator {
     }
     pub fn set_num_folds(mut self, num_folds: i32) -> Self {
         self.num_folds = num_folds;
-        self.params = self.params.set_param_int("numFolds", num_folds as i64);
+        self.params = self.params.set_param_int32("numFolds", num_folds);
         self
     }
     pub fn set_parallelism(mut self, parallelism: i32) -> Self {
         self.parallelism = parallelism;
-        self.params = self.params.set_param_int("parallelism", parallelism as 
i64);
+        self.params = self.params.set_param_int32("parallelism", parallelism);
         self
     }
     pub fn set_seed(mut self, seed: i64) -> Self {
@@ -2289,11 +2323,11 @@ mod tests {
     fn test_binary_classification_evaluator_creation() {
         let eval = BinaryClassificationEvaluator::new()
             .set_label_col("label")
-            .set_score_col("score")
+            .set_raw_prediction_col("score")
             .set_metric_name("areaUnderPR");
 
         assert_eq!(eval.label_col(), "label");
-        assert_eq!(eval.score_col(), "score");
+        assert_eq!(eval.raw_prediction_col(), "score");
         assert_eq!(eval.metric_name(), "areaUnderPR");
     }
 
@@ -2426,6 +2460,48 @@ mod tests {
         }
     }
 
+    #[test]
+    fn list_and_int_params_use_the_jvm_literal_types() {
+        use proto::expression::literal::LiteralType as L;
+        // An Array[String] param (inputCols, Pipeline stages) is an array 
literal of string
+        // elements, as PySpark sends a list; the server rejects a string 
("not an array").
+        let va = VectorAssembler::new().set_input_cols(vec!["a", "b"]);
+        let pipeline = Pipeline::new().set_stages(vec!["scaler", "lr"]);
+        for (name, params, expected) in [
+            ("inputCols", va.params(), vec!["a", "b"]),
+            ("stages", pipeline.params(), vec!["scaler", "lr"]),
+        ] {
+            let Some(L::Array(array)) = 
params.to_proto().params[name].literal_type.clone() else {
+                panic!("{name} is not an array literal");
+            };
+            #[allow(deprecated)]
+            let element_type = array.element_type.as_ref().and_then(|t| 
t.kind.clone());
+            assert!(
+                matches!(element_type, 
Some(proto::data_type::Kind::String(_))),
+                "{name} element type"
+            );
+            let elements: Vec<_> = array
+                .elements
+                .iter()
+                .map(|e| e.literal_type.clone())
+                .collect();
+            let expected: Vec<_> = expected
+                .iter()
+                .map(|s| Some(L::String(s.to_string())))
+                .collect();
+            assert_eq!(elements, expected, "{name}");
+        }
+
+        // Int params are Integer literals when the value fits 32 bits, as 
PySpark sends a Python
+        // int; the JVM param is an IntParam (maxIter, numFolds).
+        let lr = LogisticRegression::new().set_max_iter(5);
+        let params = lr.params().to_proto().params;
+        assert_eq!(params["maxIter"].literal_type, Some(L::Integer(5)));
+        let cv = CrossValidator::new().set_num_folds(3);
+        let params = cv.params().to_proto().params;
+        assert_eq!(params["numFolds"].literal_type, Some(L::Integer(3)));
+    }
+
     #[test]
     fn params_int_and_proto_roundtrip() {
         let p = Params::new()
@@ -2687,14 +2763,14 @@ mod tests {
             ("labelCol", L::String("target".into())),
             ("predictionCol", L::String("pred".into())),
             ("rawPredictionCol", L::String("margin".into())),
-            ("maxIter", L::Long(50)),
+            ("maxIter", L::Integer(50)),
             ("regParam", L::Double(0.1)),
             ("tol", L::Double(1e-5)),
             ("fitIntercept", L::Boolean(false)),
             ("standardization", L::Boolean(false)),
             ("threshold", L::Double(0.5)),
             ("weightCol", L::String("weight".into())),
-            ("aggregationDepth", L::Long(3)),
+            ("aggregationDepth", L::Integer(3)),
             ("maxBlockSizeInMB", L::Double(1.0)),
         ];
         assert_eq!(params.len(), expected.len());
diff --git a/crates/spark-connect/tests/coverage_ml_extra.rs 
b/crates/spark-connect/tests/coverage_ml_extra.rs
index 77577f68..a7a8cb6b 100644
--- a/crates/spark-connect/tests/coverage_ml_extra.rs
+++ b/crates/spark-connect/tests/coverage_ml_extra.rs
@@ -162,10 +162,10 @@ fn evaluator_builders_and_accessors() {
 
     let e = BinaryClassificationEvaluator::new()
         .set_label_col("l")
-        .set_score_col("s")
+        .set_raw_prediction_col("s")
         .set_metric_name("areaUnderPR");
     assert_eq!(e.label_col(), "l");
-    assert_eq!(e.score_col(), "s");
+    assert_eq!(e.raw_prediction_col(), "s");
     assert_eq!(e.metric_name(), "areaUnderPR");
     let _ = e.operator();
     let _ = e.params();
diff --git a/crates/spark-connect/tests/e2e_coverage.rs 
b/crates/spark-connect/tests/e2e_coverage.rs
index a5a059fa..88a518d8 100644
--- a/crates/spark-connect/tests/e2e_coverage.rs
+++ b/crates/spark-connect/tests/e2e_coverage.rs
@@ -1200,15 +1200,56 @@ fn ml_estimators_and_transformers() {
         )
         .expect("ml sample");
 
-    // This smoke test covers request construction and tolerates server 
rejection.
     // LogisticRegression has separate tests below that assert successful 
training
     // and learned predictions.
 
-    // Transformer.transform builds a fetch of the transform relation.
+    // VectorAssembler: the server assembles `a` and `b` into [id, 2 * id], as 
PySpark does.
     let mut va = VectorAssembler::new()
         .set_input_cols(vec!["a", "b"])
         .set_output_col("assembled");
-    let _ = va.transform(&df).and_then(|d| d.count());
+    let assembled = va
+        .transform(&df)
+        .expect("transform VectorAssembler")
+        .with_column(
+            "values",
+            
spark_connect::Column::new(spark_connect::expression::Expression::function(
+                "vector_to_array",
+                vec![
+                    col("assembled").expression().clone(),
+                    lit_string("float64").expression().clone(),
+                ],
+            )),
+        )
+        .select(vec![col("a"), col("values")])
+        .collect()
+        .expect("collect assembled vectors");
+    let mut assembled: Vec<(f64, Vec<f64>)> = assembled
+        .iter()
+        .map(|row| {
+            let a = match row.get_by_name("a") {
+                Some(spark_connect::row::Value::Double(a)) => *a,
+                other => panic!("unexpected a: {other:?}"),
+            };
+            let values = match row.get_by_name("values") {
+                Some(spark_connect::row::Value::List(items)) => items
+                    .iter()
+                    .map(|v| match v {
+                        spark_connect::row::Value::Double(d) => *d,
+                        other => panic!("unexpected element: {other:?}"),
+                    })
+                    .collect(),
+                other => panic!("unexpected values: {other:?}"),
+            };
+            (a, values)
+        })
+        .collect();
+    assembled.sort_by(|x, y| x.0.partial_cmp(&y.0).unwrap());
+    assert_eq!(
+        assembled,
+        (0..20)
+            .map(|i| (i as f64, vec![i as f64, 2.0 * i as f64]))
+            .collect::<Vec<_>>()
+    );
 
     // The server fits each scaler and indexer, and the transform of the model 
uses the cached
     // model. The scalers take ML vector features.
@@ -1250,13 +1291,20 @@ fn ml_estimators_and_transformers() {
         .set_metric_name("rmse");
     assert_eq!(reg_eval.evaluate(&eval_df).unwrap(), 0.0);
 
-    // BinaryClassificationEvaluator: the client build+submit path runs; the 
server
-    // needs a vector score column for a real AUC, so tolerate a shape 
rejection.
+    // BinaryClassificationEvaluator scores the rawPredictionCol, here a 
double column as the JVM
+    // accepts (a vector is the classifier output): the scores 0.1, 0.4 (label 
0) and 0.35, 0.8
+    // (label 1) give an AUC of 0.75, as PySpark gives.
+    let bin_df = s
+        .sql(
+            "SELECT CAST(l AS DOUBLE) AS label, CAST(p AS DOUBLE) AS 
rawPrediction \
+             FROM VALUES (0, 0.1), (0, 0.4), (1, 0.35), (1, 0.8) AS t(l, p)",
+        )
+        .expect("binary evaluator df");
     let bin_eval = BinaryClassificationEvaluator::new()
         .set_label_col("label")
-        .set_score_col("prediction")
+        .set_raw_prediction_col("rawPrediction")
         .set_metric_name("areaUnderROC");
-    let _ = bin_eval.evaluate(&eval_df);
+    assert_eq!(bin_eval.evaluate(&bin_df).unwrap(), 0.75);
 
     // Pipeline carries stage names as params; this smoke test tolerates 
rejection.
     let mut pipeline = Pipeline::new().set_stages(vec!["scaler", "lr"]);
diff --git a/crates/spark-connect/tests/ml_coverage.rs 
b/crates/spark-connect/tests/ml_coverage.rs
index b845d94f..1b0ef978 100644
--- a/crates/spark-connect/tests/ml_coverage.rs
+++ b/crates/spark-connect/tests/ml_coverage.rs
@@ -44,10 +44,10 @@ fn ml_estimators_setters_getters_proto() {
 
     let be = BinaryClassificationEvaluator::new()
         .set_label_col("l")
-        .set_score_col("s")
+        .set_raw_prediction_col("s")
         .set_metric_name("areaUnderROC");
     assert_eq!(be.label_col(), "l");
-    assert_eq!(be.score_col(), "s");
+    assert_eq!(be.raw_prediction_col(), "s");
     assert_eq!(be.metric_name(), "areaUnderROC");
 
     let mce = MulticlassClassificationEvaluator::new()
diff --git a/crates/spark-connect/tests/ml_extra_golden.rs 
b/crates/spark-connect/tests/ml_extra_golden.rs
index 69f35ecf..c2b7907c 100644
--- a/crates/spark-connect/tests/ml_extra_golden.rs
+++ b/crates/spark-connect/tests/ml_extra_golden.rs
@@ -165,7 +165,7 @@ fn test_binary_classification_evaluator_metrics() {
     let eval = 
BinaryClassificationEvaluator::new().set_metric_name("areaUnderPR");
     assert_eq!(eval.metric_name(), "areaUnderPR");
     assert_eq!(eval.label_col(), "label");
-    assert_eq!(eval.score_col(), "prediction");
+    assert_eq!(eval.raw_prediction_col(), "rawPrediction");
 }
 
 #[test]
diff --git a/python/tests/test_ml_e2e.py b/python/tests/test_ml_e2e.py
index a03bf03c..5bfac6a4 100644
--- a/python/tests/test_ml_e2e.py
+++ b/python/tests/test_ml_e2e.py
@@ -186,6 +186,34 @@ def test_ml_feature_transformers_as_pyspark(session):
     assert list(scaler.originalMin) == [0.0, 1.0] and list(scaler.originalMax) 
== [7.0, 1.0]
 
 
+def test_ml_connect_vector_assembler_and_evaluator_as_pyspark(session):
+    # pyspark.ml.connect's VectorAssembler sends inputCols as a list of 
strings, and the native
+    # BinaryClassificationEvaluator scores its rawPredictionCol (default 
rawPrediction), with
+    # the values of PySpark 4.3.0.
+    from pyspark.ml.connect.evaluation import BinaryClassificationEvaluator
+    from pyspark.ml.connect.feature import VectorAssembler
+    from pyspark.ml.functions import array_to_vector
+    from pyspark.sql import functions as F
+
+    df = session.createDataFrame([(1.0, 2.0, 3), (4.0, 5.0, 6)], "x double, y 
double, z int")
+    assembled = VectorAssembler(inputCols=["x", "y"], 
outputCol="v").transform(df)
+    assert [r.v.toArray().tolist() for r in assembled.orderBy("x").collect()] 
== [
+        [1.0, 2.0],
+        [4.0, 5.0],
+    ]
+
+    scores = [(0.0, 0.1), (0.0, 0.4), (1.0, 0.35), (1.0, 0.8)]
+    raw = session.createDataFrame(scores, "label double, score double").select(
+        "label",
+        array_to_vector(F.array(1.0 - F.col("score"), 
F.col("score"))).alias("rawPrediction"),
+    )
+    assert BinaryClassificationEvaluator().evaluate(raw) == 0.75
+    evaluator = 
BinaryClassificationEvaluator(rawPredictionCol="rawPrediction", 
labelCol="label")
+    assert evaluator.evaluate(raw) == 0.75
+    pr = BinaryClassificationEvaluator(metricName="areaUnderPR", 
rawPredictionCol="rawPrediction")
+    assert pr.evaluate(raw) == pytest.approx(0.7916666666666666)
+
+
 def test_ml_statistics_as_pyspark(session):
     from pyspark.ml.stat import ChiSquareTest, Correlation, Summarizer
 


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

Reply via email to