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 f9c2e1f3 [SPARK-61611][CONNECT][PYTHON] Use PySpark's own scalers of 
pyspark.ml.connect, and check the labels of the native LogisticRegression as 
PySpark does, in the Python client
f9c2e1f3 is described below

commit f9c2e1f3daf5721bca12818350f209000add8bef
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Fri Nov 13 13:43:23 2026 +0900

    [SPARK-61611][CONNECT][PYTHON] Use PySpark's own scalers of 
pyspark.ml.connect, and check the labels of the native LogisticRegression as 
PySpark does, in the Python client
    
    ### What changes were proposed in this pull request?
    
    A follow-up of the post-merge review of #574 (SPARK-61545), with the 
decisions of its author:
    
    - `pyspark.ml.connect.feature` is now PySpark 4.3.0's own module, vendored 
byte-identical and checked by the drift gate. `StandardScaler`, `MaxAbsScaler` 
and `ArrayAssembler` (with their models) come from it. They run over this 
client's transport: the fit uses `summarize_dataframe`, and the transform uses 
closures that the server's Python workers run.
    - The drop-in's native `StringIndexer` and `VectorAssembler` are set on 
that module by `pyspark.ml.connect`'s `__init__`, so `from 
pyspark.ml.connect.feature import StringIndexer` still works.
    - The PyO3 scaler wrappers and their dead arms in `ml.rs` are removed.
    - The Rust API keeps `spark_connect::ml::StandardScaler` and 
`MaxAbsScaler`. `StandardScaler` gets `set_with_mean` and `with_mean`; before, 
only the Python constructor sent `withMean=true`.
    - The native `LogisticRegression` fit runs PySpark's label checks before 
the JVM fit, with PySpark's ValueErrors: "Training dataset distinct labels must 
>= 2." and "Training labels must be integers in [0, numClasses).". It runs 
PySpark's `collect_set(label)` query. It doesn't run PySpark's count and 
`first(array_size(features))`: they don't feed the checks, and `array_size` 
raises on the vector features that the native fit takes.
    - Docs: the native estimators of a `featuresCol` are documented as taking 
vectors, arrays and pandas, unlike classic `pyspark.ml`'s VectorUDT-only 
estimators; the code comment says so too. The JVM-scaler caveats are dropped, 
and the label checks are documented.
    
    ### Why are the changes needed?
    
    For parity with PySpark 4.3.0. Each case is the client before this change, 
then PySpark (and the client after):
    
    - `StandardScaler` fit on one row: `[(0.0, 0.0)]` / `ValueError: Standard 
deviation evaluation requires more than one row data.`
    - `MaxAbsScaler` on `[[1.0, None], [-3.0, -2.0]]`: `FAILED_EXECUTE_UDF` 
(NOT_NULL_ASSERT_VIOLATION) / `[(0.333..., None), (1.0, None)]`.
    - `MaxAbsScaler` with a NaN: finite values from the JVM, which ignores NaN 
/ `None` in that slot.
    - A transform on another session: `CONNECT_ML.CACHE_INVALID` / works.
    - Empty arrays, `array<boolean>`, and a shorter array: errors or silent 
truncation / PySpark's results.
    - `LogisticRegression` on labels `{0, 2}`, `{1, 2}`, or a single class: 
fitted / `ValueError`.
    
    An edge-case probe of about 24 scaler cases gives line-for-line the same 
output on PySpark 4.3.0 and on the client.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes. The `pyspark.ml.connect` scalers are PySpark's own, with PySpark's 
values, errors, Params API, models and save/load, and `ArrayAssembler` is 
added. `LogisticRegression` raises PySpark's ValueErrors for bad labels before 
fitting. The Rust `StandardScaler` has `set_with_mean`.
    
    ### How was this patch tested?
    
    - The scaler tests in `test_ml_offline.py` and `test_ml_e2e.py` are 
rewritten against the vendored behavior. The new label-check tests, offline and 
e2e, fail with the check disabled.
    - On the tree merged with the latest master, with `TZ=UTC` and protobuf's 
default upb backend:
      - the Rust lib tests (660 and 220) and the drift gate;
      - `test_ml_offline.py`: 136 passed;
      - `test_ml_e2e.py` against Spark 4.3.0: 29 passed;
      - the ML tests of `test_dropin_e2e.py`.
    - On the branch:
      - CI's offline set: 3283 passed;
      - the other native ML e2e files: 87 passed;
      - the `--no-run` builds, `cargo fmt`, the stub audit and the ruff gates.
    
    ### 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 #607 from HyukjinKwon/SPARK-61611-ml-connect-scalers.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/pyspark-rs/src/lib.rs          |   2 -
 crates/pyspark-rs/src/ml.rs           | 283 +++++++---------------
 crates/spark-connect/src/ml.rs        |  33 +++
 docs/compatibility.md                 |  78 +++---
 pyproject.toml                        |   1 +
 python/pyspark/ml/connect/__init__.py |  11 +-
 python/pyspark/ml/connect/feature.py  | 433 +++++++++++++++++++++++++++++++++-
 python/tests/_mock_connect_server.py  |   9 +
 python/tests/test_ml_e2e.py           |  86 +++++--
 python/tests/test_ml_offline.py       | 433 +++++++++++++++-------------------
 scripts/check_vendored_upstream.sh    |   3 +
 11 files changed, 861 insertions(+), 511 deletions(-)

diff --git a/crates/pyspark-rs/src/lib.rs b/crates/pyspark-rs/src/lib.rs
index eedec08d..00c9c703 100644
--- a/crates/pyspark-rs/src/lib.rs
+++ b/crates/pyspark-rs/src/lib.rs
@@ -238,8 +238,6 @@ fn _pyspark(_py: Python<'_>, m: &Bound<'_, PyModule>) -> 
PyResult<()> {
 
     // Register ML classes (pyspark.ml.connect)
     m.add_class::<ml::PyMLModel>()?;
-    m.add_class::<ml::PyStandardScaler>()?;
-    m.add_class::<ml::PyMaxAbsScaler>()?;
     m.add_class::<ml::PyStringIndexer>()?;
     m.add_class::<ml::PyVectorAssembler>()?;
     m.add_class::<ml::PyLogisticRegression>()?;
diff --git a/crates/pyspark-rs/src/ml.rs b/crates/pyspark-rs/src/ml.rs
index 0ba22f09..615f4685 100644
--- a/crates/pyspark-rs/src/ml.rs
+++ b/crates/pyspark-rs/src/ml.rs
@@ -19,10 +19,10 @@ use spark_connect::ml::{
     BinaryClassificationEvaluator, BisectingKMeans, Classifier, CrossValidator,
     DecisionTreeClassifier, DecisionTreeRegressor, Estimator, Evaluator, 
FMClassifier,
     GBTClassifier, GBTRegressor, GaussianMixture, GeneralizedLinearRegression, 
KMeans,
-    LinearRegression, LinearSVC, LogisticRegression, MaxAbsScaler, MlOperator, 
MlVector, Model,
+    LinearRegression, LinearSVC, LogisticRegression, MlOperator, MlVector, 
Model,
     MulticlassClassificationEvaluator, MultilayerPerceptronClassifier, 
NaiveBayes, OneVsRest,
     Params, Pipeline, RandomForestClassifier, RandomForestRegressor, 
RegressionEvaluator,
-    StandardScaler, StringIndexer, Transformer, VectorAssembler,
+    StringIndexer, Transformer, VectorAssembler,
 };
 use spark_connect::DataFrame;
 
@@ -370,8 +370,7 @@ fn active_dataframe(pdf: &Bound<'_, PyAny>) -> 
PyResult<DataFrame> {
 }
 
 /// The columns that the fit of a class of PySpark's `pyspark.ml.connect` 
reads, as the params
-/// that name them, of their defaults: LogisticRegression's selects its 
features and its labels,
-/// and a scaler's its `inputCol`, which has no default.
+/// that name them, of their defaults: LogisticRegression's selects its 
features and its labels.
 type Reads = &'static [(&'static str, Option<&'static str>)];
 
 const LOGISTIC_REGRESSION_READS: Reads = &[
@@ -379,8 +378,6 @@ const LOGISTIC_REGRESSION_READS: Reads = &[
     ("labelCol", Some("label")),
 ];
 
-const SCALER_READS: Reads = &[("inputCol", None)];
-
 /// The string param `name` of `params` if it is set, else `default`. None 
when it is set to
 /// another value (a null), or is not set and has no default, which the server 
rejects.
 fn string_or(params: &Params, name: &str, default: Option<&str>) -> 
Option<String> {
@@ -407,19 +404,36 @@ fn read_columns(params: &Params, reads: Reads) -> 
Option<Vec<String>> {
 /// KeyError of pandas for a missing column, as PySpark's 
`aggregate_dataframe`. So the JVM
 /// estimator checks no other column, as PySpark's fit reads no other, and the 
dataset may have
 /// an output column (a `prediction`, say). The other estimators, of the 
classes that PySpark's
-/// `pyspark.ml.connect` does not have, fit the whole dataset, as their JVM 
estimators read it.
+/// `pyspark.ml.connect` does not have, fit the whole dataset, as their JVM 
estimators read it, and
+/// take vectors, arrays of numbers and pandas DataFrames, where classic 
`pyspark.ml` estimators
+/// take only a `VectorUDT` column.
 fn fit_native<T>(
     slf: &Bound<'_, T>,
     dataset: &Bound<'_, PyAny>,
     reads: Option<Reads>,
 ) -> PyResult<PyMLModel>
+where
+    T: Native + PyClass,
+    T::Core: Estimator,
+{
+    fit_native_checked(slf, dataset, reads, |_, _, _| Ok(()))
+}
+
+/// [`fit_native`], which first runs `check` on the DataFrame that the fit 
sends, of the estimator
+/// `estimator`: the checks that PySpark's `_fit` makes of its dataset before 
it fits.
+fn fit_native_checked<T>(
+    slf: &Bound<'_, T>,
+    dataset: &Bound<'_, PyAny>,
+    reads: Option<Reads>,
+    check: impl FnOnce(Python<'_>, &T::Core, &DataFrame) -> PyResult<()>,
+) -> PyResult<PyMLModel>
 where
     T: Native + PyClass,
     T::Core: Estimator,
 {
     let py = slf.py();
     let dataset = dataset_of(dataset, "fit", "select")?;
-    let mut estimator = snapshot(slf)?;
+    let estimator = snapshot(slf)?;
     let columns = reads.and_then(|reads| read_columns(estimator.params(), 
reads));
     let (df, select) = match dataset {
         Dataset::Spark(df) => (df, columns),
@@ -439,45 +453,59 @@ where
         Some(columns) => df.select(columns.iter().map(|name| 
exact_column(name))),
         None => df,
     };
+    check(py, &estimator, &df)?;
     let df = match array {
         Some(field) => df.with_column(&field.name, vector_of(&field)),
         None => df,
     };
-    // A scaler's JVM fit checks that its output column does not exist yet, 
and reads only its
-    // input column, as PySpark's scaler fit does. So the fit sends no 
outputCol, and the model
-    // keeps it.
-    let output = match vectors.output.is_some() {
-        true => take_output_col(estimator.params_mut()),
-        false => None,
-    };
-    let mut model = fit_core(py, estimator, &df)?;
-    keep_output_col(model.model.params_mut(), output);
-    Ok(model)
+    fit_core(py, estimator, &df)
 }
 
-/// The `outputCol` of the params of a scaler, as they hold it: a string or a 
null, or None when
-/// it is not set (see [`take_output_col`]).
-type OutputCol = Option<Option<String>>;
-
-/// Take the `outputCol` off `params`, and return it (see [`fit_native`]).
-fn take_output_col(params: &mut Params) -> OutputCol {
-    // None when it is not set, so that there is no outputCol to keep.
-    params.get_param("outputCol")?;
-    let value = string_param(params, "outputCol");
-    *params = std::mem::take(params).clear_param("outputCol");
-    Some(value)
-}
-
-/// Set the `outputCol` of `params` back to `output`, as [`take_output_col`] 
took it.
-fn keep_output_col(params: &mut Params, output: OutputCol) {
-    let Some(value) = output else {
-        return;
-    };
-    let taken = std::mem::take(params);
-    *params = match value {
-        Some(value) => taken.set_param_string("outputCol", &value),
-        None => taken.set_param_null("outputCol"),
+/// The checks of the labels of a LogisticRegression fit, as PySpark's `_fit` 
makes them of the
+/// labels that its query collects: `collect_set` of the label column, which 
has the distinct
+/// labels and no null. There must be at least two, each an integer in `[0, 
numClasses)`, with
+/// PySpark's ValueErrors. PySpark's query also counts the rows and reads the 
size of the features,
+/// which these checks do not read, and array_size raises on the vector 
features that the native
+/// LogisticRegression takes, so that query is not sent.
+fn check_labels(py: Python<'_>, df: &DataFrame, label: &str) -> PyResult<()> {
+    use spark_connect::functions::{col, collect_set};
+    use spark_connect::row::Value;
+
+    let rows = interruptible(py, &df.spark_session(), || {
+        df.agg(vec![collect_set(col(label)).expression().clone()])
+            .collect()
+            .map_err(Box::new)
+    })?;
+    let classes = match rows.first().and_then(|row| row.get(0)) {
+        Some(Value::List(classes)) => classes.as_slice(),
+        _ => &[],
     };
+    if classes.len() < 2 {
+        return Err(PyValueError::new_err(
+            "Training dataset distinct labels must >= 2.",
+        ));
+    }
+    // A label is in `range(0, numClasses)` as PySpark's `in` finds it: an 
integer, or a number
+    // that equals one (a bool is 0 or 1).
+    let integer = |value: i64| value >= 0 && value.unsigned_abs() < 
classes.len() as u64;
+    let number = |value: f64| value.fract() == 0.0 && value >= 0.0 && value < 
classes.len() as f64;
+    let in_range = classes.iter().all(|class| match class {
+        Value::Byte(v) => integer(i64::from(*v)),
+        Value::Short(v) => integer(i64::from(*v)),
+        Value::Integer(v) => integer(i64::from(*v)),
+        Value::Long(v) => integer(*v),
+        Value::Float(v) => number(f64::from(*v)),
+        Value::Double(v) => number(*v),
+        Value::Decimal { value, .. } => value.parse::<f64>().is_ok_and(number),
+        Value::Bool(v) => integer(i64::from(*v)),
+        _ => false,
+    });
+    if !in_range {
+        return Err(PyValueError::new_err(
+            "Training labels must be integers in [0, numClasses).",
+        ));
+    }
+    Ok(())
 }
 
 /// The fit of a native estimator whose core cannot fit it, as Pipeline and 
CrossValidator.
@@ -514,43 +542,31 @@ fn fit_core<C: Estimator>(py: Python<'_>, mut estimator: 
C, df: &DataFrame) -> P
     })
 }
 
-/// 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
+/// The columns of a native estimator, and of the model of its fit, that the 
JVM reads 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 the `array<double>` that 
PySpark's scalers output
-/// (their `_output_columns`, see [`vector_array`]).
+/// of the `input` column is sent as a vector by `array_to_vector`, and a 
vector as it is.
 #[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.
+    /// The vector column of the JVM estimator or model `operator`, of the 
params `params`, as
+    /// Spark's ML classes read it: those of the classification, regression 
and clustering packages
+    /// read the vector of their `featuresCol` (`features` unless set). Of the 
feature package, the
+    /// StringIndexer and the VectorAssembler 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,
             },
         }
     }
@@ -764,11 +780,11 @@ fn evaluator_input(py: Python<'_>, df: DataFrame, inputs: 
EvaluatorInputs) -> Py
     Ok(df)
 }
 
-/// The model of a class of PySpark's `pyspark.ml.connect`, 
LogisticRegression, MaxAbsScaler or
-/// StandardScaler, whose transform outputs what PySpark's 
`Transformer._transform` outputs: the
-/// columns of its `_output_columns`, of their types and in their order, 
appended to the dataset,
-/// which may not have any of them already. The other native models, of the 
classes that PySpark's
-/// `pyspark.ml.connect` does not have, output what their JVM models output, 
which check it.
+/// The model of a class of PySpark's `pyspark.ml.connect`, 
LogisticRegression, whose transform
+/// outputs what PySpark's `Transformer._transform` outputs: the columns of 
its `_output_columns`,
+/// of their types and in their order, appended to the dataset, which may not 
have any of them
+/// already. The other native models, of the classes that PySpark's 
`pyspark.ml.connect` does not
+/// have, output what their JVM models output, which check it.
 enum PySparkModel {
     /// LogisticRegressionModel: of its `featuresCol`, and its `bigint` 
prediction, and its
     /// `array<double>` probability unless its `probabilityCol` is empty 
(PySpark's `if prob_col`),
@@ -779,12 +795,6 @@ enum PySparkModel {
         prediction: Option<String>,
         probability: Option<String>,
     },
-    /// MaxAbsScalerModel or StandardScalerModel: of its `inputCol`, and its 
`array<double>`
-    /// `outputCol` (see [`Vectors`]).
-    Scaler {
-        input: Option<String>,
-        output: String,
-    },
 }
 
 impl PySparkModel {
@@ -801,14 +811,6 @@ impl PySparkModel {
                     probability: output("probabilityCol", "probability"),
                 })
             }
-            "org.apache.spark.ml.feature.MaxAbsScalerModel"
-            | "org.apache.spark.ml.feature.StandardScalerModel" => {
-                let vectors = Vectors::of(operator, params);
-                Some(Self::Scaler {
-                    input: vectors.input,
-                    output: vectors.output?,
-                })
-            }
             _ => None,
         }
     }
@@ -817,7 +819,6 @@ impl PySparkModel {
     fn input(&self) -> Option<&str> {
         match self {
             Self::LogisticRegression { features, .. } => features.as_deref(),
-            Self::Scaler { input, .. } => input.as_deref(),
         }
     }
 
@@ -829,33 +830,17 @@ impl PySparkModel {
                 probability,
                 ..
             } => prediction.iter().chain(probability).cloned().collect(),
-            Self::Scaler { output, .. } => vec![output.clone()],
         }
     }
 
     /// The transform of the empty pandas DataFrame `copy` (a shallow copy of 
it), as PySpark's
-    /// transform computes it locally. A scaler appends its `array<double>` 
output as an empty
-    /// object column, with the index of `copy`. A LogisticRegression model 
raises the ValueError of
+    /// transform computes it locally: a LogisticRegression model raises the 
ValueError of
     /// `np.stack` in PySpark's transform function, which has no array to 
stack.
-    fn transform_empty<'py>(&self, copy: &Bound<'py, PyAny>) -> 
PyResult<Bound<'py, PyAny>> {
-        let py = copy.py();
+    fn transform_empty<'py>(&self, _copy: &Bound<'py, PyAny>) -> 
PyResult<Bound<'py, PyAny>> {
         match self {
             Self::LogisticRegression { .. } => {
                 Err(PyValueError::new_err("need at least one array to stack"))
             }
-            Self::Scaler { output, .. } => {
-                let kwargs = PyDict::new(py);
-                kwargs.set_item("dtype", "object")?;
-                kwargs.set_item("index", copy.getattr("index")?)?;
-                let column = py.import("pandas")?.call_method(
-                    "Series",
-                    (PyList::empty(py),),
-                    Some(&kwargs),
-                )?;
-                let at = copy.getattr("columns")?.len()?;
-                copy.call_method1("insert", (at, output, column))?;
-                Ok(copy.clone())
-            }
         }
     }
 
@@ -963,9 +948,9 @@ impl PyMLModel {
 impl PyMLModel {
     /// The transform of the DataFrame `df`. 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`]). 
