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 8661cc19 [SPARK-61591][FOLLOWUP][CONNECT][PYTHON] Fit a scaler whose 
outputCol is its inputCol, keep the NaN of a pandas input, and transform an 
empty pandas DataFrame, in the Python client as PySpark does
8661cc19 is described below

commit 8661cc19c7eb3fce94dadd3928bf777ef23a91b1
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Fri Nov 13 11:40:24 2026 +0900

    [SPARK-61591][FOLLOWUP][CONNECT][PYTHON] Fit a scaler whose outputCol is 
its inputCol, keep the NaN of a pandas input, and transform an empty pandas 
DataFrame, in the Python client as PySpark does
    
    ### What changes were proposed in this pull request?
    
    Three follow-ups to #583, so that the native `pyspark.ml.connect` scalers 
and LogisticRegression behave as PySpark's do:
    
    - **A scaler whose `outputCol` is its `inputCol` fits.** Spark's fit checks 
that the output column is absent, so the fit now sends no `outputCol`, and the 
model keeps it. Its transform then raises PySpark's `ValueError` for an 
existing output column, at the transform as PySpark does. Before, the fit 
raised `IllegalArgumentException: Output column x already exists`.
    - **A NaN in a pandas input stays NaN.** A pandas DataFrame is now sent as 
an Arrow table built without pandas' NaN-to-null conversion. Before, a NaN 
element of an array became a null, and the scaler failed with 
`NOT_NULL_ASSERT_VIOLATION`.
    - **An empty pandas DataFrame transforms.** It is now computed without the 
server, which cannot infer its schema. A scaler appends an empty `object` 
column, as PySpark does. LogisticRegression raises PySpark's own `ValueError: 
need at least one array to stack`. Before, both raised 
`CANNOT_INFER_EMPTY_SCHEMA`.
    
    ### Why are the changes needed?
    
    A review of #583 against the official `pyspark-client` 4.3.0 found these 
three differences.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes, the three behaviors above now match PySpark 4.3.0. One difference 
remains, and `docs/compatibility.md` documents it: a pandas fit of 
`MaxAbsScaler` uses Spark's statistics, whose maximum skips a NaN element, 
where PySpark's local fit makes the scale of that feature NaN.
    
    ### How was this patch tested?
    
    - New offline tests in `test_ml_offline.py` and live tests in 
`test_ml_e2e.py`, for all three cases.
    - `test_ml_offline.py`: 133 passed.
    - `test_ml_e2e.py` and `test_gaussian_mixture_e2e.py` against a Spark 4.3.0 
Connect server: 42 passed.
    - `test_dropin_offline.py`: 1957 passed, 8 skipped.
    - `cargo fmt --all --check` passes, and the drop-in builds without warnings.
    - The three scenarios give the same results and errors as the official 
`pyspark-client` 4.3.0, for both scalers.
    
    ### 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 #599 from HyukjinKwon/SPARK-61591-followup.
    
    Authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 crates/pyspark-rs/src/ml.rs     |  98 ++++++++++++++++++++--
 docs/compatibility.md           |  35 +++++---
 python/tests/test_ml_e2e.py     |  81 ++++++++++++++++++
 python/tests/test_ml_offline.py | 181 ++++++++++++++++++++++++++++++++++++++--
 4 files changed, 368 insertions(+), 27 deletions(-)

diff --git a/crates/pyspark-rs/src/ml.rs b/crates/pyspark-rs/src/ml.rs
index e66b50e6..25135041 100644
--- a/crates/pyspark-rs/src/ml.rs
+++ b/crates/pyspark-rs/src/ml.rs
@@ -306,14 +306,35 @@ fn dataset_of<'py>(
     )))
 }
 
-/// The DataFrame of the pandas DataFrame `pdf`, of `createDataFrame` of the 
active session.
+/// The DataFrame of the pandas DataFrame `pdf`, of `createDataFrame` of the 
active session. Its
+/// columns are sent as Arrow arrays, built without pandas' conversion of NaN 
to null (which the
+/// non-nullable element type of an array rejects), so that a NaN element or 
value stays NaN, as
+/// PySpark computes on it locally. A column that Arrow takes only with that 
conversion, such as the
+/// strings with a NaN, is taken as pandas takes it.
 fn active_dataframe(pdf: &Bound<'_, PyAny>) -> PyResult<DataFrame> {
-    let df = pdf
-        .py()
+    let py = pdf.py();
+    let pa = py.import("pyarrow")?;
+    let kwargs = PyDict::new(py);
+    kwargs.set_item("from_pandas", false)?;
+    let arrays = PyList::empty(py);
+    let names = PyList::empty(py);
+    for item in pdf.call_method0("items")?.try_iter()? {
+        let (name, column): (Bound<'_, PyAny>, Bound<'_, PyAny>) = 
item?.extract()?;
+        let array = match pa.call_method("array", (&column,), Some(&kwargs)) {
+            Ok(array) => array,
+            Err(_) => pa.call_method1("array", (column,))?,
+        };
+        arrays.append(array)?;
+        names.append(name)?;
+    }
+    let table = pa
+        .getattr("Table")?
+        .call_method1("from_arrays", (arrays, names))?;
+    let df = py
         .import("pyspark.sql")?
         .getattr("SparkSession")?
         .call_method0("active")?
-        .call_method1("createDataFrame", (pdf,))?;
+        .call_method1("createDataFrame", (table,))?;
     Ok(df.extract::<PyRef<'_, PyDataFrame>>()?.dataframe.clone())
 }
 
@@ -367,7 +388,7 @@ where
 {
     let py = slf.py();
     let dataset = dataset_of(dataset, "fit", "select")?;
-    let estimator = snapshot(slf)?;
+    let mut estimator = snapshot(slf)?;
     let columns = reads.and_then(|reads| read_columns(estimator.params(), 
reads));
     let (df, select) = match dataset {
         Dataset::Spark(df) => (df, columns),
@@ -391,7 +412,41 @@ where
         Some(field) => df.with_column(&field.name, vector_of(&field)),
         None => df,
     };
-    fit_core(py, estimator, &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)
+}
+
+/// 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 fit of a native estimator whose core cannot fit it, as Pipeline and 
CrossValidator.
@@ -747,6 +802,32 @@ impl PySparkModel {
         }
     }
 
+    /// 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
+    /// `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();
+        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())
+            }
+        }
+    }
+
     /// PySpark's ValueError of `Transformer._transform` of an output column 
