This is an automated email from the ASF dual-hosted git repository.
zhengruifeng 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 8101e70b [SPARK-61629][CONNECT][PYTHON] Reject pandas DataFrames in
native ML methods
8101e70b is described below
commit 8101e70be622e626de61cc6b0cb2990e5b77ac2c
Author: Ruifeng Zheng <[email protected]>
AuthorDate: Fri Nov 13 17:34:20 2026 +0800
[SPARK-61629][CONNECT][PYTHON] Reject pandas DataFrames in native ML methods
### What changes were proposed in this pull request?
Require Spark DataFrames for native `fit`, `transform` and `evaluate`.
Reject pandas inputs consistently with `TypeError` before parameter validation,
schema access or any RPC, and direct callers to convert explicitly with
`spark.createDataFrame(...)`.
Cover all 27 native estimator/transformer/evaluator classes, fitted models,
and the unimplemented native Pipeline/CrossValidator entry points. Remove the
implicit pandas conversion helpers and update the compatibility documentation.
The vendored Python scalers retain their upstream behavior.
### Why are the changes needed?
Follow the dataset contract of standard `pyspark.ml` over Spark Connect.
The deprecated `pyspark.ml.connect` pandas contract should not drive these
native methods.
### Does this PR introduce _any_ user-facing change?
Yes. Native methods that implicitly uploaded pandas input or collected
model output now reject pandas input. LogisticRegression fitting also changes
from `NotImplementedError` to the same `TypeError`. Use `df =
spark.createDataFrame(pdf)` before `fit(df)`, `transform(df)` or
`evaluate(df)`, and call `toPandas()` explicitly for a local result.
### How was this patch tested?
- 3,487 Python offline/Arrow handoff tests passed (8 skipped), including
301 ML tests covering empty frames, pandas subclasses, vector cells, missing
columns, validation precedence and rejection without an active session or RPCs.
- 190 live ML tests passed against Spark 4.3.0, including explicit
`createDataFrame` conversion before fit, transform and evaluate. Official
PySpark separately confirmed rejection in representative standard ML methods.
- 681 Rust unit tests passed; all integration tests compiled with and
without `wasm-udf`; rustfmt, workspace Clippy with `-D warnings`, and Ruff
checks passed.
- Connect-only SQL API introspection found zero gaps after the documented
transport-only exclusions.
- Official Spark 4.3.0 Connect suite through the Rust transport: 2,638
passed, 589 skipped across 87 files, with zero unexpected failures. The three
artifact/local-cluster files requiring a separate cluster environment were
excluded.
### Was this patch authored or co-authored using generative AI tooling?
Generated-by: Codex (GPT-6)
This pull request and its description were written by Isaac.
Closes #635 from zhengruifeng/reject-pandas-ml-inputs.
Authored-by: Ruifeng Zheng <[email protected]>
Signed-off-by: Ruifeng Zheng <[email protected]>
---
crates/pyspark-rs/src/ml.rs | 261 +++++++---------------------------------
docs/compatibility.md | 51 ++++----
python/tests/test_ml_e2e.py | 123 +++++++------------
python/tests/test_ml_offline.py | 255 ++++++++++++---------------------------
4 files changed, 191 insertions(+), 499 deletions(-)
diff --git a/crates/pyspark-rs/src/ml.rs b/crates/pyspark-rs/src/ml.rs
index d483bc58..ce3c7730 100644
--- a/crates/pyspark-rs/src/ml.rs
+++ b/crates/pyspark-rs/src/ml.rs
@@ -8,9 +8,9 @@
//! setter sets the param of the wrapper itself and returns the wrapper, as
PySpark's
//! `Params._set` does. `fit`, `transform` and `evaluate` clone the core
object under a short
//! borrow, so that another thread may call a setter while they wait for the
server. They take
-//! a DataFrame or a pandas DataFrame, as PySpark's do (see [`Dataset`]).
+//! a Spark DataFrame, matching the dataset contract of standard `pyspark.ml`
over Spark Connect.
-use pyo3::exceptions::{PyNotImplementedError, PyTypeError, PyValueError};
+use pyo3::exceptions::{PyTypeError, PyValueError};
use pyo3::prelude::*;
use pyo3::pyclass::boolean_struct::False;
use pyo3::types::{PyDict, PyList, PyTuple, PyType};
@@ -294,15 +294,6 @@ fn snapshot<T: Native + PyClass>(slf: &Bound<'_, T>) ->
PyResult<T::Core> {
Ok(this.inner().clone())
}
-/// A dataset of a fit, a transform or an evaluate, as the classes of PySpark's
-/// `pyspark.ml.connect` take it: a DataFrame, or a pandas DataFrame, which
PySpark's compute on
-/// locally, and which is sent here with `createDataFrame` of the active
session, as the native
-/// classes run on the server.
-enum Dataset<'py> {
- Spark(DataFrame),
- Pandas(Bound<'py, PyAny>),
-}
-
/// Whether `dataset` is a pandas DataFrame, of an imported pandas.
fn is_pandas(dataset: &Bound<'_, PyAny>) -> PyResult<bool> {
let pandas = dataset
@@ -317,61 +308,33 @@ fn is_pandas(dataset: &Bound<'_, PyAny>) ->
PyResult<bool> {
}
}
+/// Native ML runs on Spark DataFrames. Pandas input must be converted
explicitly by the caller.
+fn reject_pandas(dataset: &Bound<'_, PyAny>, method: &str) -> PyResult<()> {
+ if is_pandas(dataset)? {
+ return Err(PyTypeError::new_err(format!(
+ "{method}() requires a Spark DataFrame; pandas DataFrames are not
supported. \
+ Convert the input with spark.createDataFrame(...) first."
+ )));
+ }
+ Ok(())
+}
+
/// The dataset of `method`, `dataset`. Another object raises the
`AttributeError` of `attribute`,
/// the attribute that PySpark reads of it first: `select` in a fit (by
`select` of the columns
/// that it reads) and an evaluate (by `aggregate_dataframe`), `columns` in a
transform (by
/// `Transformer._transform`). An object that has it raises a TypeError.
-fn dataset_of<'py>(
- dataset: &Bound<'py, PyAny>,
- method: &str,
- attribute: &str,
-) -> PyResult<Dataset<'py>> {
+fn dataset_of(dataset: &Bound<'_, PyAny>, method: &str, attribute: &str) ->
PyResult<DataFrame> {
if let Ok(df) = dataset.extract::<PyRef<'_, PyDataFrame>>() {
- return Ok(Dataset::Spark(df.dataframe.clone()));
- }
- if is_pandas(dataset)? {
- return Ok(Dataset::Pandas(dataset.clone()));
+ return Ok(df.dataframe.clone());
}
+ reject_pandas(dataset, method)?;
dataset.getattr(attribute)?;
Err(PyTypeError::new_err(format!(
- "{method}() takes a DataFrame or a pandas DataFrame, not '{}'",
+ "{method}() takes a Spark DataFrame, not '{}'",
dataset.get_type().name()?
)))
}
-/// 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. Its column names are the
`str` of the labels
-/// of `pdf`, as createDataFrame names them (a label that is not a string,
such as 0, is a name).
-fn active_dataframe(pdf: &Bound<'_, PyAny>) -> PyResult<DataFrame> {
- 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.str()?)?;
- }
- 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", (table,))?;
- Ok(df.extract::<PyRef<'_, PyDataFrame>>()?.dataframe.clone())
-}
-
/// 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.
type Reads = &'static [(&'static str, Option<&'static str>)];
@@ -399,17 +362,9 @@ fn read_columns(params: &Params, reads: Reads) ->
Option<Vec<String>> {
.collect()
}
-/// The fit of a native estimator, on `dataset` as its JVM estimator reads it:
an array column that
-/// the JVM estimator reads as an ML vector is sent as that vector (see
[`Vectors`]), and a pandas
-/// DataFrame with `createDataFrame` of the active session (see [`Dataset`]).
With `reads`, of an
-/// estimator of a class of PySpark's `pyspark.ml.connect`, only the columns
that PySpark's fit
-/// reads are sent: their `select`, or `dataset[columns]` of a pandas
DataFrame, which raises the
-/// 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, and
-/// take vectors, arrays of numbers and pandas DataFrames, where classic
`pyspark.ml` estimators
-/// take only a `VectorUDT` column.
+/// Fit a native estimator on a Spark DataFrame. Numeric array features are
converted to ML
+/// vectors for the JVM estimator (see [`Vectors`]). When `reads` is provided,
only those input
+/// columns are selected; otherwise the estimator receives the whole DataFrame.
fn fit_native<T>(
slf: &Bound<'_, T>,
dataset: &Bound<'_, PyAny>,
@@ -435,19 +390,9 @@ where
T::Core: Estimator,
{
let py = slf.py();
- let dataset = dataset_of(dataset, "fit", "select")?;
+ let df = dataset_of(dataset, "fit", "select")?;
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),
- Dataset::Pandas(pdf) => {
- let pdf = match &columns {
- Some(columns) => pdf.get_item(PyList::new(py, columns)?)?,
- None => pdf,
- };
- (active_dataframe(&pdf)?, None)
- }
- };
+ let select = reads.and_then(|reads| read_columns(estimator.params(),
reads));
let vectors = Vectors::of(estimator.operator(), estimator.params());
// Found in the schema of the whole DataFrame, which is read once for a
fit and a transform
// of it: the selection keeps the columns as they are. The JVM estimator
reads its columns by
@@ -527,7 +472,7 @@ fn check_labels(py: Python<'_>, df: &DataFrame, label:
&str) -> PyResult<()> {
/// The fit of a native estimator whose core cannot fit it, as Pipeline and
CrossValidator.
/// The core raises NOT_IMPLEMENTED of `feature` before any request, whatever
its params are, so
/// the params are not serialized first, and PySpark's serialization errors of
them are not
-/// raised. So does the fit of a pandas DataFrame, or of another object, which
is not sent.
+/// raised. Pandas inputs are rejected before reaching this unsupported
operation.
fn fit_unimplemented<T>(
slf: &Bound<'_, T>,
dataset: &Bound<'_, PyAny>,
@@ -538,6 +483,7 @@ where
T::Core: Estimator,
{
let py = slf.py();
+ reject_pandas(dataset, "fit")?;
match dataset.extract::<PyRef<'_, PyDataFrame>>() {
Ok(df) => fit_core(py, slf.try_borrow()?.inner().clone(),
&df.dataframe),
Err(_) => Err(crate::column::raise_pyspark(
@@ -763,29 +709,14 @@ fn vector_array(name: &str) -> spark_connect::Column {
/// The input columns of an evaluator, as the JVM evaluator reads them:
`doubles`, a prediction
/// that it reads as a double only, and `score`, a probability that it reads
as a double or a
-/// vector, where PySpark's evaluators read any numeric column, and an array,
as a tensor. `label`
-/// is the label column, which the JVM evaluator reads as its labelCol.
+/// vector, where PySpark's evaluators read any numeric column, and an array,
as a tensor.
struct EvaluatorInputs {
doubles: Vec<String>,
score: Option<String>,
- label: String,
-}
-
-impl EvaluatorInputs {
- /// The columns that PySpark's evaluator reads of its dataset, as its
`_get_input_cols` does:
- /// the prediction or the probability, then the label.
- fn reads(&self) -> Vec<String> {
- self.doubles
- .iter()
- .chain(&self.score)
- .cloned()
- .chain([self.label.clone()])
- .collect()
- }
}
/// Evaluate `dataset` with the JVM evaluator of `slf`, whose input columns
`inputs` gives, as
-/// PySpark's evaluators evaluate it (see [`evaluation_dataset`] and
[`evaluator_input`]). The
+/// PySpark's evaluators evaluate it (see [`evaluator_input`]). The
/// JVM evaluator reads its columns by the spelling of the schema of the
dataset.
fn evaluate_native<T>(
slf: &Bound<'_, T>,
@@ -797,9 +728,9 @@ where
T::Core: Evaluator,
{
let py = slf.py();
+ let df = dataset_of(dataset, "evaluate", "select")?;
let mut evaluator = snapshot(slf)?;
let inputs = inputs(&evaluator);
- let df = evaluation_dataset(dataset, &inputs)?;
let fields = schema_fields(py, &df)?;
// An evaluator that exposes no params is sent as it is (see
`Evaluator::params_mut`).
if let Some(evaluator_params) = evaluator.params_mut() {
@@ -819,20 +750,6 @@ where
})
}
-/// The dataset of `evaluate`, as PySpark's evaluators take it (see
[`Dataset`]): a pandas DataFrame,
-/// which PySpark evaluates locally, is sent with `createDataFrame` of the
active session, as the
-/// evaluators of this client run on the server. Only the columns that
PySpark's evaluator reads
-/// are sent, as `pdf[columns]` selects them, which raises the KeyError of
pandas for a missing one.
-fn evaluation_dataset(dataset: &Bound<'_, PyAny>, inputs: &EvaluatorInputs) ->
PyResult<DataFrame> {
- match dataset_of(dataset, "evaluate", "select")? {
- Dataset::Spark(df) => Ok(df),
- Dataset::Pandas(pdf) => {
- let columns = PyList::new(pdf.py(), inputs.reads())?;
- active_dataframe(&pdf.get_item(columns)?)
- }
- }
-}
-
/// `df` as the JVM evaluator reads it, whose schema has the fields `fields`,
with its columns of
/// `inputs` converted: a prediction (`inputs.doubles`) of another numeric
type is cast to a
/// double, and a score (`inputs.score`) of another numeric type too, while an
array score is sent
@@ -878,7 +795,6 @@ enum PySparkModel {
/// of which the JVM model, whose rawPredictionCol is empty (see
[`PyLogisticRegression`]),
/// outputs no raw prediction. (A null column param, which the server
rejects, fits no model.)
LogisticRegression {
- features: Option<String>,
prediction: Option<String>,
probability: Option<String>,
},
@@ -893,7 +809,6 @@ impl PySparkModel {
string_or(params, name, Some(default)).filter(|name|
!name.is_empty())
};
Some(Self::LogisticRegression {
- features: string_or(params, "featuresCol",
Some("features")),
prediction: output("predictionCol", "prediction"),
probability: output("probabilityCol", "probability"),
})
@@ -902,13 +817,6 @@ impl PySparkModel {
}
}
- /// The column that PySpark's transform reads (`_input_columns`).
- fn input(&self) -> Option<&str> {
- match self {
- Self::LogisticRegression { features, .. } => features.as_deref(),
- }
- }
-
/// The columns that PySpark's transform appends, in their order
(`_output_columns`).
fn outputs(&self) -> Vec<String> {
match self {
@@ -920,17 +828,6 @@ impl PySparkModel {
}
}
- /// The transform of the empty pandas DataFrame `copy` (a shallow copy of
it), as PySpark's
- /// 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>> {
- match self {
- Self::LogisticRegression { .. } => {
- Err(PyValueError::new_err("need at least one array to stack"))
- }
- }
- }
-
/// 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<()> {
@@ -950,60 +847,6 @@ impl PySparkModel {
}
}
-/// The transform of the pandas DataFrame `pdf`, as PySpark's
`transform_dataframe_column`
-/// returns it: a shallow copy of `pdf` (`copy(deep=False)`) with the output
columns inserted
-/// after its columns. PySpark's computes them locally, where `transform`
computes them on the
-/// server, of `pdf` sent with `createDataFrame` of the active session, and
they are taken back by
-/// `toPandas`, of the rows in their order, with the index of `pdf`. A model
of a class of
-/// PySpark's (see [`PySparkModel`]) is sent only the column that PySpark's
reads, `pdf[input]`,
-/// which raises the KeyError of pandas for a missing column, as PySpark's;
another transform is
-/// sent the whole of `pdf`, and its outputs are the columns that the server
appends.
-fn transform_pandas<'py>(
- pdf: &Bound<'py, PyAny>,
- pyspark: Option<&PySparkModel>,
- transform: impl FnOnce(&DataFrame) -> PyResult<DataFrame>,
-) -> PyResult<Bound<'py, PyAny>> {
- let py = pdf.py();
- let kwargs = PyDict::new(py);
- kwargs.set_item("deep", false)?;
- let copy = pdf.call_method("copy", (), Some(&kwargs))?;
- let sent = match pyspark.and_then(PySparkModel::input) {
- 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(©);
- }
- let df = active_dataframe(&sent)?;
- let out = transform(&df)?;
- let outputs = match pyspark {
- Some(model) => model.outputs(),
- None => {
- let sent: Vec<String> = schema_fields(py, &df)?
- .into_iter()
- .map(|field| field.name)
- .collect();
- schema_fields(py, &out)?
- .into_iter()
- .map(|field| field.name)
- .filter(|name| !sent.contains(name))
- .collect()
- }
- };
- let selected = out.select(outputs.iter().map(|name| exact_column(name)));
- let result = PyDataFrame::new(selected)
- .to_pandas(py, None)?
- .into_bound(py);
- result.setattr("index", copy.getattr("index")?)?;
- for output in &outputs {
- let at = copy.getattr("columns")?.len()?;
- copy.call_method1("insert", (at, output, result.get_item(output)?))?;
- }
- Ok(copy)
-}
-
/// A fitted ML model (result of `Estimator.fit`), wrapping a boxed core
`Model`.
#[pyclass(name = "MLModel", module = "pyspark.ml.connect")]
pub struct PyMLModel {
@@ -1014,21 +857,19 @@ pub struct PyMLModel {
#[pymethods]
impl PyMLModel {
- /// Apply the model to `dataset`, a DataFrame or a pandas DataFrame, as
PySpark's
- /// `Transformer.transform` takes it, whose transform of a pandas
DataFrame is a pandas
- /// DataFrame (see [`transform_pandas`]). The model of a class of
PySpark's raises PySpark's
- /// ValueError of an output column that the dataset has already (see
[`PySparkModel`]).
- fn transform(&self, py: Python<'_>, dataset: &Bound<'_, PyAny>) ->
PyResult<Py<PyAny>> {
- let pyspark = PySparkModel::of(self.model.operator(),
self.model.params());
+ /// Apply the model to a Spark DataFrame. LogisticRegression checks for
existing output
+ /// columns before constructing the transform (see [`PySparkModel`]).
+ fn transform(&self, py: Python<'_>, dataset: &Bound<'_, PyAny>) ->
PyResult<PyDataFrame> {
let input = dataset_of(dataset, "transform", "columns")?;
+ let pyspark = PySparkModel::of(self.model.operator(),
self.model.params());
if let Some(model) = &pyspark {
model.check_outputs(dataset)?;
}
- let transform = |df: &DataFrame| self.transform_dataframe(py, df,
pyspark.as_ref());
- Ok(match input {
- Dataset::Spark(df) => Py::new(py,
PyDataFrame::new(transform(&df)?))?.into_any(),
- Dataset::Pandas(pdf) => transform_pandas(&pdf, pyspark.as_ref(),
transform)?.unbind(),
- })
+ Ok(PyDataFrame::new(self.transform_dataframe(
+ py,
+ &input,
+ pyspark.as_ref(),
+ )?))
}
}
@@ -1214,22 +1055,15 @@ impl PyVectorAssembler {
) -> PyResult<Bound<'py, Self>> {
set_param(slf, "outputCol", Kind::Str, value)
}
- /// Transform `dataset`, a DataFrame or a pandas DataFrame, as PySpark's
transformers take it
- /// (see [`transform_pandas`]).
- fn transform(slf: &Bound<'_, Self>, dataset: &Bound<'_, PyAny>) ->
PyResult<Py<PyAny>> {
+ /// Transform a Spark DataFrame.
+ fn transform(slf: &Bound<'_, Self>, dataset: &Bound<'_, PyAny>) ->
PyResult<PyDataFrame> {
let py = slf.py();
let input = dataset_of(dataset, "transform", "columns")?;
let mut transformer = snapshot(slf)?;
- let mut transform =
- |df: &DataFrame| py.detach(||
transformer.transform(df).map_err(Box::new));
- Ok(match input {
- Dataset::Spark(df) => {
- Py::new(py,
PyDataFrame::new(transform(&df).to_pyerr()?))?.into_any()
- }
- Dataset::Pandas(pdf) => {
- transform_pandas(&pdf, None, |df|
transform(df).to_pyerr())?.unbind()
- }
- })
+ let output = py
+ .detach(|| transformer.transform(&input).map_err(Box::new))
+ .to_pyerr()?;
+ Ok(PyDataFrame::new(output))
}
}
@@ -1325,13 +1159,8 @@ impl PyLogisticRegression {
set_param(slf, "tol", Kind::Float, value)
}
/// Fit `dataset`, of which the fit reads the features and the labels, as
PySpark's (see
- /// [`fit_native`]). As PySpark's, it fits no pandas DataFrame yet.
+ /// [`fit_native`]).
fn fit(slf: &Bound<'_, Self>, dataset: &Bound<'_, PyAny>) ->
PyResult<PyMLModel> {
- if is_pandas(dataset)? {
- return Err(PyNotImplementedError::new_err(
- "Fitting pandas dataframe is not supported yet.",
- ));
- }
fit_native_checked(
slf,
dataset,
@@ -1948,6 +1777,7 @@ impl PyOneVsRest {
}
fn fit(slf: &Bound<'_, Self>, dataset: &Bound<'_, PyAny>) ->
PyResult<PyMLModel> {
+ reject_pandas(dataset, "fit")?;
let classifier = slf
.try_borrow()?
.classifier
@@ -4406,7 +4236,6 @@ impl PyRegressionEvaluator {
evaluate_native(slf, dataset, |evaluator| EvaluatorInputs {
doubles: vec![evaluator.prediction_col().to_string()],
score: None,
- label: evaluator.label_col().to_string(),
})
}
}
@@ -4511,7 +4340,6 @@ impl PyBinaryClassificationEvaluator {
evaluate_native(slf, dataset, |evaluator| EvaluatorInputs {
doubles: Vec::new(),
score: Some(evaluator.raw_prediction_col().to_string()),
- label: evaluator.label_col().to_string(),
})
}
}
@@ -4839,7 +4667,6 @@ impl PyMulticlassClassificationEvaluator {
evaluate_native(slf, dataset, |evaluator| EvaluatorInputs {
doubles: vec![evaluator.prediction_col().to_string()],
score: None,
- label: evaluator.label_col().to_string(),
})
}
}
diff --git a/docs/compatibility.md b/docs/compatibility.md
index fd7d8ec4..fc8cd320 100644
--- a/docs/compatibility.md
+++ b/docs/compatibility.md
@@ -231,8 +231,7 @@ PySpark's: a `bigint` prediction, and then the
`array<double>` of the probabilit
`rawPredictionCol`, a param of the JVM estimator that PySpark's does not have.
The
probabilities are the JVM's doubles, where PySpark's are of float32 tensors.
As PySpark's, its
fit reads only the features and the labels, so that a DataFrame with a
`prediction`,
-`probability` or `rawPrediction` column is fitted, and it fits no pandas
DataFrame, raising
-PySpark's `NotImplementedError`.
+`probability` or `rawPrediction` column is fitted.
Fitting returns a server-cached model. Prediction uses that model's object
reference and must use the same Spark session. Models are obtained through
@@ -266,26 +265,22 @@ 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 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
-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.
+Native `fit`, `transform` and `evaluate` require a Spark DataFrame, matching
the dataset
+contract of standard `pyspark.ml` over Spark Connect. Passing a pandas
DataFrame raises
+`TypeError` before parameter validation, schema access or any server request.
This also applies
+to empty pandas DataFrames and to the native Pipeline and CrossValidator
placeholders.
+Convert local data explicitly with `df = spark.createDataFrame(pdf)` before
calling
+`estimator.fit(df)`, `model.transform(df)` or `evaluator.evaluate(df)`.
Transforms return Spark
+DataFrames; call `toPandas()` explicitly when a local result is needed. The
deprecated
+`pyspark.ml.connect` pandas contract is not the target for these native
methods. The vendored
+Python scalers described below retain their upstream behavior.
+
+Other non-DataFrame objects retain their existing errors: a missing `select`
in a fit or
+an evaluate, or `columns` in a transform, raises `AttributeError`; an object
with that attribute
+raises `TypeError`. LogisticRegression still selects only its features and
labels for fitting.
+An output column that overlaps either input raises the JVM's error during
fitting. Its model
+checks for existing output column names before constructing the transform;
other native models
+leave output validation to their JVM models.
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):
@@ -295,14 +290,10 @@ they do not raise. The evaluators cast a prediction or a
probability of another
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 native estimators accept Spark DataFrames with vector or numeric array
feature columns.
+A fit and the transform of its model read the DataFrame schema and send an
array `featuresCol`
+as the vector (`array_to_vector`) that the JVM reads; the transform preserves
the input array
+column in its output. Standard `pyspark.ml` estimators require a `VectorUDT`
feature column.
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`
diff --git a/python/tests/test_ml_e2e.py b/python/tests/test_ml_e2e.py
index 817e4131..869348f7 100644
--- a/python/tests/test_ml_e2e.py
+++ b/python/tests/test_ml_e2e.py
@@ -440,11 +440,11 @@ def
test_ml_connect_binary_evaluator_scores_the_probability_of_pyspark_docstring
assert BinaryClassificationEvaluator().evaluate(dataset) ==
pytest.approx(5 / 6, abs=1e-9)
-def
test_ml_connect_evaluators_take_the_columns_and_the_pandas_frames_of_pyspark_tests(session):
+def test_ml_connect_evaluators_take_spark_columns_and_reject_pandas(session):
# The inputs of PySpark's own evaluator tests
(test_legacy_mode_evaluation.py) and docstrings,
# which its torch evaluators read as tensors: int labels and predictions,
a float32 or an
- # array probability, whose column 1 is the positive class, and pandas
DataFrames, which are
- # sent through createDataFrame here, as the evaluators run on the server.
The JVM evaluators
+ # array probability, whose column 1 is the positive class. Pandas inputs
must be converted
+ # explicitly to Spark DataFrames. The JVM evaluators
# give doubles, 0.6 where PySpark's float32 tensors give
0.6000000238418579.
from pyspark.ml.connect.evaluation import (
BinaryClassificationEvaluator,
@@ -459,7 +459,8 @@ def
test_ml_connect_evaluators_take_the_columns_and_the_pandas_frames_of_pyspark
)
accuracy = MulticlassClassificationEvaluator(metricName="accuracy")
assert accuracy.evaluate(multiclass) == pytest.approx(0.6)
- assert accuracy.evaluate(dataset=multiclass.toPandas()) ==
pytest.approx(0.6)
+ with pytest.raises(TypeError, match="requires a Spark DataFrame"):
+ accuracy.evaluate(dataset=multiclass.toPandas())
docstring = session.createDataFrame(
[(1, 1), (0, 0), (2, 2), (1, 0), (2, 1)], schema=["label",
"prediction"])
assert MulticlassClassificationEvaluator().evaluate(docstring) ==
pytest.approx(0.6)
@@ -468,7 +469,8 @@ def
test_ml_connect_evaluators_take_the_columns_and_the_pandas_frames_of_pyspark
[(1.0, 2), (-1.0, -1), (2.0, 3)], schema=["label", "prediction"])
mse = RegressionEvaluator(metricName="mse")
assert mse.evaluate(regression) == pytest.approx(2 / 3)
- assert mse.evaluate(regression.toPandas()) == pytest.approx(2 / 3)
+ with pytest.raises(TypeError, match="requires a Spark DataFrame"):
+ mse.evaluate(regression.toPandas())
binary = session.createDataFrame(
[
@@ -487,44 +489,46 @@ def
test_ml_connect_evaluators_take_the_columns_and_the_pandas_frames_of_pyspark
for column in ("prob2", "prob32"):
evaluator = BinaryClassificationEvaluator(metricName=metric,
probabilityCol=column)
assert evaluator.evaluate(binary) == pytest.approx(expected),
(metric, column)
- assert evaluator.evaluate(binary.toPandas()) ==
pytest.approx(expected), (metric, column)
+ with pytest.raises(TypeError, match="requires a Spark DataFrame"):
+ evaluator.evaluate(binary.toPandas())
auroc =
BinaryClassificationEvaluator(probabilityCol="prob2").evaluate(binary)
assert auroc == pytest.approx(2 / 3)
with pytest.raises(AttributeError, match="'list' object has no attribute
'select'"):
accuracy.evaluate([(1, 1)])
-def
test_ml_connect_pandas_frames_name_int_labels_and_read_their_columns_as_pyspark(session):
- # As PySpark's pandas DataFrames: an evaluator selects the columns it
reads, so a uint64
- # column that Arrow does not take is not sent, and a native model that
sends the whole frame
- # names its int label "0", as createDataFrame names it by its str, and
keeps it in its output.
- import numpy as np
+def test_native_ml_accepts_explicitly_converted_pandas(session):
import pandas as pd
- from pyspark.ml.connect import KMeans
- from pyspark.ml.connect.evaluation import RegressionEvaluator
-
- pdf = pd.DataFrame(
- {
- 0: [1.0, 2.0, 3.0],
- "label": [1.0, 2.0, 3.0],
- "prediction": [1.0, 2.5, 3.0],
- "u": np.array([1, 2, 3], dtype=np.uint64),
- }
- )
- evaluator = RegressionEvaluator(labelCol="label",
predictionCol="prediction")
- assert evaluator.evaluate(pdf) == pytest.approx(0.28867513459481287)
-
- train = session.createDataFrame(
- [([0.0, 1.0], 0.0), ([1.0, 0.0], 1.0), ([2.0, 2.0], 1.0), ([3.0, 1.0],
0.0)],
- schema=["features", "label"],
- )
- model = KMeans(k=2, seed=1).fit(train)
- frame = pd.DataFrame({0: [7, 8], "features": [np.array([0.0, 1.0]),
np.array([3.0, 1.0])]})
- out = model.transform(frame)
- assert list(out.columns) == [0, "features", "prediction"]
- assert out[0].tolist() == [7, 8]
- assert out["prediction"].tolist()[0] != out["prediction"].tolist()[1]
-
+ import pyspark.ml.connect as connect
+ from pyspark.sql import DataFrame
+
+ # Exercise the native bindings, independently of the deprecated Python ML
implementations.
+ assert connect.KMeans is __import__("pyspark._pyspark",
fromlist=["KMeans"]).KMeans
+ pdf = pd.DataFrame({"features": [[0.0, 1.0], [1.0, 0.0], [2.0, 2.0], [3.0,
1.0]],
+ "label": [0.0, 1.0, 1.0, 0.0]})
+ df = session.createDataFrame(pdf)
+ for estimator in [connect.LogisticRegression(maxIter=5),
connect.KMeans(k=2, seed=1)]:
+ with pytest.raises(TypeError, match="requires a Spark DataFrame"):
+ estimator.fit(pdf)
+ model = estimator.fit(df)
+ with pytest.raises(TypeError, match="requires a Spark DataFrame"):
+ model.transform(pdf)
+ transformed = model.transform(df)
+ assert isinstance(transformed, DataFrame)
+ assert transformed.count() == len(pdf)
+ assert set(transformed.toPandas()["prediction"]) <= {0, 1}
+
+ assembler = connect.VectorAssembler(inputCols=["label"],
outputCol="assembled")
+ with pytest.raises(TypeError, match="requires a Spark DataFrame"):
+ assembler.transform(pdf)
+ assert [row.assembled.toArray().tolist() for row in
assembler.transform(df).collect()] == [
+ [0.0], [1.0], [1.0], [0.0]
+ ]
+ scored = pd.DataFrame({"label": [1.0, 2.0, 3.0], "prediction": [1.0, 2.5,
3.0]})
+ evaluator = connect.RegressionEvaluator()
+ with pytest.raises(TypeError, match="requires a Spark DataFrame"):
+ evaluator.evaluate(scored)
+ assert evaluator.evaluate(session.createDataFrame(scored)) ==
pytest.approx(0.28867513459481287)
def
test_ml_connect_columns_spelled_in_another_case_than_the_schema_as_pyspark(session):
# As Spark resolves a column name regardless of case: a native fit,
transform and evaluate
@@ -741,19 +745,11 @@ def
test_ml_connect_logistic_regression_and_scalers_output_the_columns_of_pyspar
assert len(fitted.transform(labeled).collect()) == 4
-def
test_ml_connect_estimators_fit_and_transform_the_pandas_frames_of_pyspark(session):
- # 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). 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.
+def test_vendored_ml_scalers_keep_their_pandas_contract(session):
+ # These pure-Python upstream scalers are separate from the native ML
bindings.
import numpy as np
import pandas as pd
- from pyspark.ml.connect.classification import LogisticRegression
- from pyspark.ml.connect.clustering import KMeans
- from pyspark.ml.connect.feature import MaxAbsScaler, StandardScaler,
VectorAssembler
+ from pyspark.ml.connect.feature import MaxAbsScaler, StandardScaler
features = [[1.0, 2.0], [2.0, -1.0], [-3.0, -2.0]]
pdf = pd.DataFrame({"features": features, "label": [1, 1, 0]}, index=[10,
20, 30])
@@ -781,31 +777,6 @@ def
test_ml_connect_estimators_fit_and_transform_the_pandas_frames_of_pyspark(se
assert appended(transformed, [output])[output].iloc[0].tolist() ==
pytest.approx(
[0.3779644730092272, 1.1208970766356101], rel=1e-12)
- labeled = session.createDataFrame(pdf)
- with pytest.raises(NotImplementedError, match="Fitting pandas dataframe is
not supported yet."):
- LogisticRegression().fit(pdf)
- predicted = appended(
- LogisticRegression(maxIter=20).fit(labeled).transform(pdf),
["prediction", "probability"]
- )
- assert predicted.dtypes.astype(str).tolist() == ["int64", "object"]
- assert predicted["prediction"].tolist() == [1, 1, 0]
- for prediction, probability in zip(predicted["prediction"],
predicted["probability"]):
- assert type(probability) is np.ndarray and probability.dtype ==
np.float64
- assert probability.sum() == pytest.approx(1.0) and
probability.argmax() == prediction
- message = "Transformers does not allow output column having the same name
with existing columns."
- with pytest.raises(ValueError, match=message):
-
LogisticRegression(maxIter=5).fit(labeled).transform(pdf.assign(probability=0))
-
- clusters = appended(KMeans(k=2, seed=1).fit(pdf).transform(pdf),
["prediction"])
- assert len(set(clusters["prediction"])) == 2
- assembled = VectorAssembler(inputCols=["label"],
outputCol="v").transform(pdf)
- assert [value.toArray().tolist() for value in appended(assembled,
["v"])["v"]] == [
- [1.0], [1.0], [0.0]
- ]
- with pytest.raises(Exception, match="Column prediction already exists"):
- 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
@@ -870,10 +841,8 @@ def
test_ml_connect_scalers_transform_the_nan_of_pandas_frames_as_pyspark(sessio
)
-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.
+def test_ml_connect_empty_pandas_transforms(session):
+ # Vendored Python scalers retain their local behavior; native models
reject pandas input.
import pandas as pd
from pyspark.ml.connect.classification import LogisticRegression
from pyspark.ml.connect.feature import MaxAbsScaler, StandardScaler
@@ -887,7 +856,7 @@ def
test_ml_connect_empty_pandas_transforms_as_pyspark(session):
assert len(transformed) == 0, cls
model = LogisticRegression(maxIter=5).fit(_labeled(session))
- with pytest.raises(ValueError, match="need at least one array to stack"):
+ with pytest.raises(TypeError, match="requires a Spark DataFrame"):
model.transform(pd.DataFrame({"features": pd.Series([],
dtype=object)}))
diff --git a/python/tests/test_ml_offline.py b/python/tests/test_ml_offline.py
index 154916b0..d809da11 100644
--- a/python/tests/test_ml_offline.py
+++ b/python/tests/test_ml_offline.py
@@ -537,8 +537,8 @@ 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 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,
+ # any execution, as PySpark reads the dataset's columns first. 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
@@ -572,9 +572,8 @@ def
test_ml_connect_transforms_raise_the_value_error_of_pyspark_of_an_existing_o
with pytest.raises(ValueError) as error:
model.transform(spark.range(1))
assert str(error.value) == message, column
- with pytest.raises(ValueError) as error:
+ with pytest.raises(TypeError, match="requires a Spark DataFrame"):
model.transform(pd.DataFrame({"f": [[1.0]], column: [1.0]}))
- assert str(error.value) == message, column
assert _requests_but_deletes(service) == sent, column
for model, column in [
@@ -586,84 +585,14 @@ def
test_ml_connect_transforms_raise_the_value_error_of_pyspark_of_an_existing_o
model.transform(spark.range(1)) # No ValueError.
-def
test_ml_connect_fit_and_transform_take_the_pandas_frames_of_pyspark(ml_mock):
- # As PySpark's pyspark.ml.connect classes, whose fit and transform take a
pandas DataFrame,
- # which they compute on locally: here it is sent with createDataFrame of
the active session,
- # of only the input column that the fit or the transform of PySpark's
class reads, and the
- # 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,
- # 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
+def test_native_ml_other_invalid_inputs(ml_mock):
import pyspark.ml.connect as connect
- from _mock_connect_server import ddl_data_type
- from pyspark.errors import PySparkNotImplementedError
spark, service = ml_mock
- # The settings that toPandas reads, of a Spark 4.3.0 server.
- service.confs = {
- "spark.sql.execution.pandas.structHandlingMode": "legacy",
- "spark.sql.execution.arrow.pyspark.selfDestruct.enabled": "false",
- }
- service.data_type = ddl_data_type("features array<double>")
- pdf = pd.DataFrame({"features": [[1.0, 2.0], [2.0, -1.0]], "label": [1,
0]}, index=[7, 9])
- models = [] # Kept alive, so that no model is released during the checks.
-
- def fit(estimator):
- # The Fit that the fit of pdf sends.
- sent = len(service.execute_requests)
- service.execute_payload = _operator_info("model-1")
- models.append(estimator.fit(pdf))
- return _commands_but_deletes(service, sent)[0].ml_command.fit
-
- sent = fit(connect.KMeans()).dataset.with_columns
- assert list(sent.input.to_df.column_names) == ["features", "label"]
-
- sent = _requests_but_deletes(service)
- with pytest.raises(NotImplementedError) as error:
- connect.LogisticRegression().fit(pdf)
- assert str(error.value) == "Fitting pandas dataframe is not supported yet."
- for unimplemented in (connect.Pipeline(), connect.CrossValidator()):
- with pytest.raises(PySparkNotImplementedError) as error:
- unimplemented.fit(pdf)
- assert error.value.getCondition() == "NOT_IMPLEMENTED"
- assert _requests_but_deletes(service) == sent
-
- service.execute_payload = _operator_info("model-2")
+ service.execute_payload = _operator_info("model-1")
service.query_payload = _labels_result()
- models.append(connect.LogisticRegression().fit(spark.range(1)))
+ model = connect.LogisticRegression().fit(spark.range(1))
service.query_payload = None
- service.execute_payload = _arrow_result(
- pa.table({
- "prediction": pa.array([1, 0], pa.int64()),
- "probability": pa.array([[0.25, 0.75], [0.5, 0.5]],
pa.list_(pa.float64())),
- }),
- T.StructType([
- T.StructField("prediction", T.LongType()),
- T.StructField("probability", T.ArrayType(T.DoubleType())),
- ]),
- )
- transformed = models[-1].transform(pdf)
- root = _last_request_but_deletes(service).plan.root
- assert [_text(e) for e in root.project.expressions] == [
- _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.
@@ -673,95 +602,21 @@ 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:
- models[-1].transform(other)
+ model.transform(other)
assert str(error.value) == f"'{name}' object has no attribute
'columns'"
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:
- models[-1].transform(Columns())
- assert str(error.value) == "transform() takes a DataFrame or a pandas
DataFrame, not 'Columns'"
+ model.transform(Columns())
+ assert str(error.value) == "transform() takes a Spark DataFrame, not
'Columns'"
with pytest.raises(TypeError) as error:
connect.KMeans().fit(Columns())
- 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.
-
- # 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.
- 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_pandas_frames_name_and_read_their_columns_as_pyspark(ml_mock):
- # As PySpark's evaluators, which take a pandas DataFrame and read only
their input columns of
- # it (aggregate_dataframe selects them: dataframe[columns]): the columns
of the frame are named
- # by the str of their labels, as createDataFrame names them, so the label
0 is "0" and a label
- # that is not a string is no TypeError, and only the columns that the
evaluator reads are sent,
- # so a column of a type that Arrow does not take, a uint64 here, is not
sent either.
- import numpy as np
- import pandas as pd
- import pyarrow as pa
- import pyspark.ml.connect as connect
- from _mock_connect_server import ddl_data_type
+ assert str(error.value) == "fit() takes a Spark DataFrame, not 'Columns'"
- spark, service = ml_mock
- service.data_type = ddl_data_type("0 double, label double, prediction
double")
- pdf = pd.DataFrame(
- {
- 0: [1.0, 2.0, 3.0],
- "label": [1.0, 2.0, 3.0],
- "prediction": [1.0, 2.5, 3.0],
- "u": np.array([1, 2, 3], dtype=np.uint64),
- }
- )
- models = [] # Kept alive, so that no model is released during the checks.
- sent = len(service.execute_requests)
- service.execute_payload =
_ml_result(param=pb2.Expression.Literal(double=0.25))
- assert connect.RegressionEvaluator().evaluate(pdf) == 0.25
- evaluate = _commands_but_deletes(service, sent)[0].ml_command.evaluate
- table = pa.ipc.open_stream(_local_data(evaluate.dataset)).read_all()
- assert table.column_names == ["prediction", "label"]
- assert table.column("label").to_pylist() == [1.0, 2.0, 3.0]
- # The other native classes send the whole of the frame, which its int
label names "0".
- sent = len(service.execute_requests)
- service.execute_payload = _operator_info("model-1")
- models.append(connect.KMeans().fit(pdf.drop(columns=["u"])))
- 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 == ["0", "label", "prediction"]
def
test_ml_connect_native_columns_are_spelled_as_the_schema_of_the_dataset(ml_mock):
@@ -814,26 +669,6 @@ def
test_ml_connect_native_columns_are_spelled_as_the_schema_of_the_dataset(ml_m
assert evaluate.params.params["predictionCol"] ==
pb2.Expression.Literal(string="prediction")
-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-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
def
test_ml_connect_setters_set_the_params_of_their_receiver_as_pyspark(ml_mock):
@@ -3872,3 +3707,73 @@ def
test_remaining_regressor_native_parameters_match_official_fixture(ml_mock, n
operator, params = _native_request(spark, service, estimator, models)
assert operator.name == "org.apache.spark.ml.regression." + name
assert params ==
pb2.MlParams.FromString(base64.b64decode(case["params_b64"]))
+
+
[email protected](params=["arrays", "empty", "vectors", "subclass",
"missing-columns"])
+def pandas_ml_input(request):
+ import pandas as pd
+ from pyspark.ml.linalg import Vectors
+
+ if request.param == "empty":
+ return pd.DataFrame({"features": pd.Series([], dtype=object)})
+ if request.param == "vectors":
+ return pd.DataFrame({
+ "features": [Vectors.dense([1.0, 0.0]), Vectors.sparse(2, {1:
2.0})],
+ "label": [0.0, 1.0],
+ })
+ if request.param == "missing-columns":
+ return pd.DataFrame({0: [object()]})
+
+ class Frame(pd.DataFrame):
+ pass
+
+ cls = Frame if request.param == "subclass" else pd.DataFrame
+ return cls({"features": [[1.0, 0.0], [0.0, 2.0]], "label": [0.0, 1.0],
+ "prediction": [0.0, 1.0]}, index=[7, 9])
+
+
+def _native_ml_method(name):
+ import pyspark.ml.connect as connect
+
+ instance = getattr(connect, name)()
+ method = ("evaluate" if name.endswith("Evaluator") else
+ "transform" if name == "VectorAssembler" else "fit")
+ return getattr(instance, method)
+
+
[email protected]("name", [*_NATIVE_PARAMS, "OneVsRest"])
+def test_native_ml_rejects_pandas_without_active_session(name,
pandas_ml_input):
+ assert SparkSession.getActiveSession() is None
+ method = _native_ml_method(name)
+ with pytest.raises(TypeError) as error:
+ method(dataset=pandas_ml_input)
+ assert str(error.value) == (
+ f"{method.__name__}() requires a Spark DataFrame; pandas DataFrames
are not supported. "
+ "Convert the input with spark.createDataFrame(...) first."
+ )
+ assert SparkSession.getActiveSession() is None
+
+
[email protected]("estimator_name", ["LogisticRegression", "KMeans"])
+def test_native_ml_rejects_pandas_before_any_requests(ml_mock,
pandas_ml_input, estimator_name):
+ import pyspark.ml.connect as connect
+
+ spark, service = ml_mock
+ service.execute_payload = _operator_info("model-1")
+ service.query_payload = _labels_result()
+ model = getattr(connect, estimator_name)().fit(spark.range(1))
+ service.query_payload = None
+
+ def requests():
+ return (_requests_but_deletes(service), len(service.analyze_requests),
+ len(service.config_requests))
+
+ sent = requests()
+ methods = [_native_ml_method(name) for name in [*_NATIVE_PARAMS,
"OneVsRest"]]
+ methods += [model.transform, connect.OneVsRest(parallelism=0).fit,
+ connect.LogisticRegression(maxIter=2**100).fit,
+ connect.VectorAssembler(inputCols=[]).transform]
+ for method in methods:
+ with pytest.raises(TypeError, match="requires a Spark DataFrame"):
+ method(pandas_ml_input)
+ assert requests() == sent
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]