A LogisticRegression
-    /// model outputs PySpark's `bigint` prediction, and then its 
`array<double>` probability, of
-    /// the vector that the JVM model outputs in a column of its own, before 
its prediction.
+    /// its output (see [`Vectors`]). A LogisticRegression model outputs 
PySpark's `bigint`
+    /// prediction, and then its `array<double>` probability, of the vector 
that the JVM model
+    /// outputs in a column of its own, before its prediction.
     fn transform_dataframe(
         &self,
         py: Python<'_>,
@@ -1032,9 +1017,6 @@ impl PyMLModel {
             columns.push((field.name.clone(), exact_column(kept)));
             dropped.push(kept.as_str());
         }
-        if let Some(output) = &vectors.output {
-            columns.push((output.clone(), vector_array(output)));
-        }
         if let Some(PySparkModel::LogisticRegression {
             prediction: Some(prediction),
             ..
@@ -1062,94 +1044,8 @@ impl PyMLModel {
     }
 }
 
-/// StandardScaler estimator.
-#[pyclass(name = "StandardScaler", module = "pyspark.ml.connect.feature")]
-pub struct PyStandardScaler {
-    inner: StandardScaler,
-    unsendable: Vec<&'static str>,
-}
-
 const COLUMN_PARAMS: &[(&str, Kind)] = &[("inputCol", Kind::Str), 
("outputCol", Kind::Str)];
 
-#[pymethods]
-impl PyStandardScaler {
-    #[new]
-    #[pyo3(signature = (*args, **kwargs), text_signature = "(*, inputCol=None, 
outputCol=None)")]
-    fn new(args: &Bound<'_, PyTuple>, kwargs: Option<&Bound<'_, PyDict>>) -> 
PyResult<Self> {
-        let mut this = Self {
-            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",
-            &[],
-            COLUMN_PARAMS,
-            args,
-            kwargs,
-        )?;
-        Ok(this)
-    }
-    #[pyo3(name = "setInputCol")]
-    fn set_input_col<'py>(
-        slf: Bound<'py, Self>,
-        value: &Bound<'py, PyAny>,
-    ) -> PyResult<Bound<'py, Self>> {
-        set_param(slf, "inputCol", Kind::Str, value)
-    }
-    #[pyo3(name = "setOutputCol")]
-    fn set_output_col<'py>(
-        slf: Bound<'py, Self>,
-        value: &Bound<'py, PyAny>,
-    ) -> PyResult<Bound<'py, Self>> {
-        set_param(slf, "outputCol", Kind::Str, value)
-    }
-    fn fit(slf: &Bound<'_, Self>, dataset: &Bound<'_, PyAny>) -> 
PyResult<PyMLModel> {
-        fit_native(slf, dataset, Some(SCALER_READS))
-    }
-}
-
-/// MaxAbsScaler estimator.
-#[pyclass(name = "MaxAbsScaler", module = "pyspark.ml.connect.feature")]
-pub struct PyMaxAbsScaler {
-    inner: MaxAbsScaler,
-    unsendable: Vec<&'static str>,
-}
-
-#[pymethods]
-impl PyMaxAbsScaler {
-    #[new]
-    #[pyo3(signature = (*args, **kwargs), text_signature = "(*, inputCol=None, 
outputCol=None)")]
-    fn new(args: &Bound<'_, PyTuple>, kwargs: Option<&Bound<'_, PyDict>>) -> 
PyResult<Self> {
-        let mut this = Self {
-            inner: MaxAbsScaler::new(),
-            unsendable: Vec::new(),
-        };
-        init_params(&mut this, "MaxAbsScaler", &[], COLUMN_PARAMS, args, 
kwargs)?;
-        Ok(this)
-    }
-    #[pyo3(name = "setInputCol")]
-    fn set_input_col<'py>(
-        slf: Bound<'py, Self>,
-        value: &Bound<'py, PyAny>,
-    ) -> PyResult<Bound<'py, Self>> {
-        set_param(slf, "inputCol", Kind::Str, value)
-    }
-    #[pyo3(name = "setOutputCol")]
-    fn set_output_col<'py>(
-        slf: Bound<'py, Self>,
-        value: &Bound<'py, PyAny>,
-    ) -> PyResult<Bound<'py, Self>> {
-        set_param(slf, "outputCol", Kind::Str, value)
-    }
-    fn fit(slf: &Bound<'_, Self>, dataset: &Bound<'_, PyAny>) -> 
PyResult<PyMLModel> {
-        fit_native(slf, dataset, Some(SCALER_READS))
-    }
-}
-
 /// StringIndexer estimator.
 #[pyclass(name = "StringIndexer", module = "pyspark.ml.connect.feature")]
 pub struct PyStringIndexer {
@@ -1340,7 +1236,12 @@ impl PyLogisticRegression {
                 "Fitting pandas dataframe is not supported yet.",
             ));
         }
-        fit_native(slf, dataset, Some(LOGISTIC_REGRESSION_READS))
+        fit_native_checked(
+            slf,
+            dataset,
+            Some(LOGISTIC_REGRESSION_READS),
+            |py, estimator, df| check_labels(py, df, estimator.label_col()),
+        )
     }
 }
 