that `dataset` has
     /// already: one of `list(dataset.columns)`, of their exact names, before 
any transform.
     fn check_outputs(&self, dataset: &Bound<'_, PyAny>) -> PyResult<()> {
@@ -787,6 +868,11 @@ fn transform_pandas<'py>(
         Some(input) => copy.get_item(input)?.call_method0("to_frame")?,
         None => copy.clone(),
     };
+    // The server cannot infer the schema of an empty pandas DataFrame, so 
PySpark's own result of
+    // no rows is computed here, as PySpark computes it.
+    if let (Some(model), 0) = (pyspark, pdf.len()?) {
+        return model.transform_empty(&copy);
+    }
     let df = active_dataframe(&sent)?;
     let out = transform(&df)?;
     let outputs = match pyspark {
diff --git a/docs/compatibility.md b/docs/compatibility.md
index 50669bae..757a2ee1 100644
--- a/docs/compatibility.md
+++ b/docs/compatibility.md
@@ -244,20 +244,29 @@ not given is not sent, so the server's default applies. A 
list param without ele
 accepted by its constructor and setters, and a fit, transform or evaluate 
raises PySpark's
 `CANNOT_INFER_ARRAY_ELEMENT_TYPE` for it, as PySpark's serialization does.
 
-Their fit, transform and evaluate take a DataFrame or a pandas DataFrame, as 
PySpark's do, and
-run on the server, where PySpark's compute on a pandas DataFrame locally: a 
pandas DataFrame is
-sent through `createDataFrame` of the active session, and 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). Another object raises the `AttributeError` that PySpark's 
raises, of its
+Their fit, transform and evaluate take a DataFrame or a pandas DataFrame, as 
PySpark's do, and run
+on the server, where PySpark's compute on a pandas DataFrame locally: a pandas 
DataFrame is sent
+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. 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 other 
native models, of the
+`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
diff --git a/python/tests/test_ml_e2e.py b/python/tests/test_ml_e2e.py
index 33d06c33..2ab31e36 100644
--- a/python/tests/test_ml_e2e.py
+++ b/python/tests/test_ml_e2e.py
@@ -698,6 +698,87 @@ def 
test_ml_connect_estimators_fit_and_transform_the_pandas_frames_of_pyspark(se
         KMeans(k=2, seed=1).fit(pdf).transform(pdf.assign(prediction=0))
 
 
+def test_ml_connect_scaler_fit_with_its_input_as_output_as_pyspark(session):
+    # As PySpark's scaler fit, which reads only its inputCol: a scaler whose 
outputCol is its
+    # inputCol fits, and its model keeps the outputCol, so that its transform 
raises PySpark's
+    # ValueError of an output column that the DataFrame has, of the DataFrame 
and of a pandas one.
+    import pandas as pd
+    from pyspark.ml.connect.feature import MaxAbsScaler, StandardScaler
+
+    df = session.createDataFrame([([1.0, 2.0],), ([3.0, 4.0],), ([5.0, 
9.0],)], ["x"])
+    message = (
+        "Transformers does not allow output column having the same name with 
existing columns."
+    )
+    for cls in (StandardScaler, MaxAbsScaler):
+        model = cls(inputCol="x", outputCol="x").fit(df)
+        with pytest.raises(ValueError) as error:
+            model.transform(df)
+        assert str(error.value) == message, cls
+        with pytest.raises(ValueError) as error:
+            model.transform(pd.DataFrame({"x": [[1.0, 2.0]]}))
+        assert str(error.value) == message, cls
+
+
+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.
+    import numpy as np
+    import pandas as pd
+    from pyspark.ml.connect.feature import MaxAbsScaler, StandardScaler
+
+    nan = float("nan")
+    fitted = session.createDataFrame([([1.0, 1.0],), ([2.0, 4.0],), ([3.0, 
8.0],)], ["x"])
+    pdf = pd.DataFrame({"x": [np.array([nan, 1.0]), np.array([2.0, 4.0]), 
np.array([3.0, 8.0])]})
+
+    def check(transformed, expected):
+        assert list(transformed.columns) == ["x", "o"]
+        assert transformed.dtypes.astype(str).tolist() == ["object", "object"]
+        assert [type(value) for value in transformed["o"]] == [np.ndarray] * 3
+        np.testing.assert_allclose(
+            np.array([value.tolist() for value in transformed["o"]]),
+            np.array(expected),
+            rtol=1e-12,
+            equal_nan=True,
+        )
+
+    check(
+        MaxAbsScaler(inputCol="x", 
outputCol="o").fit(fitted).transform(pdf.copy()),
+        [[nan, 0.125], [2 / 3, 0.5], [1.0, 1.0]],
+    )
+    check(
+        StandardScaler(inputCol="x", 
outputCol="o").fit(fitted).transform(pdf.copy()),
+        [[nan, -0.9491579957524987], [0.0, -0.0949157995752498], [1.0, 
1.0440737953277488]],
+    )
+    check(
+        StandardScaler(inputCol="x", 
outputCol="o").fit(pdf).transform(pdf.copy()),
+        [[nan, -0.9491579957524987], [nan, -0.0949157995752498], [nan, 
1.0440737953277488]],
+    )
+
+
+def test_ml_connect_empty_pandas_transforms_as_pyspark(session):
+    # As PySpark's transform of an empty pandas DataFrame, which computes 
locally: a scaler appends
+    # its output column, of object dtype, and a LogisticRegression model 
raises the ValueError of
+    # its transform function, which stacks no array. The server is not asked 
for them.
+    import pandas as pd
+    from pyspark.ml.connect.classification import LogisticRegression
+    from pyspark.ml.connect.feature import MaxAbsScaler, StandardScaler
+
+    fitted = session.createDataFrame([([1.0, 1.0],), ([2.0, 4.0],), ([3.0, 
8.0],)], ["x"])
+    for cls in (MaxAbsScaler, StandardScaler):
+        empty = pd.DataFrame({"x": pd.Series([], dtype=object)})
+        transformed = cls(inputCol="x", 
outputCol="o").fit(fitted).transform(empty)
+        assert list(transformed.columns) == ["x", "o"], cls
+        assert transformed.dtypes.astype(str).tolist() == ["object", 
"object"], cls
+        assert len(transformed) == 0, cls
+
+    model = LogisticRegression(maxIter=5).fit(_labeled(session))
+    with pytest.raises(ValueError, match="need at least one array to stack"):
+        model.transform(pd.DataFrame({"features": pd.Series([], 
dtype=object)}))
+
+
 def 
test_ml_connect_setters_change_the_next_evaluate_and_fit_as_pyspark(session):
     # As PySpark's Params._set: a setter of pyspark.ml.connect sets the param 
of the evaluator or
     # estimator itself and returns it, so the next evaluate or fit uses the 
value of a setter whose
diff --git a/python/tests/test_ml_offline.py b/python/tests/test_ml_offline.py
index 913fbcef..c0c95fc8 100644
--- a/python/tests/test_ml_offline.py
+++ b/python/tests/test_ml_offline.py
@@ -146,6 +146,21 @@ def _relation(df):
     return pb2.Relation.FromString(df._relation_bytes())
 
 
+def _local_data(message):
+    # The Arrow IPC data of the first LocalRelation under message, as 
createDataFrame sends the
+    # local data of a pandas DataFrame, or None when there is none.
+    if message.DESCRIPTOR.name == "LocalRelation":
+        return message.data
+    for field, value in message.ListFields():
+        if field.type != field.TYPE_MESSAGE or 
field.message_type.GetOptions().map_entry:
+            continue
+        for item in value if field.is_repeated else [value]:
+            data = _local_data(item)
+            if data is not None:
+                return data
+    return None
+
+
 class _Color(enum.Enum):
     RED = 1
 
@@ -197,10 +212,16 @@ def 
test_ml_connect_fitted_scalers_transform_the_cached_model(ml_mock):
         fit = _commands_but_deletes(service, sent)[0].ml_command.fit
         assert fit.estimator.name == name
         assert fit.estimator.type == pb2.MlOperator.OPERATOR_TYPE_ESTIMATOR
-        # StandardScaler also sends withMean, as PySpark's scales to (x - 
mean) / std.
+        # 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),
-            "outputCol": pb2.Expression.Literal(string="o"),
+            **outputs,
             **({"withMean": pb2.Expression.Literal(boolean=True)} if cls is 
StandardScaler else {}),
         }
         if cls is StringIndexer:
@@ -224,6 +245,44 @@ def 
test_ml_connect_fitted_scalers_transform_the_cached_model(ml_mock):
         assert transform.params.params["outputCol"] == 
pb2.Expression.Literal(string="o")
 
 
+def 
test_ml_connect_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."
+    )
+    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
+
+
 def _attribute(name):
     # The text of the column of the name `name` exactly, as PySpark's 
col("`name`") sends it.
     return f'unresolved_attribute {{ unparsed_identifier: "`{name}`" 
is_metadata_column: false }}'
@@ -326,8 +385,9 @@ def 
test_ml_connect_native_estimators_take_the_array_columns_of_pyspark(ml_mock)
         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.)
-        params = {"inputCol": "features", "outputCol": "o"} if type(estimator) 
in scalers else {}
+        # 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 {}
         sent = {k: v.string for k, v in fit.params.params.items() if k not in 
_defaults_sent(name)}
         assert sent == params, name
         assert _defaults_sent(name).keys() <= fit.params.params.keys(), name
@@ -636,6 +696,83 @@ def 
test_ml_connect_fit_and_transform_take_the_pandas_frames_of_pyspark(ml_mock)
     assert str(error.value) == "fit() takes a DataFrame or a pandas DataFrame, 
not 'Columns'"
 
 
+def test_ml_connect_pandas_frames_send_their_nan_as_pyspark(ml_mock):
+    # As PySpark computes on a pandas DataFrame locally, its NaN elements of 
arrays and its NaN
+    # values are NaN, not nulls: the DataFrame is sent as an Arrow table of 
its columns, built
+    # without pandas' conversion of NaN to null, which createDataFrame of a 
pandas DataFrame makes
+    # of the elements of an array, though the schema of such an array has no 
null.
+    import math
+
+    import pandas as pd
+    import pyarrow as pa
+    import pyspark.ml.connect as connect
+
+    spark, service = ml_mock
+    pdf = pd.DataFrame(
+        {
+            "x": [np.array([np.nan, 1.0]), np.array([2.0, 4.0])],
+            "y": [1.5, np.nan],
+            "s": ["a", np.nan],
+        }
+    )
+    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())
+    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]
+
+
+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.
+    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")
+    models.append(connect.LogisticRegression().fit(features))
+    sent = _requests_but_deletes(service)
+    with pytest.raises(ValueError, match="need at least one array to stack"):
+        models[-1].transform(empty)
+    assert _requests_but_deletes(service) == sent
+
+
 def 
test_ml_connect_setters_set_the_params_of_their_receiver_as_pyspark(ml_mock):
     # As PySpark's Params._set: every setter of the native pyspark.ml.connect 
estimators,
     # transformers and evaluators sets its param on the object itself and 
returns the object, so
@@ -737,6 +874,10 @@ 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
 
@@ -954,6 +1095,20 @@ def _defaults_sent(name):
     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()}
@@ -1020,6 +1175,12 @@ 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)
@@ -1164,13 +1325,17 @@ 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 = _native_sent(spark, service, obj, models)
-            assert sent.keys() == {sent_name} | _defaults_sent(name).keys(), 
(name, param)
-            assert sent[sent_name][0] == "null", (name, param)
+            assert sent.keys() == sent_names | _defaults_sent(name).keys(), 
(name, param)
+            if sent_names:
+                assert sent[sent_name][0] == "null", (name, param)
             if param != "thresholds":
                 sent = _native_sent(spark, service, cls(**{param: None}), 
models)
-                assert sent.keys() == {sent_name} | 
_defaults_sent(name).keys(), (name, param)
-                assert sent[sent_name][0] == "null", (name, param)
+                assert sent.keys() == sent_names | 
_defaults_sent(name).keys(), (name, param)
+                if sent_names:
+                    assert sent[sent_name][0] == "null", (name, param)
         operator, _ = _native_request(spark, service, cls(), models)
         assert re.fullmatch(name + "_[0-9a-f]{12}", operator.uid), operator.uid
 


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

Reply via email to