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 79e62fcb [SPARK-61545][CONNECT][PYTHON] Let the native ML estimators 
and scalers take the array columns of PySpark's pyspark.ml.connect classes, and 
scale as PySpark's scalers do
79e62fcb is described below

commit 79e62fcbd651b9f19357f85d8562c0971046b3f2
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Thu Nov 12 22:16:54 2026 +0900

    [SPARK-61545][CONNECT][PYTHON] Let the native ML estimators and scalers 
take the array columns of PySpark's pyspark.ml.connect classes, and scale as 
PySpark's scalers do
    
    ### What changes were proposed in this pull request?
    
    A follow-up of #563 (SPARK-61531), from the same review: the native scalers 
and estimators of the Python client required vector features, where PySpark's 
`pyspark.ml.connect` classes compute with numpy and torch on array columns.
    
    - PySpark's `MaxAbsScaler` and `StandardScaler` take an array of numbers 
(`summarize_dataframe`) and output an `array<double>` (`_output_columns`).
    - `StandardScaler` scales to `(x - mean) / std`.
    - `LogisticRegression` takes array features.
    - So PySpark's own docstring examples failed here with `Column features 
must be of type ... VectorUDT ... but was actually ... array<double>`.
    
    In `crates/pyspark-rs/src/ml.rs`:
    - `Vectors::of` decides from the JVM class which columns the JVM reads or 
writes as vectors:
      - estimators of the classification, regression and clustering packages 
read their `featuresCol`;
      - scalers read their `inputCol` and write their `outputCol`.
      - Nothing is class-specific, so every native estimator gets it, including 
#567's GBTRegressor.
    - A fit (`fit_native`), and the transform of its model 
(`PyMLModel::transform`), read the DataFrame's schema once.
      - They send an array of numbers in that column as the vector the JVM 
reads (`array_to_vector`). Decimal arrays are cast to `array<double>` first, 
which `array_to_vector` needs.
      - A vector is sent as it is.
      - The transform keeps the array column as it was in its output.
    - The models of `MaxAbsScaler` and `StandardScaler` output an 
`array<double>` (`vector_to_array`), as PySpark's do.
    - `StandardScaler`'s constructor sends the JVM scaler's `withMean`, false 
by default, so it scales to `(x - mean) / std` as PySpark's does. PySpark's 
scaler has no such param.
    - If the transform can't read the schema (a DataFrame too deep for the 
server), it sends the column as it is and stays lazy. The evaluators of #563 
share the schema helpers.
    
    `docs/compatibility.md` describes the new behavior and what remains:
    - the JVM's doubles where PySpark computes float32 from float arrays;
    - the `rawPrediction`/`probability` vectors and double `prediction` of the 
native LogisticRegression, where PySpark's are `bigint` and `array<double>`.
    
    ### Why are the changes needed?
    
    To match PySpark 4.3.0. Official `pyspark-client` 4.3.0, probed against the 
same server, outputs 
`struct<features:array<double>,scaled_features:array<double>>` for 
MaxAbsScaler's docstring example, with rows `[0.3333333333333333, 1.0]`, 
`[0.6666666666666666, -0.5]` and `[-1.0, -1.0]`. These now match exactly. 
StandardScaler now gives PySpark's centered values, such as 
`[0.3779644730092272, 1.1208970766356101]` for the first row. A scaler → 
LogisticRegression or KMeans pipeline works,  [...]
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes. In the Python client:
    - The native estimators and scalers take array columns.
    - The scalers output `array<double>` instead of vectors.
    - `StandardScaler` centers the values, as PySpark's does.
    
    ### How was this patch tested?
    
    - New:
      - 
`test_ml_connect_scalers_and_estimators_take_the_array_columns_of_pyspark` 
(e2e) covers PySpark's docstring inputs, int and decimal arrays, 
StandardScaler's values, LogisticRegression, and scaler → 
LogisticRegression/KMeans pipelines.
      - `test_ml_connect_native_estimators_take_the_array_columns_of_pyspark` 
(offline) covers every native estimator of a `featuresCol`, from 
`_NATIVE_PARAMS`, and the scalers.
    - Updated:
      - `test_ml_connect_scalers_fit_and_transform_as_pyspark`: `array<double>` 
output, centered values.
      - `test_ml_connect_fitted_scalers_transform_the_cached_model`: the 
`vector_to_array` layer, and `withMean`.
      - `_defaults_sent`: StandardScaler's `withMean`.
      - A DecisionTreeClassifier test of invalid features in 
`test_dropin_e2e.py`, which now uses an array of strings, since an array of 
numbers is taken.
    - The new and updated tests fail without the change.
    - `test_ml_offline.py` (121 passed) and `test_ml_e2e.py` (23 passed, 
against a Spark 4.3.0 server) pass.
    - The GBT e2e files and the native-ML tests of `test_dropin_e2e.py` (34 
passed) pass.
    - The offline drop-in ML subset passes.
    - `cargo fmt --all --check`, the release build, `ruff check` and 
`scripts/audit_no_stubs.sh` are clean.
    
    ### 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 #574 from HyukjinKwon/SPARK-61545-ml-array-columns.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/pyspark-rs/src/ml.rs     | 260 ++++++++++++++++++++++++++++++++++------
 docs/compatibility.md           |  23 +++-
 python/tests/test_dropin_e2e.py |   4 +-
 python/tests/test_ml_e2e.py     |  91 +++++++++++++-
 python/tests/test_ml_offline.py | 136 ++++++++++++++++++++-
 5 files changed, 465 insertions(+), 49 deletions(-)

diff --git a/crates/pyspark-rs/src/ml.rs b/crates/pyspark-rs/src/ml.rs
index 3dc221a1..888483b4 100644
--- a/crates/pyspark-rs/src/ml.rs
+++ b/crates/pyspark-rs/src/ml.rs
@@ -259,13 +259,21 @@ fn snapshot<T: Native + PyClass>(slf: &Bound<'_, T>) -> 
PyResult<T::Core> {
     Ok(this.inner().clone())
 }
 
+/// The fit of a native estimator, on `df` as its JVM estimator reads it: an 
array column that the
+/// JVM estimator reads as an ML vector is sent as that vector (see 
[`Vectors`]).
 fn fit_native<T>(slf: &Bound<'_, T>, df: &PyDataFrame) -> PyResult<PyMLModel>
 where
     T: Native + PyClass,
     T::Core: Estimator,
 {
+    let py = slf.py();
     let estimator = snapshot(slf)?;
-    fit_core(slf.py(), estimator, df)
+    let vectors = Vectors::of(estimator.operator(), estimator.params());
+    let dataset = match vectors.array_input(py, &df.dataframe, false)? {
+        Some(field) => df.dataframe.with_column(&field.name, 
vector_of(&field)),
+        None => df.dataframe.clone(),
+    };
+    fit_core(py, estimator, &dataset)
 }
 
 /// The fit of a native estimator whose core cannot fit it, as Pipeline and 
CrossValidator.
@@ -277,24 +285,182 @@ where
     T::Core: Estimator,
 {
     let estimator = slf.try_borrow()?.inner().clone();
-    fit_core(slf.py(), estimator, df)
+    fit_core(slf.py(), estimator, &df.dataframe)
 }
 
-fn fit_core<C: Estimator>(
-    py: Python<'_>,
-    mut estimator: C,
-    df: &PyDataFrame,
-) -> PyResult<PyMLModel> {
-    let session = df.dataframe.spark_session();
-    let model = interruptible(py, &session, || {
-        estimator.fit(&df.dataframe).map_err(Box::new)
-    })?;
+fn fit_core<C: Estimator>(py: Python<'_>, mut estimator: C, df: &DataFrame) -> 
PyResult<PyMLModel> {
+    let session = df.spark_session();
+    let model = interruptible(py, &session, || 
estimator.fit(df).map_err(Box::new))?;
     Ok(PyMLModel {
         model,
         session_id: session.session_id().to_string(),
     })
 }
 
+/// The columns of a native estimator, and of the model of its fit, that the 
JVM reads or writes
+/// as ML vectors, as their fit and transform send them, so that they take the 
columns of PySpark's
+/// `pyspark.ml.connect` classes, which compute with numpy and torch on 
arrays: an array of numbers
+/// of the `input` column is sent as a vector by `array_to_vector`, and a 
vector as it is, while the
+/// `output` vector of a scaler is converted to an `array<double>` by 
`vector_to_array`, as
+/// PySpark's scalers output (their `_output_columns`).
+#[derive(Default)]
+struct Vectors {
+    input: Option<String>,
+    output: Option<String>,
+}
+
+impl Vectors {
+    /// The vector columns of the JVM estimator or model `operator`, of the 
params `params`, as
+    /// Spark's ML classes read and write them: those of the classification, 
regression and
+    /// clustering packages read the vector of their `featuresCol` (`features` 
unless set). Of the
+    /// feature package, the scalers read the vector of their `inputCol` and 
write that of their
+    /// `outputCol` (`<uid>__output` unless set), and the others 
(StringIndexer) read no vector.
+    fn of(operator: &spark_connect::ml::MlOperator, params: &Params) -> Self {
+        let class = operator
+            .name
+            .strip_suffix("Model")
+            .unwrap_or(&operator.name);
+        match class.strip_prefix("org.apache.spark.ml.feature.") {
+            Some(feature) if feature.ends_with("Scaler") => Self {
+                input: string_param(params, "inputCol"),
+                output: Some(
+                    string_param(params, "outputCol")
+                        .unwrap_or_else(|| format!("{}__output", 
operator.uid)),
+                ),
+            },
+            Some(_) => Self::default(),
+            None => Self {
+                input: Some(
+                    string_param(params, "featuresCol").unwrap_or_else(|| 
"features".to_string()),
+                ),
+                output: None,
+            },
+        }
+    }
+
+    /// The field of the `input` column in the schema of `df`, found 
regardless of case as Spark
+    /// resolves it, when it is an array of numbers. Another type is sent as 
it is, which the JVM
+    /// estimator checks. The schema is read only for an `input`. With 
`lazily`, of a transform,
+    /// which is lazy as the transforms of PySpark's JVM models are, a schema 
that the server does
+    /// not give (of a DataFrame too deep for it, say) leaves the column as it 
is: the server
+    /// raises its error when the transformed DataFrame is analyzed or run, as 
without the read.
+    fn array_input(
+        &self,
+        py: Python<'_>,
+        df: &DataFrame,
+        lazily: bool,
+    ) -> PyResult<Option<spark_connect::types::StructField>> {
+        use spark_connect::types::DataType;
+
+        let Some(input) = &self.input else {
+            return Ok(None);
+        };
+        let fields = if lazily {
+            let session = df.spark_session();
+            // A signal still raises: it is the outer error.
+            match crate::interrupt::interruptible_outcome(py, &session, || {
+                df.schema().map_err(Box::new)
+            })? {
+                Ok(DataType::Struct { fields }) => fields,
+                _ => return Ok(None),
+            }
+        } else {
+            schema_fields(py, df)?
+        };
+        Ok(fields
+            .into_iter()
+            .find(|field| field.name.eq_ignore_ascii_case(input))
+            .filter(|field| match &field.data_type {
+                DataType::Array { element_type, .. } => matches!(
+                    **element_type,
+                    DataType::Byte
+                        | DataType::Short
+                        | DataType::Integer
+                        | DataType::Long
+                        | DataType::Float
+                        | DataType::Double
+                        | DataType::Decimal { .. }
+                ),
+                _ => false,
+            }))
+    }
+}
+
+/// The ML vector of `field`, an array column of numbers: `array_to_vector` of 
it, which takes
+/// the arrays of the numbers that Spark casts up to doubles. An array of 
decimals, which it does
+/// not take, is cast to an `array<double>` first, as PySpark's MaxAbsScaler 
computes on decimals.
+fn vector_of(field: &spark_connect::types::StructField) -> 
spark_connect::Column {
+    use spark_connect::types::DataType;
+
+    let column = exact_column(&field.name);
+    array_to_vector(match &field.data_type {
+        DataType::Array { element_type, .. }
+            if matches!(**element_type, DataType::Decimal { .. }) =>
+        {
+            column.cast(DataType::Array {
+                element_type: Box::new(DataType::Double),
+                contains_null: true,
+            })
+        }
+        _ => column,
+    })
+}
+
+/// The string param `name` of `params`, if it is set to a string, as the core 
reads it (a null is
+/// not a string).
+fn string_param(params: &Params, name: &str) -> Option<String> {
+    use spark_connect_proto::expression::{literal::LiteralType, ExprType};
+
+    match params.get_param(name)?.expr_type.as_ref()? {
+        ExprType::Literal(literal) => match literal.literal_type.as_ref()? {
+            LiteralType::String(value) => Some(value.clone()),
+            _ => None,
+        },
+        _ => None,
+    }
+}
+
+/// The fields of the schema of `df`, which is read from the server once (and 
then cached).
+fn schema_fields(
+    py: Python<'_>,
+    df: &DataFrame,
+) -> PyResult<Vec<spark_connect::types::StructField>> {
+    use spark_connect::types::DataType;
+
+    let schema = interruptible(py, &df.spark_session(), || 
df.schema().map_err(Box::new))?;
+    Ok(match schema {
+        DataType::Struct { fields } => fields,
+        _ => Vec::new(),
+    })
+}
+
+/// The column of the name `name` exactly, a name with a dot too.
+fn exact_column(name: &str) -> spark_connect::Column {
+    spark_connect::column::col(&format!("`{}`", name.replace('`', "``")))
+}
+
+/// `array_to_vector` of `column`, the ML vector of an array of numbers.
+fn array_to_vector(column: spark_connect::Column) -> spark_connect::Column {
+    spark_connect::Column::new(spark_connect::expression::Expression::function(
+        "array_to_vector",
+        vec![column.expression().clone()],
+    ))
+}
+
+/// `vector_to_array` of the column `name`, of PySpark's default dtype 
`float64`: the
+/// `array<double>` of an ML vector.
+fn vector_to_array(name: &str) -> spark_connect::Column {
+    spark_connect::Column::new(spark_connect::expression::Expression::function(
+        "vector_to_array",
+        vec![
+            exact_column(name).expression().clone(),
+            spark_connect::column::lit_string("float64")
+                .expression()
+                .clone(),
+        ],
+    ))
+}
+
 /// 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.