@@ -4504,8 +4405,6 @@ impl PyCrossValidator {
 }
 
 native!(
-    PyStandardScaler => StandardScaler,
-    PyMaxAbsScaler => MaxAbsScaler,
     PyStringIndexer => StringIndexer,
     PyVectorAssembler => VectorAssembler,
     PyLogisticRegression => LogisticRegression,
diff --git a/crates/spark-connect/src/ml.rs b/crates/spark-connect/src/ml.rs
index 6ee230cf..bc4b5fe5 100644
--- a/crates/spark-connect/src/ml.rs
+++ b/crates/spark-connect/src/ml.rs
@@ -778,6 +778,17 @@ impl StandardScaler {
         self.params.output_col_or_default(&self.operator.uid)
     }
 
+    /// Whether to center the features to mean 0 before scaling (default: 
false, as in Spark).
+    pub fn set_with_mean(mut self, value: bool) -> Self {
+        self.params = self.params.set_param_bool("withMean", value);
+        self
+    }
+
+    /// Whether the features are centered to mean 0 before scaling (default: 
false).
+    pub fn with_mean(&self) -> bool {
+        self.params.bool_or("withMean", false)
+    }
+
     fn model_from_info(
         &self,
         info: proto::ml_command_result::MlOperatorInfo,
@@ -6776,6 +6787,28 @@ mod tests {
         assert_eq!(scaler.output_col(), "my_scaled");
     }
 
+    #[test]
+    fn test_standard_scaler_with_mean() {
+        // As Spark's default, the features are not centered unless the setter 
says so.
+        let scaler = StandardScaler::new();
+        assert!(!scaler.with_mean());
+        assert!(scaler.params().get_param("withMean").is_none());
+
+        let scaler = StandardScaler::new().set_with_mean(true);
+        assert!(scaler.with_mean());
+        let bool_param = scaler.params().get_param("withMean").unwrap();
+        let Some(proto::expression::ExprType::Literal(literal)) = 
&bool_param.expr_type else {
+            panic!("withMean is not a literal");
+        };
+        assert_eq!(
+            literal.literal_type,
+            Some(proto::expression::literal::LiteralType::Boolean(true))
+        );
+
+        let scaler = scaler.set_with_mean(false);
+        assert!(!scaler.with_mean());
+    }
+
     #[test]
     fn test_operator_to_proto() {
         let op = MlOperator::new("test.Operator", OperatorType::Transformer);
diff --git a/docs/compatibility.md b/docs/compatibility.md
index 50368ea2..d8e2a8a4 100644
--- a/docs/compatibility.md
+++ b/docs/compatibility.md
@@ -230,9 +230,7 @@ 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. `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.
+`rawPredictionCol` that the JVM evaluator scores.
 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
@@ -249,41 +247,45 @@ on the server, where PySpark's compute on a pandas 
DataFrame locally: a pandas D
 through `createDataFrame` of the active session as an Arrow table of its 
columns, whose NaN elements
 of arrays and NaN values of floats stay NaN, as PySpark's local computation 
keeps them (pandas'
 conversion would make them nulls); the other columns are converted as pandas 
converts them. The
-statistics of a scaler's fit are Spark's, so the maximum of `MaxAbsScaler` 
skips a NaN element,
-where PySpark's local fit makes the scale of that feature NaN. The
-transform of one is a shallow copy of it (`copy(deep=False)`) with the output 
columns appended, of
-its index, as PySpark's makes it, of PySpark's dtypes and cells (an `int64` 
prediction, ndarrays of
-the probabilities and of the scaled values). The transform of an empty pandas 
DataFrame is computed
-without the server, which cannot infer the schema of no rows: a scaler appends 
an empty `object`
-column, and a LogisticRegression model raises the `ValueError` of PySpark's 
transform function,
-which stacks no array. Another object raises the `AttributeError` that 
PySpark's raises, of its
-`select` in a fit or an evaluate, and of its `columns` in a transform. The fit 
of
-`LogisticRegression` and of a scaler sends only the columns that PySpark's fit 
reads (the features
-and the labels, or the `inputCol`), so the JVM estimator checks no other 
column, and their models
-send only the column that PySpark's transform reads of a pandas DataFrame. For 
LogisticRegression,
-an output column of the name of a column that the fit reads still raises the 
JVM's error at the fit,
-where PySpark's raises at the transform. The transform of the model of 
`LogisticRegression` or of a
-scaler raises PySpark's `ValueError` of an output column that the DataFrame 
has already, of its
-exact name, before any transform. The fit of a scaler sends no `outputCol`, 
which the JVM fit checks
-is absent, so a scaler whose `outputCol` is its `inputCol` fits, and its model 
keeps the `outputCol`
-for its transform, which raises that `ValueError`. The other native models, of 
the
-classes that PySpark's `pyspark.ml.connect` does not have, are sent the whole 
of a pandas
-DataFrame, and their JVM models check their output columns, which the 
transform of a pandas
-DataFrame appends. The evaluators cast a prediction or a probability of another
-numeric type to a double, and send an array of probabilities 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, 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 the
-`array<double>` of PySpark's, nullable and of nullable elements as its 
`pandas_udf` outputs it,
-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`), and the cells of the transform of a pandas DataFrame 
are float64
-ndarrays, where PySpark's are float32 of float32 inputs.
+transform of a LogisticRegression model is a shallow copy of it 
(`copy(deep=False)`) with the output
+columns appended, of its index, as PySpark's makes it, of PySpark's dtypes and 
cells (an `int64`
+prediction, ndarrays of the probabilities and of the scaled values). The 
transform of an empty
+pandas DataFrame is computed without the server, which cannot infer the schema 
of no rows: a
+LogisticRegression model raises the `ValueError` of PySpark's transform 
function, which stacks no
+array. Another object raises the `AttributeError` that PySpark's raises, of 
its `select` in a fit or
+an evaluate, and of its `columns` in a transform. The fit of 
`LogisticRegression` sends only the
+columns that PySpark's fit reads (the features and the labels), so the JVM 
estimator checks no other
+column, and its model sends only the column that PySpark's transform reads of 
a pandas DataFrame.
+For LogisticRegression, an output column of the name of a column that the fit 
reads still raises the
+JVM's error at the fit, where PySpark's raises at the transform. The transform 
of the model of
+`LogisticRegression` raises PySpark's `ValueError` of an output column that 
the DataFrame has
+already, of its exact name, before any transform. The other native models, of 
the classes that
+PySpark's `pyspark.ml.connect` does not have, are sent the whole of a pandas 
DataFrame, and their
+JVM models check their output columns, which the transform of a pandas 
DataFrame appends.
+
+The fit of `LogisticRegression` checks its labels before it fits, as PySpark's 
`_fit` does, on the
+distinct labels of the server's `collect_set` of the label column (a null 
label is not one of them):
+there must be at least two, each an integer in `[0, numClasses)`, else 
PySpark's `ValueError` is
+raised. The other checks of PySpark's fit (the row count, the size of the 
features) are not made, as
+they do not raise. The evaluators cast a prediction or a probability of 
another numeric type to a
+double, and send an array of probabilities 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 estimators of a `featuresCol` take vectors, arrays of numbers and 
pandas DataFrames
+alike: 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 `featuresCol` as the vector 
(`array_to_vector`) that
+the JVM reads; the transform outputs the array column as it was. Classic 
`pyspark.ml` estimators
+take only a `VectorUDT` column, while the native estimators that PySpark's 
`pyspark.ml.connect` does
+not have (GBTRegressor, NaiveBayes, BisectingKMeans, GaussianMixture, 
GeneralizedLinearRegression,
+...) take the three kinds of input that the classes of `pyspark.ml.connect` 
take, as they exist only
+in this client.
+
+The scalers of `pyspark.ml.connect`, `StandardScaler` and `MaxAbsScaler`, are 
PySpark's own classes
+(`pyspark.ml.connect.feature`), vendored unchanged: they fit with PySpark's 
`summarize_dataframe`
+and transform with PySpark's closures, on the server for a Spark DataFrame and 
locally for a pandas
+DataFrame, so their values, types and errors are PySpark's, and they send no 
ML request. The Rust API keeps its `StandardScaler` and `MaxAbsScaler`,
+the JVM's scalers, whose `StandardScaler::set_with_mean` centers the features 
(`withMean`, false by
+default).
 
 ## Native RandomForestRegressor
 
diff --git a/pyproject.toml b/pyproject.toml
index 65301374..208b487e 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -175,6 +175,7 @@ extend-exclude = [
     "python/pyspark/sql/connect/proto/example_plugins_pb2.py",
     "python/pyspark/sql/connect/proto/example_plugins_pb2.pyi",
     "python/pyspark/ml/connect/base.py",
+    "python/pyspark/ml/connect/feature.py",
     "python/pyspark/ml/connect/functions.py",
     "python/pyspark/ml/param/__init__.py",
     "python/pyspark/ml/param/_shared_params_code_gen.py",
diff --git a/python/pyspark/ml/connect/__init__.py 
b/python/pyspark/ml/connect/__init__.py
index 6472429e..0de15bf4 100644
--- a/python/pyspark/ml/connect/__init__.py
+++ b/python/pyspark/ml/connect/__init__.py
@@ -6,10 +6,9 @@ Re-exports the estimator/transformer/evaluator/pipeline 
classes so that both
 (`pyspark.ml.connect.feature`, `.classification`, `.evaluation`) work.
 """
 from pyspark.ml.connect.feature import (
+    ArrayAssembler,
     StandardScaler,
     MaxAbsScaler,
-    StringIndexer,
-    VectorAssembler,
 )
 from pyspark.ml.connect.classification import (
     GBTClassifier,
@@ -44,6 +43,13 @@ from pyspark._pyspark import MLModel
 from pyspark.ml.connect.base import Estimator, Transformer, Evaluator, Model
 from pyspark.ml.connect import feature, evaluation, tuning
 
+# feature.py is the byte-identical upstream module, so the native 
StringIndexer and VectorAssembler
+# of the drop-in are set on it here, where `from pyspark.ml.connect.feature 
import ...` finds them.
+from pyspark._pyspark import StringIndexer, VectorAssembler
+
+feature.StringIndexer = StringIndexer
+feature.VectorAssembler = VectorAssembler
+
 __all__ = [
     # Reference `pyspark.ml.connect` public surface.
     "Estimator",
@@ -58,6 +64,7 @@ __all__ = [
     # Fork-additional concrete estimators/evaluators (Rust-backed).
     "StandardScaler",
     "MaxAbsScaler",
+    "ArrayAssembler",
     "StringIndexer",
     "VectorAssembler",
     "LogisticRegression",
diff --git a/python/pyspark/ml/connect/feature.py 
b/python/pyspark/ml/connect/feature.py
index ac6e8899..2184b3c7 100644
--- a/python/pyspark/ml/connect/feature.py
+++ b/python/pyspark/ml/connect/feature.py
@@ -1,9 +1,428 @@
-"""Feature transformers/estimators (pyspark.ml.connect.feature)."""
-from pyspark._pyspark import (
-    MaxAbsScaler,
-    StandardScaler,
-    StringIndexer,
-    VectorAssembler,
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+from typing import Any, Union, List, Tuple, Callable, Dict, Optional
+
+import numpy as np
+import pandas as pd
+import pyarrow as pa
+
+from pyspark import keyword_only
+from pyspark.sql import DataFrame
+from pyspark.ml.param.shared import (
+    HasInputCol,
+    HasInputCols,
+    HasOutputCol,
+    HasFeatureSizes,
+    HasHandleInvalid,
+    Param,
+    Params,
+    TypeConverters,
 )
+from pyspark.ml.connect.base import Estimator, Model, Transformer
+from pyspark.ml.connect.io_utils import ParamsReadWrite, CoreModelReadWrite
+
+
+class MaxAbsScaler(Estimator, HasInputCol, HasOutputCol, ParamsReadWrite):
+    """
+    Rescale each feature individually to range [-1, 1] by dividing through the 
largest maximum
+    absolute value in each feature. It does not shift/center the data, and 
thus does not destroy
+    any sparsity.
+
+    .. versionadded:: 3.5.0
+
+    .. deprecated:: 4.0.0
+
+    Examples
+    --------
+    >>> from pyspark.ml.connect.feature import MaxAbsScaler
+    >>> scaler = MaxAbsScaler(inputCol='features', outputCol='scaled_features')
+    >>> dataset = spark.createDataFrame([
+    ...     ([1.0, 2.0],),
+    ...     ([2.0, -1.0],),
+    ...     ([-3.0, -2.0],),
+    ... ], schema=['features'])
+    >>> scaler_model = scaler.fit(dataset)
+    >>> transformed_dataset = scaler_model.transform(dataset)
+    >>> transformed_dataset.show(truncate=False)
+    +------------+--------------------------+
+    |features    |scaled_features           |
+    +------------+--------------------------+
+    |[1.0, 2.0]  |[0.3333333333333333, 1.0] |
+    |[2.0, -1.0] |[0.6666666666666666, -0.5]|
+    |[-3.0, -2.0]|[-1.0, -1.0]              |
+    +------------+--------------------------+
+    """
+
+    _input_kwargs: Dict[str, Any]
+
+    @keyword_only
+    def __init__(self, *, inputCol: Optional[str] = None, outputCol: 
Optional[str] = None) -> None:
+        """
+        __init__(self, \\*, inputCol=None, outputCol=None)
+        """
+        super().__init__()
+        kwargs = self._input_kwargs
+        self._set(**kwargs)
+
+    def _fit(self, dataset: Union["pd.DataFrame", "DataFrame"]) -> 
"MaxAbsScalerModel":
+        from pyspark.ml.connect.summarizer import summarize_dataframe
+
+        input_col = self.getInputCol()
+
+        stat_res = summarize_dataframe(dataset, input_col, ["min", "max", 
"count"])
+        min_values = stat_res["min"]
+        max_values = stat_res["max"]
+        n_samples_seen = stat_res["count"]
+
+        max_abs_values = np.maximum(np.abs(min_values), np.abs(max_values))
+
+        model = MaxAbsScalerModel(max_abs_values, n_samples_seen)
+        model._resetUid(self.uid)
+        return self._copyValues(model)
+
+
+class MaxAbsScalerModel(Model, HasInputCol, HasOutputCol, ParamsReadWrite, 
CoreModelReadWrite):
+    """
+    Model fitted by MaxAbsScaler.
+
+    .. versionadded:: 3.5.0
+
+    .. deprecated:: 4.0.0
+    """
+
+    def __init__(
+        self, max_abs_values: Optional["np.ndarray"] = None, n_samples_seen: 
Optional[int] = None
+    ) -> None:
+        super().__init__()
+        self.max_abs_values = max_abs_values
+        if max_abs_values is not None:
+            # if scale value is zero, replace it with 1.0 (for preventing 
division by zero)
+            self.scale_values = np.where(max_abs_values == 0.0, 1.0, 
max_abs_values)
+        self.n_samples_seen = n_samples_seen
+
+    def _input_columns(self) -> List[str]:
+        return [self.getInputCol()]
+
+    def _output_columns(self) -> List[Tuple[str, str]]:
+        return [(self.getOutputCol(), "array<double>")]
+
+    def _get_transform_fn(self) -> Callable[..., Any]:
+        scale_values = self.scale_values
+
+        def transform_fn(series: Any) -> Any:
+            def map_value(x: "np.ndarray") -> "np.ndarray":
+                return x / scale_values
+
+            return series.apply(map_value)
+
+        return transform_fn
+
+    def _get_core_model_filename(self) -> str:
+        return self.__class__.__name__ + ".arrow.parquet"
+
+    def _save_core_model(self, path: str) -> None:
+        import pyarrow.parquet as pq
+
+        table = pa.Table.from_arrays(
+            [
+                pa.array([self.scale_values], pa.list_(pa.float64())),
+                pa.array([self.max_abs_values], pa.list_(pa.float64())),
+                pa.array([self.n_samples_seen], pa.int64()),
+            ],
+            names=["scale", "max_abs", "n_samples"],
+        )
+        pq.write_table(table, path)
+
+    def _load_core_model(self, path: str) -> None:
+        import pyarrow.parquet as pq
+
+        table = pq.read_table(path)
+
+        self.max_abs_values = np.array(table.column("scale")[0].as_py())
+        self.scale_values = np.array(table.column("max_abs")[0].as_py())
+        self.n_samples_seen = table.column("n_samples")[0].as_py()
+
+
+class StandardScaler(Estimator, HasInputCol, HasOutputCol, ParamsReadWrite):
+    """
+    Standardizes features by removing the mean and scaling to unit variance 
using column summary
+    statistics on the samples in the training set.
+
+    .. versionadded:: 3.5.0
+
+    .. deprecated:: 4.0.0
+
+    Examples
+    --------
+    >>> from pyspark.ml.connect.feature import StandardScaler
+    >>> scaler = StandardScaler(inputCol='features', 
outputCol='scaled_features')
+    >>> dataset = spark.createDataFrame([
+    ...     ([1.0, 2.0],),
+    ...     ([2.0, -1.0],),
+    ...     ([-3.0, -2.0],),
+    ... ], schema=['features'])
+    >>> scaler_model = scaler.fit(dataset)
+    >>> transformed_dataset = scaler_model.transform(dataset)
+    >>> transformed_dataset.show(truncate=False)
+    +------------+------------------------------------------+
+    |features    |scaled_features                           |
+    +------------+------------------------------------------+
+    |[1.0, 2.0]  |[0.3779644730092272, 1.1208970766356101]  |
+    |[2.0, -1.0] |[0.7559289460184544, -0.3202563076101743] |
+    |[-3.0, -2.0]|[-1.1338934190276817, -0.8006407690254358]|
+    +------------+------------------------------------------+
+    """
+
+    _input_kwargs: Dict[str, Any]
+
+    @keyword_only
+    def __init__(self, inputCol: Optional[str] = None, outputCol: 
Optional[str] = None) -> None:
+        """
+        __init__(self, \\*, inputCol=None, outputCol=None)
+        """
+        super().__init__()
+        kwargs = self._input_kwargs
+        self._set(**kwargs)
+
+    def _fit(self, dataset: Union[DataFrame, pd.DataFrame]) -> 
"StandardScalerModel":
+        from pyspark.ml.connect.summarizer import summarize_dataframe
+
+        input_col = self.getInputCol()
+
+        stat_result = summarize_dataframe(dataset, input_col, ["mean", "std", 
"count"])
+        mean_values = stat_result["mean"]
+        std_values = stat_result["std"]
+        n_samples_seen = stat_result["count"]
+
+        model = StandardScalerModel(mean_values, std_values, n_samples_seen)
+        model._resetUid(self.uid)
+        return self._copyValues(model)
+
+
+class StandardScalerModel(Model, HasInputCol, HasOutputCol, ParamsReadWrite, 
CoreModelReadWrite):
+    """
+    Model fitted by StandardScaler.
+
+    .. versionadded:: 3.5.0
+
+    .. deprecated:: 4.0.0
+    """
+
+    def __init__(
+        self,
+        mean_values: Optional["np.ndarray"] = None,
+        std_values: Optional["np.ndarray"] = None,
+        n_samples_seen: Optional[int] = None,
+    ) -> None:
+        super().__init__()
+        self.mean_values = mean_values
+        self.std_values = std_values
+        if std_values is not None:
+            # if scale value is zero, replace it with 1.0 (for preventing 
division by zero)
+            self.scale_values = np.where(std_values == 0.0, 1.0, std_values)
+        self.n_samples_seen = n_samples_seen
+
+    def _input_columns(self) -> List[str]:
+        return [self.getInputCol()]
+
+    def _output_columns(self) -> List[Tuple[str, str]]:
+        return [(self.getOutputCol(), "array<double>")]
+
+    def _get_transform_fn(self) -> Callable[..., Any]:
+        mean_values = self.mean_values
+        scale_values = self.scale_values
+
+        def transform_fn(series: Any) -> Any:
+            def map_value(x: "np.ndarray") -> "np.ndarray":
+                return (x - mean_values) / scale_values
+
+            return series.apply(map_value)
+
+        return transform_fn
+
+    def _get_core_model_filename(self) -> str:
+        return self.__class__.__name__ + ".arrow.parquet"
+
+    def _save_core_model(self, path: str) -> None:
+        import pyarrow.parquet as pq
+
+        table = pa.Table.from_arrays(
+            [
+                pa.array([self.scale_values], pa.list_(pa.float64())),
+                pa.array([self.mean_values], pa.list_(pa.float64())),
+                pa.array([self.std_values], pa.list_(pa.float64())),
+                pa.array([self.n_samples_seen], pa.int64()),
+            ],
+            names=["scale", "mean", "std", "n_samples"],
+        )
+        pq.write_table(table, path)
+
+    def _load_core_model(self, path: str) -> None:
+        import pyarrow.parquet as pq
+
+        table = pq.read_table(path)
+
+        self.scale_values = np.array(table.column("scale")[0].as_py())
+        self.mean_values = np.array(table.column("mean")[0].as_py())
+        self.std_values = np.array(table.column("std")[0].as_py())
+        self.n_samples_seen = table.column("n_samples")[0].as_py()
+
+
+class ArrayAssembler(
+    Transformer,
+    HasInputCols,
+    HasOutputCol,
+    HasFeatureSizes,
+    HasHandleInvalid,
+    ParamsReadWrite,
+):
+    """
+    A feature transformer that merges multiple input columns into an array 
type column.
+
+    Parameters
+    ----------
+    You need to set param `inputCols` for specifying input column names,
+    and set param `featureSizes` for specifying corresponding input column
+    feature size, for scalar type input column, corresponding feature size 
must be set to 1,
+    otherwise, set corresponding feature size to feature array length.
+    Output column is "array<double"> type and contains array of assembled 
features.
+    All elements in input feature columns must be convertible to double type.
+
+    You can set 'handler_invalid' param to specify how to handle invalid input 
value
+    (None or NaN), if it is set to 'error', error is thrown for invalid input 
value,
+    if it is set to 'keep', it returns relevant number of NaN in the output.
+
+    .. versionadded:: 4.0.0
+
+    .. deprecated:: 4.0.0
+
+    Examples
+    --------
+    >>> from pyspark.ml.connect.feature import ArrayAssembler
+    >>> import numpy as np
+    >>>
+    >>> spark_df = spark.createDataFrame(
+    ...     [
+    ...         ([2.0, 3.5, 1.5], 3.0, True, 1),
+    ...         ([-3.0, np.nan, -2.5], 4.0, False, 2),
+    ...     ],
+    ...     schema=["f1", "f2", "f3", "f4"],
+    ... )
+    >>> assembler = ArrayAssembler(
+    ...     inputCols=["f1", "f2", "f3", "f4"],
+    ...     outputCol="out",
+    ...     featureSizes=[3, 1, 1, 1],
+    ...     handleInvalid="keep",
+    ... )
+    >>> assembler.transform(spark_df).select("out").show(truncate=False)
+    """
+
+    _input_kwargs: Dict[str, Any]
+
+    # Override doc of handleInvalid param.
+    handleInvalid: Param[str] = Param(
+        Params._dummy(),
+        "handleInvalid",
+        "how to handle invalid entries. Options are 'error' (throw an error), "
+        "or 'keep' (return relevant number of NaN in the output). Default 
value "
+        "is 'error'",
+        typeConverter=TypeConverters.toString,
+    )
+
+    @keyword_only
+    def __init__(
+        self,
+        *,
+        inputCols: Optional[List[str]] = None,
+        outputCol: Optional[str] = None,
+        featureSizes: Optional[List[int]] = None,
+        handleInvalid: Optional[str] = "error",
+    ) -> None:
+        """
+        __init__(
+            self, \\*, inputCols=None, outputCol=None, featureSizes=None, 
handleInvalid="error"
+        )
+        """
+        super().__init__()
+        kwargs = self._input_kwargs
+        self._set(**kwargs)
+        self._setDefault(handleInvalid="error")
+
+    def _input_columns(self) -> List[str]:
+        return self.getInputCols()
+
+    def _output_columns(self) -> List[Tuple[str, str]]:
+        return [(self.getOutputCol(), "array<double>")]
+
+    def _get_transform_fn(self) -> Callable[..., Any]:
+        feature_size_list = self.getFeatureSizes()
+        if feature_size_list is None or len(feature_size_list) != 
len(self.getInputCols()):
+            raise ValueError(
+                "'feature_size_list' param must be set with an array of 
integer, and"
+                "its length must be equal to number of input columns."
+            )
+        for feature_size in feature_size_list:
+            if feature_size <= 0:
+                raise ValueError("All input feature sizes must be an positive 
integer.")
+
+        assembled_feature_size = sum(feature_size_list)
+        handler_invalid = self.getHandleInvalid()
+
+        if handler_invalid not in ["error", "keep"]:
+            raise ValueError("'handler_invalid' param must be set with 'error' 
or 'keep' value.")
+
+        keep_invalid = handler_invalid == "keep"
+
+        def assemble_features(*feature_list: Any) -> Any:
+            assembled_array = np.empty(assembled_feature_size, 
dtype=np.float64)
+            pos = 0
+            for index, feature in enumerate(feature_list):
+                feature_size = feature_size_list[index]
+
+                if feature is not None:
+                    if np.isscalar(feature) and feature_size != 1:
+                        raise ValueError(
+                            f"The {index + 1}th input feature is a scalar 
value, but provided "
+                            f"feature size is {feature_size}."
+                        )
+                    if not np.isscalar(feature) and len(feature) != 
feature_size:
+                        raise ValueError(
+                            f"The {index + 1}th input feature size does not 
match "
+                            f"with provided feature size {feature_size}."
+                        )
+                if keep_invalid:
+                    if feature is None:
+                        assembled_array[pos : pos + feature_size] = np.nan
+                    else:
+                        assembled_array[pos : pos + feature_size] = feature
+                else:
+                    if feature is None or np.isnan(feature).any():
+                        raise ValueError(
+                            f"The input features contains invalid value: 
{str(feature)}"
+                        )
+                    else:
+                        assembled_array[pos : pos + feature_size] = feature
+
+                pos += feature_size
+
+            return assembled_array
+
+        def transform_fn(*series_list: Any) -> Any:
+            return pd.Series(assemble_features(*feature_list) for feature_list 
in zip(*series_list))
 
-__all__ = ["StandardScaler", "MaxAbsScaler", "StringIndexer", 
"VectorAssembler"]
+        return transform_fn
diff --git a/python/tests/_mock_connect_server.py 
b/python/tests/_mock_connect_server.py
index 34e18b87..b08e8c4e 100644
--- a/python/tests/_mock_connect_server.py
+++ b/python/tests/_mock_connect_server.py
@@ -311,6 +311,7 @@ def serve(connection):
             self.release_execute_requests = []
             self.execute_payload = b""
             self.execute_payloads = None
+            self.query_payload = None
             self.execute_failure = None
             self.execute_error = None
             self.stream_failure = None
@@ -454,6 +455,10 @@ def serve(connection):
         # With `execute_payloads` set (a list of raw ExecutePlanResponse 
fields), the execution
         # streams one response of each, r1, r2, ..., instead of 
`execute_payload`.
         execute_payloads = None
+        # With `query_payload` set (raw ExecutePlanResponse fields), the 
execution of a DataFrame's
+        # query, a plan with no command, such as the label query of a 
LogisticRegression fit,
+        # streams it instead of the payloads of a command.
+        query_payload = None
         execute_failure = None
         # With `stream_failure` set to a status code name, or a (name, delay 
in ms) of a failure
         # with that RetryInfo delay, ExecutePlan streams its responses and 
then fails with it,
@@ -719,6 +724,10 @@ def serve(connection):
             payloads = (
                 [self.execute_payload] if self.execute_payloads is None else 
self.execute_payloads
             )
+            # ExecutePlanRequest.plan=3, of which Plan.command=2 is set for a 
command only.
+            plan = parse_message(parse_message(request).get(3, [b""])[0])
+            if self.query_payload is not None and 2 not in plan:
+                payloads = [self.query_payload]
             for index, payload in enumerate(payloads, 1):
                 yield header + message_field(13, f"r{index}") + payload
             if self.stream_failure:
diff --git a/python/tests/test_ml_e2e.py b/python/tests/test_ml_e2e.py
index 581af7c6..2f2156cd 100644
--- a/python/tests/test_ml_e2e.py
+++ b/python/tests/test_ml_e2e.py
@@ -75,26 +75,27 @@ 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 
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).
+    # pyspark.ml.connect's StandardScaler and MaxAbsScaler, which are 
PySpark's own classes: they
+    # fit with summarize_dataframe and transform with closures on the server, 
and output an
+    # array<double>, of the values of PySpark 4.3.0. The native StringIndexer 
is fitted and cached
+    # by the server, and its transform gives its indexes.
     from pyspark.ml.connect.feature import MaxAbsScaler, StandardScaler, 
StringIndexer
-    from pyspark.ml.connect.functions import array_to_vector
 
     rows = [(1, [2.0, 4.0], "a"), (2, [4.0, 2.0], "b"), (3, [6.0, 6.0], "a")]
     df = session.createDataFrame(rows, "x int, f array<double>, s string")
-    df = df.withColumn("v", array_to_vector("f"))
 
     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)
+    scaled = StandardScaler(inputCol="f", outputCol="o").fit(df).transform(df)
     assert scaled.schema["o"].dataType.simpleString() == "array<double>"
-    assert rows(scaled, "o") == [[-1.0, 0.0], [0.0, -1.0], [1.0, 1.0]]
+    # The values of PySpark 4.3.0, of its float64 arithmetic: (x - mean) / 
std, which rounds.
+    expected = [[-0.9999999999999998, 0.0], [0.0, -0.9999999999999998], [1.0, 
1.0]]
+    for got, want in zip(rows(scaled, "o"), expected):
+        assert got == pytest.approx(want, rel=1e-12, abs=1e-12)
 
-    maxabs = MaxAbsScaler(inputCol="v", outputCol="o").fit(df).transform(df)
+    maxabs = MaxAbsScaler(inputCol="f", outputCol="o").fit(df).transform(df)
     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]
@@ -258,12 +259,10 @@ def _native_estimators():
         LinearRegression,
         LinearSVC,
         LogisticRegression,
-        MaxAbsScaler,
         MultilayerPerceptronClassifier,
         NaiveBayes,
         RandomForestClassifier,
         RandomForestRegressor,
-        StandardScaler,
         StringIndexer,
     )
 
@@ -285,8 +284,6 @@ def _native_estimators():
         (LogisticRegression(maxIter=2), ml + 
"classification.LogisticRegressionModel"),
         (RandomForestClassifier(numTrees=2), ml + 
"classification.RandomForestClassificationModel"),
         (RandomForestRegressor(numTrees=2), ml + 
"regression.RandomForestRegressionModel"),
-        (StandardScaler(inputCol="features", outputCol="o"), ml + 
"feature.StandardScalerModel"),
-        (MaxAbsScaler(inputCol="features", outputCol="o"), ml + 
"feature.MaxAbsScalerModel"),
         (StringIndexer(inputCol="s", outputCol="o"), ml + 
"feature.StringIndexerModel"),
     ]
 
@@ -493,10 +490,10 @@ def 
test_ml_connect_evaluators_take_the_columns_and_the_pandas_frames_of_pyspark
 
 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.
+    # pyspark.ml.connect classes compute on arrays: the scalers are PySpark's 
own, and output an
+    # array<double>, with the values of PySpark 4.3.0 (StandardScaler scales 
to (x - mean) / std).
+    # An array of numbers is sent to the JVM estimator that LogisticRegression 
is, as the vector
+    # that it reads, and the transform keeps the array as it is.
     from pyspark.ml.connect.classification import LogisticRegression
     from pyspark.ml.connect.clustering import KMeans
     from pyspark.ml.connect.feature import MaxAbsScaler, StandardScaler
@@ -521,11 +518,14 @@ def 
test_ml_connect_scalers_and_estimators_take_the_array_columns_of_pyspark(ses
         assert transformed.schema.simpleString() == (
             f"struct<features:array<{element}>,scaled_features:array<double>>"
         )
-        assert [row.scaled_features for row in transformed.collect()] == [
+        # The values of PySpark 4.3.0, which the decimals of the fit give with 
their rounding.
+        expected = [
             [0.3333333333333333, 1.0],
             [0.6666666666666666, -0.5],
             [-1.0, -1.0],
-        ], element
+        ]
+        for row, want in zip(transformed.collect(), expected):
+            assert row.scaled_features == pytest.approx(want, rel=1e-12), 
element
 
     scaler = StandardScaler(inputCol="features", outputCol="scaled_features")
     transformed = scaler.fit(dataset).transform(dataset)
@@ -577,6 +577,40 @@ def 
test_ml_connect_scalers_and_estimators_take_the_array_columns_of_pyspark(ses
     assert len({row.prediction for row in clusters.collect()}) == 2
 
 
+def test_ml_connect_logistic_regression_checks_its_labels_as_pyspark(session):
+    # As PySpark's LogisticRegression._fit, of the distinct labels of its 
query, which skips a
+    # null label: at least two, each an integer in [0, numClasses). The 
ValueErrors are those of
+    # PySpark 4.3.0, raised before the fit, which the JVM estimator would 
otherwise fit or reject.
+    from pyspark.ml.connect.classification import LogisticRegression
+
+    features = [[1.0, 2.0], [2.0, -1.0], [-3.0, -2.0], [-1.0, -2.0]]
+
+    def labeled(labels, label_type="double"):
+        rows = [(f, label) for f, label in zip(features, labels)]
+        return session.createDataFrame(rows, f"features array<double>, label 
{label_type}")
+
+    too_few = "Training dataset distinct labels must >= 2."
+    not_index = "Training labels must be integers in [0, numClasses)."
+    for labels, message in [
+        ([1.0, 1.0, 1.0, 1.0], too_few),
+        ([0.0, 0.0, 0.0, 0.0], too_few),
+        ([0.0, 0.0, 2.0, 2.0], not_index),
+        ([1.0, 1.0, 2.0, 2.0], not_index),
+        ([-1.0, -1.0, 1.0, 1.0], not_index),
+        ([0.5, 0.5, 1.0, 1.0], not_index),
+    ]:
+        with pytest.raises(ValueError) as error:
+            LogisticRegression(maxIter=5).fit(labeled(labels))
+        assert str(error.value) == message, labels
+    with pytest.raises(ValueError) as error:
+        LogisticRegression(maxIter=5).fit(labeled(["a", "a", "b", "b"], 
"string"))
+    assert str(error.value) == not_index
+    # The labels of a DataFrame of no rows have no distinct labels.
+    with pytest.raises(ValueError) as error:
+        LogisticRegression(maxIter=5).fit(labeled([], "double"))
+    assert str(error.value) == too_few
+
+
 def 
test_ml_connect_logistic_regression_and_scalers_output_the_columns_of_pyspark(session):
     # The schemas of the transforms of PySpark 4.3.0's LogisticRegression and 
scalers of
     # pyspark.ml.connect, of their pandas_udf: the columns of their 
_output_columns, nullable and
@@ -641,8 +675,8 @@ def 
test_ml_connect_estimators_fit_and_transform_the_pandas_frames_of_pyspark(se
     # As PySpark's pyspark.ml.connect classes, whose fit and transform take a 
pandas DataFrame:
     # here it is sent with createDataFrame of the active session, and the 
transform is a shallow
     # copy of it with the output columns appended, of its index, of the dtypes 
and the cells of
-    # PySpark's (an int64 prediction, ndarrays of probabilities and of scaled 
values), of the
-    # values of the JVM. PySpark's LogisticRegression fits no pandas 
DataFrame. The native classes
+    # PySpark's (an int64 prediction, ndarrays of probabilities and of scaled 
values). PySpark's
+    # LogisticRegression fits no pandas DataFrame. The native classes
     # that PySpark's pyspark.ml.connect does not have are sent the whole 
pandas DataFrame, and
     # append the columns that their JVM models append, which check them.
     import numpy as np
@@ -726,9 +760,9 @@ def 
test_ml_connect_scaler_fit_with_its_input_as_output_as_pyspark(session):
 def 
test_ml_connect_scalers_transform_the_nan_of_pandas_frames_as_pyspark(session):
     # As PySpark computes the transform of a pandas DataFrame locally, a NaN 
element of its arrays
     # stays NaN, and the scaled values of the other elements are PySpark's. 
The values are those of
-    # PySpark 4.3.0. The fit of a StandardScaler on a pandas DataFrame with a 
NaN propagates it, as
-    # PySpark's numpy does. The fit of a MaxAbsScaler skips the NaN, as the 
JVM's summarizer does,
-    # which PySpark's numpy does not, so that fit is not checked here.
+    # PySpark 4.3.0. The fits of the scalers on a pandas DataFrame are local, 
as PySpark's are, so
+    # a NaN propagates into their scales (the maximum of MaxAbsScaler too). 
The fit of a Spark
+    # DataFrame is the server's summary, which skips a NaN element of the 
maximum.
     import numpy as np
     import pandas as pd
     from pyspark.ml.connect.feature import MaxAbsScaler, StandardScaler
@@ -760,6 +794,10 @@ def 
test_ml_connect_scalers_transform_the_nan_of_pandas_frames_as_pyspark(sessio
         StandardScaler(inputCol="x", 
outputCol="o").fit(pdf).transform(pdf.copy()),
         [[nan, -0.9491579957524987], [nan, -0.0949157995752498], [nan, 
1.0440737953277488]],
     )
+    check(
+        MaxAbsScaler(inputCol="x", 
outputCol="o").fit(pdf).transform(pdf.copy()),
+        [[nan, 0.125], [nan, 0.5], [nan, 1.0]],
+    )
 
 
 def test_ml_connect_empty_pandas_transforms_as_pyspark(session):
diff --git a/python/tests/test_ml_offline.py b/python/tests/test_ml_offline.py
index 05e9437b..08bbf62e 100644
--- a/python/tests/test_ml_offline.py
+++ b/python/tests/test_ml_offline.py
@@ -100,6 +100,17 @@ def _operator_info(ref_id):
     )
 
 
+def _labels_result(classes=(0, 1), double=False):
+    # The response of the label query of a LogisticRegression fit: the array 
of the distinct labels
+    # of its collect_set, which the fit checks before it fits: of doubles, or 
else of longs.
+    import pyarrow as pa
+
+    element = T.DoubleType() if double else T.LongType()
+    arrow = pa.float64() if double else pa.int64()
+    table = pa.table({"labels": pa.array([list(classes)], pa.list_(arrow))})
+    return _arrow_result(table, T.StructType([T.StructField("labels", 
T.ArrayType(element))]))
+
+
 def _arrow_result(table, schema):
     # The ExecutePlanResponse of the rows of the Arrow table, of the Spark 
schema `schema`, which
     # the mock server sends of an execution.
@@ -130,8 +141,13 @@ def _requests_but_deletes(service):
 def _commands_but_deletes(service, start=0):
     # The commands of the requests that the server received from the start-th 
on, but the
     # Deletes of models that earlier tests released: a release is sent without 
waiting for it,
-    # so it can reach the server between a request of a test and the check of 
that request.
-    return [c for c in _commands(service)[start:] if not 
c.ml_command.HasField("delete")]
+    # so it can reach the server between a request of a test and the check of 
that request. A
+    # request of a DataFrame's plan, such as the label query of a fit, has no 
command.
+    return [
+        c
+        for c in _commands(service)[start:]
+        if c.WhichOneof("command_type") and not c.ml_command.HasField("delete")
+    ]
 
 
 def _last_request_but_deletes(service):
@@ -191,96 +207,77 @@ def test_ml_cache_queries_are_those_of_pyspark(ml_mock):
     assert command.ml_command.get_model_size.model_ref == 
pb2.ObjectRef(id="ref-1")
 
 
-def test_ml_connect_fitted_scalers_transform_the_cached_model(ml_mock):
+def test_ml_connect_fitted_string_indexer_transforms_the_cached_model(ml_mock):
     # As the fitted models of PySpark Connect: fit sends an MlCommand.Fit of 
the estimator, and the
     # transform of the fitted model refers to the object that the server 
cached for the fit, not to
-    # a transformer of the estimator's name, which the server rejects.
-    from pyspark.ml.connect.feature import MaxAbsScaler, StandardScaler, 
StringIndexer
+    # a transformer of the estimator's name, which the server rejects. (The 
scalers of
+    # pyspark.ml.connect are PySpark's own classes, which fit and transform in 
Python, see
+    # test_ml_connect_scalers_are_pyspark_own_classes.)
+    from pyspark.ml.connect.feature import StringIndexer
 
     spark, service = ml_mock
-    df = spark.range(1).selectExpr("array(1.0D, 2.0D) AS f", "'a' AS s")
-    models = []  # Kept alive, so that no model is released during the checks.
-    for cls, name, column in [
-        (StandardScaler, "org.apache.spark.ml.feature.StandardScaler", "f"),
-        (MaxAbsScaler, "org.apache.spark.ml.feature.MaxAbsScaler", "f"),
-        (StringIndexer, "org.apache.spark.ml.feature.StringIndexer", "s"),
-    ]:
-        sent = len(service.execute_requests)
-        service.execute_payload = _operator_info("model-1")
-        estimator = cls(inputCol=column, outputCol="o")
-        models.append(estimator.fit(df))
-        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. A scaler's
-        # fit sends no outputCol (see _unsent_by_fit), and its transform sends 
it below.
-        outputs = (
-            {}
-            if _unsent_by_fit(cls.__name__)
-            else {"outputCol": pb2.Expression.Literal(string="o")}
-        )
-        assert dict(fit.params.params) == {
-            "inputCol": pb2.Expression.Literal(string=column),
-            **outputs,
-            **({"withMean": pb2.Expression.Literal(boolean=True)} if cls is 
StandardScaler else {}),
-        }
-        if cls is StringIndexer:
-            assert fit.dataset == _relation(df)
-        else:
-            # A scaler sends the select of its input column, the column that 
PySpark's fit reads.
-            assert fit.dataset.project.input == _relation(df)
-            assert [_text(e) for e in fit.dataset.project.expressions] == 
[_attribute(column)]
-
-        scaled = models[-1].transform(df)
-        assert len(service.execute_requests) == sent + 1
-        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_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")
+    df = spark.range(1).selectExpr("'a' AS s")
+    sent = len(service.execute_requests)
+    service.execute_payload = _operator_info("model-1")
+    model = StringIndexer(inputCol="s", outputCol="o").fit(df)
+    fit = _commands_but_deletes(service, sent)[0].ml_command.fit
+    assert fit.estimator.name == "org.apache.spark.ml.feature.StringIndexer"
+    assert fit.estimator.type == pb2.MlOperator.OPERATOR_TYPE_ESTIMATOR
+    assert dict(fit.params.params) == {
+        "inputCol": pb2.Expression.Literal(string="s"),
+        "outputCol": pb2.Expression.Literal(string="o"),
+    }
+    assert fit.dataset == _relation(df)
 
+    scaled = model.transform(df)
+    assert len(service.execute_requests) == sent + 1
+    transform = _relation(scaled).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 
test_ml_connect_scaler_fit_with_its_input_as_output_takes_no_output_col_as_pyspark(ml_mock):
-    # As PySpark's scaler fit, which reads only its inputCol, the fit of a 
scaler whose outputCol is
-    # its inputCol succeeds. The JVM fit checks that the output column does 
not exist, so the fit
-    # sends no outputCol, and the model keeps it: its transform raises 
PySpark's ValueError of an
-    # output column that the DataFrame has, before any request, and sends the 
outputCol otherwise.
-    from _mock_connect_server import ddl_data_type
-    from pyspark.ml.connect.feature import MaxAbsScaler, StandardScaler
 
-    spark, service = ml_mock
-    x = spark.range(1).selectExpr("array(1.0D, 2.0D) AS x")
-    models = []  # Kept alive, so that no model is released during the checks.
-    message = (
-        "Transformers does not allow output column having the same name with 
existing columns."
+def test_ml_connect_scalers_are_pyspark_own_classes(ml_mock):
+    # The scalers of pyspark.ml.connect are the classes of PySpark's 
feature.py, which
+    # StandardScaler and MaxAbsScaler fit with summarize_dataframe and 
transform with closures on
+    # the server, so they send no MlCommand and have no setters, as PySpark's 
have none. The native
+    # StringIndexer and VectorAssembler are exported by the same module, 
beside them.
+    import numpy as np
+    import pandas as pd
+    import pyspark.ml.connect as connect
+    from pyspark.ml.connect import feature
+    from pyspark.ml.connect.feature import (
+        ArrayAssembler,
+        MaxAbsScaler,
+        StandardScaler,
+        StringIndexer,
+        VectorAssembler,
     )
-    for cls in (StandardScaler, MaxAbsScaler):
-        service.data_type = ddl_data_type("x array<double>")
-        sent = len(service.execute_requests)
-        service.execute_payload = _operator_info("model-1")
-        models.append(cls(inputCol="x", outputCol="x").fit(x))
-        fit = _commands_but_deletes(service, sent)[0].ml_command.fit
-        assert "outputCol" not in fit.params.params, cls
-        assert fit.params.params["inputCol"] == 
pb2.Expression.Literal(string="x"), cls
 
-        sent = _requests_but_deletes(service)
-        with pytest.raises(ValueError) as error:
-            models[-1].transform(x)
-        assert str(error.value) == message, cls
-        assert _requests_but_deletes(service) == sent, cls
-        # Of a DataFrame without x, the transform appends x, as PySpark's does.
-        y = spark.range(1).selectExpr("array(3.0D) AS y")
-        service.data_type = ddl_data_type("y array<double>")
-        assert _model_sent(models[-1], y) == {
-            "inputCol": ("string", "x"),
-            **({"withMean": ("boolean", True)} if cls is StandardScaler else 
{}),
-            "outputCol": ("string", "x"),
-        }, cls
+    spark, service = ml_mock
+    for scaler in (StandardScaler, MaxAbsScaler):
+        assert scaler.__module__ == "pyspark.ml.connect.feature"
+        assert getattr(connect, scaler.__name__) is scaler
+        assert not hasattr(scaler, "set" + "InputCol")
+    assert connect.ArrayAssembler is ArrayAssembler is feature.ArrayAssembler
+    assert StringIndexer is feature.StringIndexer and VectorAssembler is 
feature.VectorAssembler
+    assert feature.StringIndexer.__module__ == "pyspark.ml.connect.feature"
+
+    # The model of a fit, built from its statistics, transforms a pandas 
DataFrame locally, as
+    # (x - mean) / scale, with the scale of a zero standard deviation replaced 
by 1, and without a
+    # request to the server.
+    sent = _requests_but_deletes(service)
+    model = feature.StandardScalerModel(
+        np.array([2.0, 1.0]), np.array([1.0, 0.0]), 3
+    )
+    model._resetUid("StandardScaler_test")
+    model._set(inputCol="f", outputCol="o")
+    pdf = pd.DataFrame({"f": [np.array([3.0, 5.0]), np.array([2.0, 1.0])]})
+    transformed = model.transform(pdf)
+    assert list(transformed.columns) == ["f", "o"]
+    assert [value.tolist() for value in transformed["o"]] == [[1.0, 4.0], 
[0.0, 0.0]]
+    assert _requests_but_deletes(service) == sent
 
 
 def _attribute(name):
@@ -327,23 +324,21 @@ def _aliases(with_columns):
 
 
 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 the array<double> of PySpark's, of vector_to_array of it. A vector, 
another type and the
-    # column of StringIndexer, which reads no vector, are sent as they are. 
The fit of
-    # LogisticRegression or of a scaler, whose fit in PySpark reads only its 
columns, is of the
-    # select of them.
+    # As PySpark's pyspark.ml.connect classes, which compute on arrays: the 
fit 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. A vector, another type and 
the column of
+    # StringIndexer, which reads no vector, are sent as they are. The fit of 
LogisticRegression,
+    # whose fit in PySpark reads only its columns, is of the select of them.
+    # (The scalers compute on arrays in Python, as PySpark's do: they send no 
request of their own.)
     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 selected(relation, df, columns):
         # Whether relation is the select of the columns of df, or df itself of 
no columns.
@@ -360,36 +355,29 @@ def 
test_ml_connect_native_estimators_take_the_array_columns_of_pyspark(ml_mock)
         analyzed = len(service.analyze_requests)
         sent = len(service.execute_requests)
         service.execute_payload = _operator_info("model-1")
+        service.query_payload = _labels_result()
         models.append(estimator.fit(df))
+        service.query_payload = None
         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)>"
+        "id bigint, Features array<int>, label double, s string, words 
array<string>"
     )
     # 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
-    ]
-    reads = {
-        "MaxAbsScaler": ["features"],
-        "StandardScaler": ["features"],
-        "LogisticRegression": ["features", "label"],
-    }
+    estimators = [getattr(connect, name)() for name in featured]
+    reads = {"LogisticRegression": ["features", "label"]}
     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. (The params that a class sends of itself: see 
_defaults_sent, and
-        # the outputCol that a scaler's fit does not send: see _unsent_by_fit.)
-        params = {"inputCol": "features"} if type(estimator) in scalers else {}
+        # array in its place. (The params that a class sends of itself: see 
_defaults_sent.)
         sent = {k: v.string for k, v in fit.params.params.items() if k not in 
_defaults_sent(name)}
-        assert sent == params, name
+        assert sent == {}, name
         assert _defaults_sent(name).keys() <= fit.params.params.keys(), name
         assert selected(fit.dataset.with_columns.input, df, reads.get(name)), 
name
         assert _aliases(fit.dataset.with_columns) == [
@@ -406,7 +394,7 @@ def 
test_ml_connect_native_estimators_take_the_array_columns_of_pyspark(ml_mock)
             (["Features"], _array_to_vector("Features")),
         ], name
         vectors = []
-        outputs = [(["o"], _vector_array("o"))] if type(estimator) in scalers 
else []
+        outputs = []
         if name == "LogisticRegression":
             # The probability vector of the JVM model, in a column of its own 
(see
             # 
test_ml_connect_logistic_regression_outputs_the_columns_of_pyspark).
@@ -418,15 +406,6 @@ def 
test_ml_connect_native_estimators_take_the_array_columns_of_pyspark(ml_mock)
         assert transformed.drop.column_names == [kept] + vectors, name
         assert _aliases(output) == [(["Features"], _attribute(kept))] + 
outputs, 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, columns, analyzed in [
         (connect.LogisticRegression(featuresCol="s"), ["s", "label"], 1),
         (connect.KMeans(featuresCol="words"), None, 1),
@@ -441,14 +420,45 @@ def 
test_ml_connect_native_estimators_take_the_array_columns_of_pyspark(ml_mock)
     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)
-        scaler = type(estimator) in scalers
-        assert selected(fit.dataset, df, ["features"] if scaler else None), 
estimator
-        if scaler:
-            assert _aliases(transformed.with_columns) == [(["o"], 
_vector_array("o"))]
-            transformed = transformed.with_columns.input
-        assert transformed.ml_relation.transform.input == _relation(df), 
estimator
+    df, fit, transformed = requests(connect.KMeans())
+    assert fit.dataset == _relation(df)
+    assert transformed.ml_relation.transform.input == _relation(df)
+
+
+def 
test_ml_connect_logistic_regression_checks_its_labels_before_its_fit_as_pyspark(ml_mock):
+    # As PySpark's LogisticRegression._fit, which checks the distinct labels 
of its query before it
+    # fits: at least two, each an integer in [0, numClasses), else its 
ValueError, with no fit sent.
+    # The e2e test checks the same cases against the server.
+    import pyspark.ml.connect as connect
+
+    spark, service = ml_mock
+    df = spark.range(1)
+    too_few = "Training dataset distinct labels must >= 2."
+    not_index = "Training labels must be integers in [0, numClasses)."
+    for classes, double, message in [
+        ((), False, too_few),
+        ((1,), False, too_few),
+        ((0, 2), False, not_index),
+        ((1, 2), False, not_index),
+        ((-1, 1), False, not_index),
+        ((0.5, 1.0), True, not_index),
+    ]:
+        sent = len(service.execute_requests)
+        service.query_payload = _labels_result(classes, double)
+        with pytest.raises(ValueError) as error:
+            connect.LogisticRegression().fit(df)
+        assert str(error.value) == message, classes
+        service.query_payload = None
+        # Only the label query is sent: no fit, whose command would be the 
only one of the ML.
+        assert len(service.execute_requests) == sent + 1, classes
+        assert _commands_but_deletes(service, sent) == [], classes
+
+    sent = len(service.execute_requests)
+    service.execute_payload = _operator_info("model-1")
+    service.query_payload = _labels_result((0, 1, 2))
+    connect.LogisticRegression().fit(df)
+    service.query_payload = None
+    assert len(_commands_but_deletes(service, sent)) == 1
 
 
 def 
test_ml_connect_logistic_regression_outputs_the_columns_of_pyspark(ml_mock):
@@ -477,6 +487,7 @@ def 
test_ml_connect_logistic_regression_outputs_the_columns_of_pyspark(ml_mock):
         assert not hasattr(LogisticRegression, "set" + param[0].upper() + 
param[1:])
 
     df = spark.range(1)
+    service.query_payload = _labels_result()
     models = []  # Kept alive, so that no model is released during the checks.
     for estimator, columns, outputs in [
         (LogisticRegression(), ["features", "label"], ["prediction", 
"probability"]),
@@ -518,11 +529,11 @@ def 
test_ml_connect_logistic_regression_outputs_the_columns_of_pyspark(ml_mock):
 
 
 def 
test_ml_connect_transforms_raise_the_value_error_of_pyspark_of_an_existing_output(ml_mock):
-    # As PySpark's Transformer._transform: the transform of a model of 
LogisticRegression or of a
-    # scaler raises its ValueError of an output column that the DataFrame has 
already, of its
-    # exact name, before any execution, as PySpark reads the dataset's columns 
first, and so does
-    # the transform of a pandas DataFrame. The other native models, which 
PySpark's
-    # pyspark.ml.connect does not have, leave their outputs to the checks of 
their JVM models.
+    # As PySpark's Transformer._transform: the transform of a model of 
LogisticRegression raises
+    # its ValueError of an output column that the DataFrame has already, of 
its exact name, before
+    # any execution, as PySpark reads the dataset's columns first, and so does 
the transform of a
+    # pandas DataFrame. The other native models, which PySpark's 
pyspark.ml.connect does not have,
+    # leave their outputs to the checks of their JVM models.
     import pandas as pd
     import pyspark.ml.connect as connect
     from _mock_connect_server import ddl_data_type
@@ -537,20 +548,18 @@ def 
test_ml_connect_transforms_raise_the_value_error_of_pyspark_of_an_existing_o
         # The model of estimator, and the uid of its fit.
         sent = len(service.execute_requests)
         service.execute_payload = _operator_info("model-1")
+        service.query_payload = _labels_result()
         models.append(estimator.fit(spark.range(1)))
+        service.query_payload = None
         return models[-1], _commands_but_deletes(service, 
sent)[0].ml_command.fit.estimator.uid
 
     lr, _ = fitted(connect.LogisticRegression())
     unprobable, _ = fitted(connect.LogisticRegression(probabilityCol=""))
-    scaler, _ = fitted(connect.MaxAbsScaler(inputCol="f", outputCol="o"))
-    unnamed, uid = fitted(connect.StandardScaler(inputCol="f"))
     kmeans, _ = fitted(connect.KMeans())
     for model, column in [
         (lr, "prediction"),
         (lr, "probability"),
         (unprobable, "prediction"),
-        (scaler, "o"),
-        (unnamed, f"{uid}__output"),
     ]:
         service.data_type = ddl_data_type(f"f array<double>, `{column}` 
double")
         sent = _requests_but_deletes(service)
@@ -565,7 +574,6 @@ def 
test_ml_connect_transforms_raise_the_value_error_of_pyspark_of_an_existing_o
     for model, column in [
         (lr, "Prediction"),
         (unprobable, "probability"),
-        (scaler, "O"),
         (kmeans, "prediction"),
     ]:
         service.data_type = ddl_data_type(f"f array<double>, `{column}` 
double")
@@ -579,8 +587,8 @@ def 
test_ml_connect_fit_and_transform_take_the_pandas_frames_of_pyspark(ml_mock)
     # whole of it of the other native classes. The transform is a shallow copy 
of the pandas
     # DataFrame, with the output columns of the server appended, of its index, 
as PySpark's
     # transform_dataframe_column makes it. PySpark's LogisticRegression fits 
no pandas DataFrame,
-    # a missing column raises the KeyError of pandas, as PySpark's, and an 
object that is not a
-    # DataFrame the AttributeError of PySpark's first access to it.
+    # and an object that is not a DataFrame raises the AttributeError of 
PySpark's first access
+    # to it. (The scalers compute on a pandas DataFrame locally, as PySpark's 
do: no request.)
     import pandas as pd
     import pyarrow as pa
     import pyspark.ml.connect as connect
@@ -604,10 +612,6 @@ def 
test_ml_connect_fit_and_transform_take_the_pandas_frames_of_pyspark(ml_mock)
         models.append(estimator.fit(pdf))
         return _commands_but_deletes(service, sent)[0].ml_command.fit
 
-    sent = fit(connect.MaxAbsScaler(inputCol="features", 
outputCol="o")).dataset.with_columns
-    assert _aliases(sent) == [(["features"], _array_to_vector("features"))]
-    assert list(sent.input.to_df.column_names) == ["features"]
-    scaler = models[-1]
     sent = fit(connect.KMeans()).dataset.with_columns
     assert list(sent.input.to_df.column_names) == ["features", "label"]
 
@@ -619,35 +623,12 @@ def 
test_ml_connect_fit_and_transform_take_the_pandas_frames_of_pyspark(ml_mock)
         with pytest.raises(PySparkNotImplementedError) as error:
             unimplemented.fit(pdf)
         assert error.value.getCondition() == "NOT_IMPLEMENTED"
-    with pytest.raises(KeyError):
-        connect.MaxAbsScaler(inputCol="f").fit(pdf)
-    with pytest.raises(KeyError) as error:
-        scaler.transform(pd.DataFrame({"x": [1]}))
-    assert error.value.args == ("features",)
     assert _requests_but_deletes(service) == sent
 
-    service.execute_payload = _arrow_result(
-        pa.table({"o": pa.array([[0.5, 1.0], [1.0, -0.5]], 
pa.list_(pa.float64()))}),
-        T.StructType([T.StructField("o", T.ArrayType(T.DoubleType()))]),
-    )
-    transformed = scaler.transform(pdf)
-    root = _last_request_but_deletes(service).plan.root
-    assert [_text(e) for e in root.project.expressions] == [_attribute("o")]
-    transform = 
root.project.input.drop.input.with_columns.input.ml_relation.transform
-    assert list(transform.input.with_columns.input.to_df.column_names) == 
["features"]
-    assert transformed is not pdf and list(pdf.columns) == ["features", 
"label"]
-    assert list(transformed.columns) == ["features", "label", "o"]
-    assert list(transformed.index) == [7, 9]
-    assert transformed.dtypes.astype(str).to_dict() == {
-        "features": "object", "label": "int64", "o": "object",
-    }
-    assert [type(value) for value in transformed["o"]] == [np.ndarray, 
np.ndarray]
-    assert [value.tolist() for value in transformed["o"]] == [[0.5, 1.0], 
[1.0, -0.5]]
-    # A shallow copy, of the data of pdf.
-    assert np.shares_memory(transformed["label"].to_numpy(), 
pdf["label"].to_numpy())
-
     service.execute_payload = _operator_info("model-2")
+    service.query_payload = _labels_result()
     models.append(connect.LogisticRegression().fit(spark.range(1)))
+    service.query_payload = None
     service.execute_payload = _arrow_result(
         pa.table({
             "prediction": pa.array([1, 0], pa.int64()),
@@ -664,11 +645,19 @@ def 
test_ml_connect_fit_and_transform_take_the_pandas_frames_of_pyspark(ml_mock)
         _attribute("prediction"), _attribute("probability"),
     ]
     assert list(transformed.columns) == ["features", "label", "prediction", 
"probability"]
+    assert list(transformed.index) == [7, 9]
     assert transformed.dtypes.astype(str).to_dict() == {
         "features": "object", "label": "int64", "prediction": "int64", 
"probability": "object",
     }
     assert transformed["prediction"].tolist() == [1, 0]
     assert [value.tolist() for value in transformed["probability"]] == [[0.25, 
0.75], [0.5, 0.5]]
+    # A shallow copy, of the data of pdf.
+    assert np.shares_memory(transformed["label"].to_numpy(), 
pdf["label"].to_numpy())
+    sent = _requests_but_deletes(service)
+    with pytest.raises(KeyError) as error:
+        models[-1].transform(pd.DataFrame({"x": [1]}))
+    assert error.value.args == ("features",)
+    assert _requests_but_deletes(service) == sent
 
     class Columns:
         # An object of the attributes that PySpark reads, which is not a 
DataFrame.
@@ -678,18 +667,14 @@ def 
test_ml_connect_fit_and_transform_take_the_pandas_frames_of_pyspark(ml_mock)
     for other in ([1], None):
         name = type(other).__name__
         with pytest.raises(AttributeError) as error:
-            scaler.transform(other)
+            models[-1].transform(other)
         assert str(error.value) == f"'{name}' object has no attribute 
'columns'"
-        for estimator in (
-            connect.LogisticRegression(),
-            connect.MaxAbsScaler(inputCol="features"),
-            connect.KMeans(),
-        ):
+        for estimator in (connect.LogisticRegression(), connect.KMeans()):
             with pytest.raises(AttributeError) as error:
                 estimator.fit(other)
             assert str(error.value) == f"'{name}' object has no attribute 
'select'"
     with pytest.raises(TypeError) as error:
-        scaler.transform(Columns())
+        models[-1].transform(Columns())
     assert str(error.value) == "transform() takes a DataFrame or a pandas 
DataFrame, not 'Columns'"
     with pytest.raises(TypeError) as error:
         connect.KMeans().fit(Columns())
@@ -717,57 +702,38 @@ def 
test_ml_connect_pandas_frames_send_their_nan_as_pyspark(ml_mock):
     )
     models = []  # Kept alive, so that no model is released during the checks.
 
-    def sent_data(estimator):
-        # The Arrow table of the local data that the fit of estimator sends.
-        sent = len(service.execute_requests)
-        service.execute_payload = _operator_info("model-1")
-        models.append(estimator.fit(pdf))
-        fit = _commands_but_deletes(service, sent)[0].ml_command.fit
-        return pa.ipc.open_stream(_local_data(fit.dataset)).read_all()
-
-    # A scaler fits its inputCol, and the NaN of its elements survives.
-    table = sent_data(connect.MaxAbsScaler(inputCol="x", outputCol="o"))
-    assert table.column_names == ["x"]
-    first, second = table.column("x").to_pylist()
-    assert math.isnan(first[0]) and first[1] == 1.0 and second == [2.0, 4.0]
     # The other native classes send the whole of the pandas DataFrame, and a 
NaN value survives,
     # while the NaN of a string column is a null, as pandas makes it.
-    table = sent_data(connect.KMeans())
+    sent = len(service.execute_requests)
+    service.execute_payload = _operator_info("model-1")
+    models.append(connect.KMeans().fit(pdf))
+    fit = _commands_but_deletes(service, sent)[0].ml_command.fit
+    table = pa.ipc.open_stream(_local_data(fit.dataset)).read_all()
     assert table.column_names == ["x", "y", "s"]
     assert math.isnan(table.column("y").to_pylist()[1])
     assert table.column("y").to_pylist()[0] == 1.5
     assert table.column("s").to_pylist() == ["a", None]
+    first, second = table.column("x").to_pylist()
+    assert math.isnan(first[0]) and first[1] == 1.0 and second == [2.0, 4.0]
 
 
-def 
test_ml_connect_empty_pandas_transforms_compute_locally_as_pyspark(ml_mock):
-    # As PySpark's transform of an empty pandas DataFrame, which computes 
locally: a scaler appends
-    # its output column, of object dtype, to the index of the DataFrame, and a 
LogisticRegression
-    # model raises the ValueError of its transform function, which stacks no 
array. Neither sends
-    # a request, as the server cannot infer the schema of no rows.
+def 
test_ml_connect_logistic_regression_transforms_an_empty_pandas_frame_as_pyspark(ml_mock):
+    # As PySpark's transform of an empty pandas DataFrame, which computes 
locally: a
+    # LogisticRegression model raises the ValueError of its transform 
function, which stacks no
+    # array. It sends no request, as the server cannot infer the schema of no 
rows.
     import pandas as pd
     import pyspark.ml.connect as connect
 
     spark, service = ml_mock
     features = spark.range(1).selectExpr("array(1.0D, 2.0D) AS features")
     models = []  # Kept alive, so that no model is released during the checks.
-    service.execute_payload = _operator_info("model-1")
-    models.append(connect.MaxAbsScaler(inputCol="features", 
outputCol="o").fit(features))
-    sent = _requests_but_deletes(service)
-
-    empty = pd.DataFrame({"features": pd.Series([], dtype=object)})
-    transformed = models[-1].transform(empty)
-    assert transformed is not empty and list(empty.columns) == ["features"]
-    assert list(transformed.columns) == ["features", "o"]
-    assert transformed.dtypes.astype(str).to_dict() == {"features": "object", 
"o": "object"}
-    assert len(transformed) == 0 and transformed.index.equals(empty.index)
-    assert _requests_but_deletes(service) == sent
-    with pytest.raises(KeyError) as error:
-        models[-1].transform(pd.DataFrame({"x": pd.Series([], dtype=object)}))
-    assert error.value.args == ("features",)
-
     service.execute_payload = _operator_info("model-2")
+    service.query_payload = _labels_result()
     models.append(connect.LogisticRegression().fit(features))
+    service.query_payload = None
     sent = _requests_but_deletes(service)
+
+    empty = pd.DataFrame({"features": pd.Series([], dtype=object)})
     with pytest.raises(ValueError, match="need at least one array to stack"):
         models[-1].transform(empty)
     assert _requests_but_deletes(service) == sent
@@ -784,10 +750,8 @@ def 
test_ml_connect_setters_set_the_params_of_their_receiver_as_pyspark(ml_mock)
         LinearRegression,
         LinearSVC,
         LogisticRegression,
-        MaxAbsScaler,
         MulticlassClassificationEvaluator,
         RegressionEvaluator,
-        StandardScaler,
         StringIndexer,
         VectorAssembler,
     )
@@ -811,15 +775,15 @@ def 
test_ml_connect_setters_set_the_params_of_their_receiver_as_pyspark(ml_mock)
             params = _commands_but_deletes(service, 
sent)[0].ml_command.evaluate.params
         elif hasattr(obj, "fit"):
             service.execute_payload = _operator_info("model-1")
+            service.query_payload = _labels_result()
             models.append(obj.fit(df))
+            service.query_payload = None
             params = _commands_but_deletes(service, 
sent)[0].ml_command.fit.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")),
         (
@@ -874,10 +838,6 @@ def 
test_ml_connect_setters_set_the_params_of_their_receiver_as_pyspark(ml_mock)
             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()}
-        for name in _unsent_by_fit(cls.__name__):
-            # The fit sends no such param, and the transform of the model it 
fitted sends it.
-            assert _model_sent(models[-1], df)[name] == ("string", 
values[name]), (cls, name)
-            del sent_values[name]
         assert {name: params.get(name) for name in sent_values} == 
sent_values, cls
         assert params == sent_params(cls(**values)), cls
 
@@ -923,8 +883,6 @@ def 
test_ml_pipeline_and_cross_validator_fit_is_not_implemented(ml_mock):
 # param in PySpark. Their constructors take them all but thresholds, which 
PySpark's
 # RandomForestClassifier takes by its setter only.
 _NATIVE_PARAMS = {
-    "StandardScaler": dict(inputCol="str", outputCol="str"),
-    "MaxAbsScaler": dict(inputCol="str", outputCol="str"),
     "StringIndexer": dict(inputCol="str", outputCol="str"),
     "VectorAssembler": dict(inputCols="str_list", outputCol="str"),
     "LogisticRegression": dict(
@@ -1058,7 +1016,9 @@ def _native_request(spark, service, obj, models):
         return evaluate.evaluator, evaluate.params
     if hasattr(obj, "fit"):
         service.execute_payload = _operator_info("model-1")
+        service.query_payload = _labels_result()
         models.append(obj.fit(df))
+        service.query_payload = None
         fit = _commands_but_deletes(service, sent)[0].ml_command.fit
         return fit.estimator, fit.params
     transform = _relation(obj.transform(df)).ml_relation.transform
@@ -1083,34 +1043,17 @@ 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, the 
centering of
-    # StandardScaler, as PySpark's scales to (x - mean) / std, and the empty 
raw prediction column
-    # of LogisticRegression, as PySpark's outputs no raw prediction.
+    # BinaryClassificationEvaluator, which PySpark's constructor sets, and the 
empty raw prediction
+    # column of LogisticRegression, as PySpark's outputs no raw prediction.
     if name == "MulticlassClassificationEvaluator":
         return {"metricName": ("string", "accuracy")}
     if name == "BinaryClassificationEvaluator":
         return {"rawPredictionCol": ("string", "probability")}
-    if name == "StandardScaler":
-        return {"withMean": ("boolean", True)}
     if name == "LogisticRegression":
         return {"rawPredictionCol": ("string", "")}
     return {}
 
 
-def _unsent_by_fit(name):
-    # The params that the fit of a native class takes but does not send: the 
outputCol of a scaler,
-    # whose JVM fit checks that its output column does not exist yet, so that 
the fit reads no
-    # output column, and whose model keeps it, for the transform to send it.
-    return {"outputCol"} if name in ("StandardScaler", "MaxAbsScaler") else 
set()
-
-
-def _model_sent(model, df):
-    # The params that the transform of a fitted scaler sends: its output 
column is appended, so
-    # that its relation is the with_columns of the transform.
-    transform = 
_relation(model.transform(df)).with_columns.input.ml_relation.transform
-    return {name: _literal_value(literal) for name, literal in 
transform.params.params.items()}
-
-
 def _native_sent(spark, service, obj, models):
     _, params = _native_request(spark, service, obj, models)
     return {name: _literal_value(literal) for name, literal in 
params.params.items()}
@@ -1177,12 +1120,6 @@ def 
test_ml_connect_params_convert_with_the_type_converters_of_pyspark(ml_mock):
                     if name in _NOT_FITTABLE:
                         continue  # Their params are sent by no request.
                     sent = _native_sent(spark, service, obj, models)
-                    if param in _unsent_by_fit(name):
-                        # The fit sends none of it, and the transform of its 
model sends it.
-                        assert sent == _defaults_sent(name), (name, param, 
value)
-                        model_sent = _model_sent(models[-1], spark.range(1))
-                        assert model_sent[param] == expected, (name, param, 
value)
-                        continue
                     assert sent == {
                         **_defaults_sent(name), _sent_name(name, param): 
expected
                     }, (name, param, value)
@@ -1327,8 +1264,7 @@ def 
test_ml_connect_unsendable_ints_none_and_uids_as_pyspark(ml_mock):
             assert getattr(obj, setter)(value) is obj
             assert getattr(obj, setter)(None) is obj
             sent_name = _sent_name(name, param)
-            # The params that the fit sends: a scaler's fit sends no outputCol 
(see _unsent_by_fit).
-            sent_names = {sent_name} - _unsent_by_fit(name)
+            sent_names = {sent_name}
             sent = _native_sent(spark, service, obj, models)
             assert sent.keys() == sent_names | _defaults_sent(name).keys(), 
(name, param)
             if sent_names:
@@ -1363,6 +1299,7 @@ def 
test_ml_connect_setters_run_while_a_fit_or_an_evaluate_waits_as_pyspark(ml_m
         obj = getattr(connect, name)()
         service.reset()
         service.block_execute = True
+        service.query_payload = _labels_result()
         if hasattr(obj, "evaluate"):
             service.execute_payload = 
_ml_result(param=pb2.Expression.Literal(double=0.5))
             call = obj.evaluate
@@ -1384,10 +1321,14 @@ def 
test_ml_connect_setters_run_while_a_fit_or_an_evaluate_waits_as_pyspark(ml_m
             assert getattr(obj, setter)("changed") is obj
         finally:
             service.release_response()
+            if name == "LogisticRegression":
+                # Its fit waits for the release of its label query, as its own 
execution.
+                assert service.wait_execute_started(2), name
+                service.release_response()
             waiting.join(10)
         models.append(outcome)
         assert len(outcome) == 1 and not isinstance(outcome[0], Exception), 
(name, outcome)
-        (command,) = _commands(service)
+        (command,) = [c for c in _commands(service) if 
c.WhichOneof("command_type")]
         held = command.ml_command.evaluate if hasattr(obj, "evaluate") else 
command.ml_command.fit
         assert set(held.params.params) == set(_defaults_sent(name)), name
         assert _native_sent(spark, service, obj, models) == {
diff --git a/scripts/check_vendored_upstream.sh 
b/scripts/check_vendored_upstream.sh
index bd9c0479..f38449a9 100644
--- a/scripts/check_vendored_upstream.sh
+++ b/scripts/check_vendored_upstream.sh
@@ -183,6 +183,9 @@ VENDORED_FILES=(
   "sql/connect/proto/example_plugins_pb2.pyi"
   # ML connect base ABCs (Estimator/Transformer/Evaluator/Model) - pure 
upstream.
   "ml/connect/base.py"
+  # The scalers and ArrayAssembler of pyspark.ml.connect, which run their fit 
and transform in
+  # Python on the server (summarize_dataframe and the closures of the models) 
- pure upstream.
+  "ml/connect/feature.py"
   # vector_to_array/array_to_vector of pyspark.ml.functions build their 
columns here, through
   # pyspark.sql.connect.functions.builtin - pure upstream.
   "ml/connect/functions.py"


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

Reply via email to