@@ -364,10 +530,7 @@ fn evaluation_dataset(dataset: &Bound<'_, PyAny>) -> 
PyResult<DataFrame> {
 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 fields = schema_fields(py, &df)?;
     let mut df = df;
     for field in fields {
         let named = |name: &String| name.eq_ignore_ascii_case(&field.name);
@@ -375,21 +538,14 @@ fn evaluator_input(py: Python<'_>, df: DataFrame, inputs: 
EvaluatorInputs) -> Py
         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()],
-                ))
-            }
+            | DataType::Decimal { .. } => 
exact_column(&field.name).cast(DataType::Double),
+            DataType::Array { .. } if score => 
array_to_vector(exact_column(&field.name)),
             _ => continue,
         };
         df = df.with_column(&field.name, converted);
@@ -407,33 +563,62 @@ pub struct PyMLModel {
 
 #[pymethods]
 impl PyMLModel {
-    /// Apply the model to a DataFrame.
+    /// Apply the model to a DataFrame. As PySpark's models of 
`pyspark.ml.connect`, it takes an
+    /// array of numbers where the JVM model reads a vector, and keeps that 
column as it is in its
+    /// output, and a scaler outputs an `array<double>` (see [`Vectors`]).
     fn transform(&self, py: Python<'_>, df: &PyDataFrame) -> 
PyResult<PyDataFrame> {
         let mut model = self.model.clone_box();
         let session = df.dataframe.spark_session();
-        if session.session_id() != self.session_id {
+        let vectors = Vectors::of(model.operator(), model.params());
+        // An array input is sent as its vector, which the JVM model reads, 
and kept as it is in a
+        // column of its own, which takes its place again in the output.
+        let array = vectors
+            .array_input(py, &df.dataframe, true)?
+            .map(|field| (format!("{}__input", model.operator().uid), field));
+        let input = match &array {
+            Some((kept, field)) => df.dataframe.with_columns(vec![
+                (kept.clone(), exact_column(&field.name)),
+                (field.name.clone(), vector_of(field)),
+            ]),
+            None => df.dataframe.clone(),
+        };
+        let out = if session.session_id() != self.session_id {
             // As PySpark, the transform of a DataFrame of another session 
refers to the model
             // on the server of that session, which raises 
CONNECT_ML.CACHE_INVALID when the
             // DataFrame is analyzed or run, as it caches no such model. (The 
Rust API rejects
             // the transform itself.) Its input is the placeholder of the 
DataFrame, as in the
             // plans of `pyspark.ml`: the core resolves it, counting its 
levels for the depth
             // bound, where an input put in whole would count as one level.
-            let input =
-                DataFrame::from_sent_relation(session.clone(), 
df.dataframe.placeholder_relation());
+            let placeholder =
+                DataFrame::from_sent_relation(session.clone(), 
input.placeholder_relation());
             let relation = spark_connect_proto::Relation {
                 rel_type: 
Some(spark_connect_proto::relation::RelType::MlRelation(
-                    Box::new(model.build_ml_relation(&input).to_pyerr()?),
+                    
Box::new(model.build_ml_relation(&placeholder).to_pyerr()?),
                 )),
                 ..Default::default()
             };
-            return Ok(PyDataFrame::new(
-                DataFrame::from_relation(session, relation, None).to_pyerr()?,
-            ));
+            DataFrame::from_relation(session, relation, None).to_pyerr()?
+        } else {
+            py.detach(|| model.transform(&input).map_err(Box::new))
+                .to_pyerr()?
+        };
+        // The JVM model appends its output columns, and keeps the columns of 
its input, in place.
+        let mut columns = Vec::new();
+        if let Some((kept, field)) = &array {
+            columns.push((field.name.clone(), exact_column(kept)));
         }
-        let out = py
-            .detach(|| model.transform(&df.dataframe).map_err(Box::new))
-            .to_pyerr()?;
-        Ok(PyDataFrame::new(out))
+        if let Some(output) = &vectors.output {
+            columns.push((output.clone(), vector_to_array(output)));
+        }
+        let out = if columns.is_empty() {
+            out
+        } else {
+            out.with_columns(columns)
+        };
+        Ok(PyDataFrame::new(match &array {
+            Some((kept, _)) => out.drop(vec![kept.as_str()]),
+            None => out,
+        }))
     }
 }
 
@@ -455,6 +640,9 @@ impl PyStandardScaler {
             inner: StandardScaler::new(),
             unsendable: Vec::new(),
         };
+        // As PySpark's, which scales the values to (x - mean) / std: the JVM 
scaler centers them
+        // only with `withMean`, false by default, a param that PySpark's 
scaler does not have.
+        apply(&mut this, "withMean", Converted::Bool(true));
         init_params(
             &mut this,
             "StandardScaler",
diff --git a/docs/compatibility.md b/docs/compatibility.md
index 09738c70..29cd5d6b 100644
--- a/docs/compatibility.md
+++ b/docs/compatibility.md
@@ -162,10 +162,12 @@ two runs, were equal. For reproducible values, use the 
`_with_seed` variants
 
 The native `spark_connect::ml::LogisticRegression` fits Spark's JVM
 `org.apache.spark.ml.classification.LogisticRegression` through the Connect ML
-protocol. Training features must be ML vectors; convert an array column with
-`array_to_vector` before fitting. This differs from the deprecated Python
-`pyspark.ml.connect.classification.LogisticRegression`, which uses array 
features
-and PyTorch training.
+protocol. In the Rust API, training features must be ML vectors; convert an 
array column
+with `array_to_vector` before fitting. The Python class takes an array column 
of numbers too,
+as the deprecated `pyspark.ml.connect.classification.LogisticRegression` of 
PySpark does (see
+below), but fits the JVM estimator, where PySpark's trains with PyTorch: its 
model outputs the
+JVM's `rawPrediction` and `probability` vectors and a double `prediction`, 
where PySpark's
+outputs a `bigint` prediction and an `array<double>` probability.
 
 Fitting returns a server-cached model. Prediction uses that model's object
 reference and must use the same Spark session. Models are obtained through
@@ -193,8 +195,17 @@ DataFrame, as PySpark's do, and run on the server: a 
pandas DataFrame is sent th
 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`.
+returns `0.6000000238418579`). The native scalers, and the native estimators 
of a
+`featuresCol`, take the array columns of numbers that PySpark's take, as well 
as ML vectors: a
+fit, and the transform of its model, read the schema of the DataFrame, as 
PySpark's transform
+reads its columns, and send an array `inputCol` of a scaler, or `featuresCol` 
of another
+estimator, as the vector (`array_to_vector`) that the JVM reads; the transform 
outputs the
+array column as it was. The models of `StandardScaler` and `MaxAbsScaler` 
output an
+`array<double>` (`vector_to_array`), as PySpark's do, also of a vector input, 
which PySpark's
+scalers do not take. The scaled values are the JVM's doubles, also of an array 
of floats
+(`0.3333333333333333` where PySpark's float32 give `0.3333333432674408`).
+`StandardScaler` scales to `(x - mean) / std`, as PySpark's does: its 
constructor sends the
+`withMean` of Spark's scaler, which is false by default and which PySpark's 
scaler does not have.
 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
diff --git a/python/tests/test_dropin_e2e.py b/python/tests/test_dropin_e2e.py
index f67af307..8f81e551 100644
--- a/python/tests/test_dropin_e2e.py
+++ b/python/tests/test_dropin_e2e.py
@@ -5521,8 +5521,10 @@ def 
test_decision_tree_classifier_rejects_invalid_parameters_and_training_data(s
 
     with pytest.raises(Exception):
         DecisionTreeClassifier().fit(training.drop("features"))
+    # An array of numbers is taken as the vector of its numbers, as PySpark's 
estimators take
+    # arrays; an array of strings is not.
     with pytest.raises(Exception):
-        
DecisionTreeClassifier().fit(training.withColumn("features",F.array(F.lit(1.0))))
+        
DecisionTreeClassifier().fit(training.withColumn("features",F.array(F.lit("a"))))
 
 
 def _decision_tree_regressor():
diff --git a/python/tests/test_ml_e2e.py b/python/tests/test_ml_e2e.py
index e0c93f75..2d5af620 100644
--- a/python/tests/test_ml_e2e.py
+++ b/python/tests/test_ml_e2e.py
@@ -76,7 +76,9 @@ def 
test_ml_connect_random_forest_null_bootstrap_fits_as_pyspark(session):
 
 def test_ml_connect_scalers_fit_and_transform_as_pyspark(session):
     # pyspark.ml.connect's StandardScaler, MaxAbsScaler and StringIndexer: the 
server fits each one
-    # and caches the model, and the transform of the model gives the values of 
PySpark 4.3.0.
+    # and caches the model, and the transform of the model gives the values of 
Spark's scalers.
+    # The scalers take a vector too, which PySpark's do not, and output an 
array<double>, as
+    # PySpark's do (see 
test_ml_connect_scalers_and_estimators_take_the_array_columns_of_pyspark).
     from pyspark.ml.connect.feature import MaxAbsScaler, StandardScaler, 
StringIndexer
     from pyspark.ml.connect.functions import array_to_vector
 
@@ -87,12 +89,14 @@ def 
test_ml_connect_scalers_fit_and_transform_as_pyspark(session):
     def rows(frame, column):
         return [row[column] for row in frame.orderBy("x").collect()]
 
+    # (x - mean) / std, of the means 4 and the standard deviations 2 of the 
columns.
     scaled = StandardScaler(inputCol="v", outputCol="o").fit(df).transform(df)
-    values = [v.toArray().tolist() for v in rows(scaled, "o")]
-    assert values == [[1.0, 2.0], [2.0, 1.0], [3.0, 3.0]]
+    assert scaled.schema["o"].dataType.simpleString() == "array<double>"
+    assert rows(scaled, "o") == [[-1.0, 0.0], [0.0, -1.0], [1.0, 1.0]]
 
     maxabs = MaxAbsScaler(inputCol="v", outputCol="o").fit(df).transform(df)
-    values = [v.toArray().tolist() for v in rows(maxabs, "o")]
+    assert maxabs.schema["o"].dataType.simpleString() == "array<double>"
+    values = rows(maxabs, "o")
     assert values[0] == pytest.approx([1 / 3, 2 / 3]) and values[2] == [1.0, 
1.0]
 
     indexed = StringIndexer(inputCol="s", outputCol="o").fit(df).transform(df)
@@ -475,6 +479,85 @@ def 
test_ml_connect_evaluators_take_the_columns_and_the_pandas_frames_of_pyspark
         accuracy.evaluate([(1, 1)])
 
 
+def 
test_ml_connect_scalers_and_estimators_take_the_array_columns_of_pyspark(session):
+    # The examples of PySpark's MaxAbsScaler, StandardScaler and 
LogisticRegression, whose
+    # pyspark.ml.connect classes compute on arrays: an array of numbers is 
sent as the vector that
+    # the JVM estimators and models read, the transform keeps the array as it 
is, and a scaler
+    # outputs an array<double>, as PySpark's, with the values of PySpark 
4.3.0. StandardScaler
+    # scales to (x - mean) / std, as PySpark's, with the withMean of the JVM 
scaler.
+    from pyspark.ml.connect.classification import LogisticRegression
+    from pyspark.ml.connect.clustering import KMeans
+    from pyspark.ml.connect.feature import MaxAbsScaler, StandardScaler
+    from pyspark.sql import functions as F
+
+    features = [[1.0, 2.0], [2.0, -1.0], [-3.0, -2.0]]
+    dataset = session.createDataFrame([(f,) for f in features], 
schema=["features"])
+    scaler = MaxAbsScaler(inputCol="features", outputCol="scaled_features")
+    transformed = scaler.fit(dataset).transform(dataset)
+    assert transformed.schema.simpleString() == (
+        "struct<features:array<double>,scaled_features:array<double>>"
+    )
+    assert [tuple(row) for row in transformed.collect()] == [
+        ([1.0, 2.0], [0.3333333333333333, 1.0]),
+        ([2.0, -1.0], [0.6666666666666666, -0.5]),
+        ([-3.0, -2.0], [-1.0, -1.0]),
+    ]
+    # Arrays of ints and of decimals, which PySpark's MaxAbsScaler takes too, 
are kept as they are.
+    for element in ("int", "decimal(10,2)"):
+        typed = 
dataset.select(F.col("features").cast(f"array<{element}>").alias("features"))
+        transformed = scaler.fit(typed).transform(typed)
+        assert transformed.schema.simpleString() == (
+            f"struct<features:array<{element}>,scaled_features:array<double>>"
+        )
+        assert [row.scaled_features for row in transformed.collect()] == [
+            [0.3333333333333333, 1.0],
+            [0.6666666666666666, -0.5],
+            [-1.0, -1.0],
+        ], element
+
+    scaler = StandardScaler(inputCol="features", outputCol="scaled_features")
+    transformed = scaler.fit(dataset).transform(dataset)
+    assert transformed.schema.simpleString() == (
+        "struct<features:array<double>,scaled_features:array<double>>"
+    )
+    rows = transformed.collect()
+    assert [row.features for row in rows] == features
+    mean = [0.0, -1 / 3]
+    std = [7**0.5, (13 / 3) ** 0.5]  # The sample standard deviations of the 
columns.
+    for row in rows:
+        expected = [(value - m) / s for value, m, s in zip(row.features, mean, 
std)]
+        assert row.scaled_features == pytest.approx(expected, rel=1e-12)
+    # The first row of PySpark 4.3.0's example.
+    assert rows[0].scaled_features == pytest.approx(
+        [0.3779644730092272, 1.1208970766356101], rel=1e-12)
+
+    # LogisticRegression is Spark's JVM estimator here, without the torch 
params of PySpark's
+    # (learningRate), and the labels are ints, as in PySpark's example.
+    labeled = session.createDataFrame(
+        [([1.0, 2.0], 1), ([2.0, -1.0], 1), ([-3.0, -2.0], 0), ([-1.0, -2.0], 
0)],
+        schema=["features", "label"],
+    )
+    model = LogisticRegression(maxIter=20).fit(labeled)
+    transformed = model.transform(labeled)
+    assert transformed.columns[:2] == ["features", "label"]
+    assert transformed.schema["features"].dataType.simpleString() == 
"array<double>"
+    assert [(row.features, row.prediction) for row in transformed.collect()] 
== [
+        ([1.0, 2.0], 1.0),
+        ([2.0, -1.0], 1.0),
+        ([-3.0, -2.0], 0.0),
+        ([-1.0, -2.0], 0.0),
+    ]
+
+    # The array<double> of a scaler is the input of the next estimator, as in 
PySpark.
+    scaler = MaxAbsScaler(inputCol="features", outputCol="scaled")
+    scaled = scaler.fit(labeled).transform(labeled)
+    model = LogisticRegression(featuresCol="scaled", maxIter=20).fit(scaled)
+    assert [row.prediction for row in model.transform(scaled).collect()] == 
[1.0, 1.0, 0.0, 0.0]
+    clusters = KMeans(featuresCol="scaled", k=2, 
seed=1).fit(scaled).transform(scaled)
+    assert clusters.schema["scaled"].dataType.simpleString() == "array<double>"
+    assert len({row.prediction for row in clusters.collect()}) == 2
+
+
 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 fb982286..4e4d280b 100644
--- a/python/tests/test_ml_offline.py
+++ b/python/tests/test_ml_offline.py
@@ -181,21 +181,150 @@ def 
test_ml_connect_fitted_scalers_transform_the_cached_model(ml_mock):
         fit = _commands_but_deletes(service, sent)[0].ml_command.fit
         assert fit.estimator.name == name
         assert fit.estimator.type == pb2.MlOperator.OPERATOR_TYPE_ESTIMATOR
+        # StandardScaler also sends withMean, as PySpark's scales to (x - 
mean) / std.
         assert dict(fit.params.params) == {
             "inputCol": pb2.Expression.Literal(string=column),
             "outputCol": pb2.Expression.Literal(string="o"),
+            **({"withMean": pb2.Expression.Literal(boolean=True)} if cls is 
StandardScaler else {}),
         }
         assert fit.dataset == _relation(df)
 
         scaled = models[-1].transform(df)
         assert len(service.execute_requests) == sent + 1
-        transform = _relation(scaled).ml_relation.transform
+        relation = _relation(scaled)
+        if cls is not StringIndexer:
+            # The vector that the JVM scaler outputs is sent as the 
array<double> of PySpark's.
+            assert _aliases(relation.with_columns) == [(["o"], 
_vector_to_array("o"))]
+            relation = relation.with_columns.input
+        transform = relation.ml_relation.transform
         assert transform.obj_ref == pb2.ObjectRef(id="model-1")
         assert not transform.HasField("transformer")
         assert transform.input == _relation(df)
         assert transform.params.params["outputCol"] == 
pb2.Expression.Literal(string="o")
 
 
+def _attribute(name):
+    # The text of the column of the name `name` exactly, as PySpark's 
col("`name`") sends it.
+    return f'unresolved_attribute {{ unparsed_identifier: "`{name}`" 
is_metadata_column: false }}'
+
+
+def _array_to_vector(name):
+    # The text of PySpark's array_to_vector(col("`name`")).
+    return (
+        'unresolved_function { function_name: "array_to_vector" '
+        f'arguments {{ {_attribute(name)} }} }}'
+    )
+
+
+def _vector_to_array(name):
+    # The text of PySpark's vector_to_array(col("`name`")), of its default 
dtype, float64.
+    return (
+        'unresolved_function { function_name: "vector_to_array" '
+        f'arguments {{ {_attribute(name)} }} arguments {{ literal {{ string: 
"float64" }} }} }}'
+    )
+
+
+def _aliases(with_columns):
+    # The names and the expressions of the columns of a WithColumns relation.
+    return [(list(alias.name), _text(alias.expr)) for alias in 
with_columns.aliases]
+
+
+def 
test_ml_connect_native_estimators_take_the_array_columns_of_pyspark(ml_mock):
+    # As PySpark's pyspark.ml.connect classes, which compute on arrays: the 
fit of a native scaler,
+    # or of an estimator of a featuresCol, and the transform of its model find 
the column in the
+    # schema of the DataFrame, which they read once, regardless of case as 
Spark resolves it, and
+    # send an array of numbers as PySpark's array_to_vector of it, the vector 
that the JVM reads.
+    # The transform keeps the array in a column of its own, which takes its 
place again in the
+    # output, as PySpark's transform keeps its input columns, and the vector 
that a scaler outputs
+    # is PySpark's vector_to_array of it, an array<double>. A vector, another 
type and the column
+    # of StringIndexer, which reads no vector, are sent as they are.
+    import pyspark.ml.connect as connect
+    from _mock_connect_server import ddl_data_type
+    from pyspark.ml.linalg import VectorUDT
+
+    spark, service = ml_mock
+    models = []  # Kept alive, so that no model is released during the checks.
+    scalers = (connect.MaxAbsScaler, connect.StandardScaler)
+
+    def requests(estimator, reads=1):
+        # The Fit of estimator, and the relation of the transform of its 
model, of a new
+        # DataFrame, whose schema the mock server answers.
+        df = spark.range(1)
+        analyzed = len(service.analyze_requests)
+        sent = len(service.execute_requests)
+        service.execute_payload = _operator_info("model-1")
+        models.append(estimator.fit(df))
+        fit = _commands_but_deletes(service, sent)[0].ml_command.fit
+        transformed = _relation(models[-1].transform(df))
+        assert len(service.analyze_requests) == analyzed + reads, estimator
+        return df, fit, transformed
+
+    service.data_type = ddl_data_type(
+        "id bigint, Features array<int>, label double, s string, words 
array<string>, "
+        "d array<decimal(10,2)>"
+    )
+    # Every native estimator of a featuresCol, of its default "features" here.
+    featured = [name for name, params in _NATIVE_PARAMS.items() if 
"featuresCol" in params]
+    assert {"LogisticRegression", "KMeans"} <= set(featured)
+    estimators = [cls(inputCol="features", outputCol="o") for cls in scalers] 
+ [
+        getattr(connect, name)() for name in featured
+    ]
+    for estimator in estimators:
+        name = type(estimator).__name__
+        df, fit, transformed = requests(estimator)
+        # The params name the column as they were given, and the dataset has 
the vector of the
+        # array in its place.
+        params = {"inputCol": "features", "outputCol": "o"} if type(estimator) 
in scalers else {}
+        sent = {k: v.string for k, v in fit.params.params.items() if k != 
"withMean"}
+        assert sent == params, name
+        assert ("withMean" in fit.params.params) == (name == 
"StandardScaler"), name
+        assert fit.dataset.with_columns.input == _relation(df), name
+        assert _aliases(fit.dataset.with_columns) == [
+            (["Features"], _array_to_vector("Features"))
+        ], name
+
+        (kept,) = transformed.drop.column_names
+        output = transformed.drop.input.with_columns
+        transform = output.input.ml_relation.transform
+        assert transform.obj_ref == pb2.ObjectRef(id="model-1"), name
+        assert transform.input.with_columns.input == _relation(df), name
+        assert _aliases(transform.input.with_columns) == [
+            ([kept], _attribute("Features")),
+            (["Features"], _array_to_vector("Features")),
+        ], name
+        scaled = [(["o"], _vector_to_array("o"))] if type(estimator) in 
scalers else []
+        assert _aliases(output) == [(["Features"], _attribute(kept))] + 
scaled, name
+
+    # An array of decimals, which array_to_vector does not take, is cast to an 
array<double>.
+    _, fit, _ = requests(connect.MaxAbsScaler(inputCol="d", outputCol="o"))
+    cast = (
+        f"cast {{ expr {{ {_attribute('d')} }} "
+        "type { array { element_type { double { } } contains_null: true } } }"
+    )
+    vector = f'unresolved_function {{ function_name: "array_to_vector" 
arguments {{ {cast} }} }}'
+    assert _aliases(fit.dataset.with_columns) == [(["d"], vector)]
+
+    for estimator, reads in [
+        (connect.LogisticRegression(featuresCol="s"), 1),
+        (connect.KMeans(featuresCol="words"), 1),
+        (connect.StringIndexer(inputCol="features", outputCol="o"), 0),
+    ]:
+        df, fit, transformed = requests(estimator, reads)
+        assert fit.dataset == _relation(df), estimator
+        assert transformed.ml_relation.transform.input == _relation(df), 
estimator
+
+    service.data_type = _data_type_proto(
+        T.StructType([T.StructField("features", VectorUDT())])
+    ).SerializeToString()
+    for estimator in [connect.MaxAbsScaler(inputCol="features", 
outputCol="o"), connect.KMeans()]:
+        df, fit, transformed = requests(estimator)
+        assert fit.dataset == _relation(df), estimator
+        if type(estimator) in scalers:
+            assert _aliases(transformed.with_columns) == [(["o"], 
_vector_to_array("o"))]
+            transformed = transformed.with_columns.input
+        assert transformed.ml_relation.transform.input == _relation(df), 
estimator
+
+
 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
@@ -479,11 +608,14 @@ def _sent_name(name, param):
 def _defaults_sent(name):
     # The params that a native class sends unless it is given them: the metric 
of
     # MulticlassClassificationEvaluator and the probability column of
-    # BinaryClassificationEvaluator, which PySpark's constructor sets.
+    # BinaryClassificationEvaluator, which PySpark's constructor sets, and the 
centering of
+    # StandardScaler, as PySpark's scales to (x - mean) / std.
     if name == "MulticlassClassificationEvaluator":
         return {"metricName": ("string", "accuracy")}
     if name == "BinaryClassificationEvaluator":
         return {"rawPredictionCol": ("string", "probability")}
+    if name == "StandardScaler":
+        return {"withMean": ("boolean", True)}
     return {}
 
 


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

Reply via email to