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 84193a49 [SPARK-61591][CONNECT][PYTHON] Output PySpark's columns from
the native LogisticRegression and take pandas DataFrames in the native ML fit
and transform, in the Python client
84193a49 is described below
commit 84193a49542c264fc1f8a48162a7e0c97c5d1d2d
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Fri Nov 13 08:51:42 2026 +0900
[SPARK-61591][CONNECT][PYTHON] Output PySpark's columns from the native
LogisticRegression and take pandas DataFrames in the native ML fit and
transform, in the Python client
### What changes were proposed in this pull request?
A follow-up of #563 (SPARK-61531) and #574 (SPARK-61545). The native
classes of `pyspark.ml.connect` (JVM estimators over the Connect ML protocol)
now output PySpark's columns and take its inputs:
**LogisticRegression.**
- Its model outputs PySpark's `_output_columns`: a `bigint` prediction,
then an `array<double>` probability, and no `rawPrediction`. Both are nullable,
and the array contains null, as PySpark's pandas UDF outputs them.
- It used to output the JVM's `rawPrediction` and `probability` vectors and
a non-nullable double prediction.
- An empty `probabilityCol` outputs no probability, as PySpark's `if
prob_col`.
- The constructor sends `rawPredictionCol=""`, as the StandardScaler
constructor sends `withMean`, so a dataset with a `rawPrediction` column fits
and transforms.
- The constructor takes `probabilityCol` and `tol` in PySpark's order, with
`setProbabilityCol` and `setTol`.
- PySpark's PyTorch-only params (`numTrainWorkers`, `batchSize`,
`learningRate`, `momentum`, `seed`) still raise the unexpected-keyword
`TypeError`, since the JVM's L-BFGS cannot use them. This is documented.
**pandas DataFrames.** `fit` and `transform` take a `dataset`, a DataFrame
or a pandas DataFrame, as PySpark's do:
- `LogisticRegression.fit` of a pandas DataFrame raises PySpark's
`NotImplementedError("Fitting pandas dataframe is not supported yet.")`.
- The other estimators fit it through `createDataFrame` of the active
session.
- A model's transform of a pandas DataFrame returns a pandas DataFrame: a
shallow copy of the input with the output columns appended, computed on the
server. MaxAbsScaler's matches the reference exactly: columns, dtypes, index,
`float64` ndarray cells, and the shallow copy.
- Another object raises PySpark's `AttributeError` of `columns` (transform)
or `select` (fit).
**Existing output columns.** The models of LogisticRegression, MaxAbsScaler
and StandardScaler raise PySpark's `ValueError("Transformers does not allow
output column having the same name with existing columns.")` before
transforming. They used to raise the server's `IllegalArgumentException`. Their
fits send only the columns that PySpark's fits read (features and label, or
`inputCol`), so a dataset with an output column fits, as in PySpark.
**Scaler output.** The scalers output an `array<double>` that is nullable
and contains null, as PySpark's does. It used to be neither.
On the live server, the transform schemas of the reference and of this
client are now identical for MaxAbsScaler, StandardScaler, and
LogisticRegression with default, empty and renamed probability columns.
### Why are the changes needed?
To match PySpark 4.3.0's `pyspark.ml.connect`.
### Does this PR introduce _any_ user-facing change?
Yes, in the Python client. The native LogisticRegression model outputs a
bigint prediction and an array probability, with no raw prediction. The native
classes take pandas DataFrames, raise PySpark's errors, and output nullable
scaled arrays.
### How was this patch tested?
- New and updated tests in `test_ml_offline.py` (10) and `test_ml_e2e.py`
(3), which fail without the change.
- The lib tests of both crates (857 passed), the Rust integration tests
against a local Spark 4.3.0 server (998 passed, 26 ignored), the build of all
tests with `wasm-udf`, the offline Python suites (3269 passed, 8 skipped), and
the live drop-in, Arrow and ML suites (310 and 51 passed), on master with
SPARK-61590 and SPARK-61591 applied. `cargo fmt --all --check` and the no-stub
audit pass.
### 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 #583 from HyukjinKwon/SPARK-61591-native-ml.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/pyspark-rs/src/dataframe.rs | 2 +-
crates/pyspark-rs/src/ml.rs | 584 ++++++++++++++++++++++++++++++-------
docs/compatibility.md | 68 +++--
python/tests/test_ml_e2e.py | 150 +++++++++-
python/tests/test_ml_offline.py | 369 +++++++++++++++++++++--
5 files changed, 1012 insertions(+), 161 deletions(-)
diff --git a/crates/pyspark-rs/src/dataframe.rs
b/crates/pyspark-rs/src/dataframe.rs
index 8da79f26..8c8f0a97 100644
--- a/crates/pyspark-rs/src/dataframe.rs
+++ b/crates/pyspark-rs/src/dataframe.rs
@@ -104,7 +104,7 @@ impl PyDataFrame {
/// The pandas DataFrame of the result, as `SparkConnectClient.to_pandas`
makes it: the
/// settings of the conversion first, in one request; then the Arrow
result with the schema
/// that the server sends, which `pyspark.sql.connect.client._to_pandas`
converts.
- fn to_pandas(
+ pub(crate) fn to_pandas(
&self,
py: Python<'_>,
struct_handling_mode: Option<Bound<'_, PyAny>>,
diff --git a/crates/pyspark-rs/src/ml.rs b/crates/pyspark-rs/src/ml.rs
index 79b4ab55..50e076aa 100644
--- a/crates/pyspark-rs/src/ml.rs
+++ b/crates/pyspark-rs/src/ml.rs
@@ -7,17 +7,18 @@
//! `TypeConverters` of the param in PySpark, and send it as PySpark sends a
Python value. A
//! 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.
+//! 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`]).
-use pyo3::exceptions::PyTypeError;
+use pyo3::exceptions::{PyNotImplementedError, PyTypeError, PyValueError};
use pyo3::prelude::*;
use pyo3::pyclass::boolean_struct::False;
-use pyo3::types::{PyDict, PyTuple, PyType};
+use pyo3::types::{PyDict, PyList, PyTuple, PyType};
use pyo3::PyClass;
use spark_connect::ml::{
BinaryClassificationEvaluator, BisectingKMeans, CrossValidator,
DecisionTreeClassifier,
DecisionTreeRegressor, Estimator, Evaluator, GBTClassifier, GBTRegressor,
KMeans,
- LinearRegression, LinearSVC, LogisticRegression, MaxAbsScaler, Model,
+ LinearRegression, LinearSVC, LogisticRegression, MaxAbsScaler, MlOperator,
Model,
MulticlassClassificationEvaluator, NaiveBayes, Params, Pipeline,
RandomForestClassifier,
RandomForestRegressor, RegressionEvaluator, StandardScaler, StringIndexer,
Transformer,
VectorAssembler,
@@ -260,33 +261,162 @@ fn snapshot<T: Native + PyClass>(slf: &Bound<'_, T>) ->
PyResult<T::Core> {
Ok(this.inner().clone())
}
-/// The fit of a native estimator, on `df` as its JVM estimator reads it: an
array column that the
-/// JVM estimator reads as an ML vector is sent as that vector (see
[`Vectors`]).
-fn fit_native<T>(slf: &Bound<'_, T>, df: &PyDataFrame) -> PyResult<PyMLModel>
+/// 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
+ .py()
+ .import("sys")?
+ .getattr("modules")?
+ .get_item("pandas")
+ .ok();
+ match pandas {
+ Some(pandas) => dataset.is_instance(&pandas.getattr("DataFrame")?),
+ None => Ok(false),
+ }
+}
+
+/// 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>> {
+ 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()));
+ }
+ dataset.getattr(attribute)?;
+ Err(PyTypeError::new_err(format!(
+ "{method}() takes a DataFrame or a pandas DataFrame, not '{}'",
+ dataset.get_type().name()?
+ )))
+}
+
+/// The DataFrame of the pandas DataFrame `pdf`, of `createDataFrame` of the
active session.
+fn active_dataframe(pdf: &Bound<'_, PyAny>) -> PyResult<DataFrame> {
+ let df = pdf
+ .py()
+ .import("pyspark.sql")?
+ .getattr("SparkSession")?
+ .call_method0("active")?
+ .call_method1("createDataFrame", (pdf,))?;
+ 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,
+/// and a scaler's its `inputCol`, which has no default.
+type Reads = &'static [(&'static str, Option<&'static str>)];
+
+const LOGISTIC_REGRESSION_READS: Reads = &[
+ ("featuresCol", Some("features")),
+ ("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> {
+ match params.get_param(name) {
+ Some(_) => string_param(params, name),
+ None => default.map(str::to_string),
+ }
+}
+
+/// The names of the columns `reads` of `params` (see [`string_or`]), or None
when one of them has
+/// none.
+fn read_columns(params: &Params, reads: Reads) -> Option<Vec<String>> {
+ reads
+ .iter()
+ .map(|&(name, default)| string_or(params, name, default))
+ .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.
+fn fit_native<T>(
+ slf: &Bound<'_, T>,
+ dataset: &Bound<'_, PyAny>,
+ reads: Option<Reads>,
+) -> PyResult<PyMLModel>
where
T: Native + PyClass,
T::Core: Estimator,
{
let py = slf.py();
+ let dataset = dataset_of(dataset, "fit", "select")?;
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),
+ Dataset::Pandas(pdf) => {
+ let pdf = match &columns {
+ Some(columns) => pdf.get_item(PyList::new(py, columns)?)?,
+ None => pdf,
+ };
+ (active_dataframe(&pdf)?, None)
+ }
+ };
let vectors = Vectors::of(estimator.operator(), estimator.params());
- let dataset = match vectors.array_input(py, &df.dataframe, false)? {
- Some(field) => df.dataframe.with_column(&field.name,
vector_of(&field)),
- None => df.dataframe.clone(),
+ // 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.
+ let array = vectors.array_input(py, &df, false)?;
+ let df = match select {
+ Some(columns) => df.select(columns.iter().map(|name|
exact_column(name))),
+ None => df,
};
- fit_core(py, estimator, &dataset)
+ let df = match array {
+ Some(field) => df.with_column(&field.name, vector_of(&field)),
+ None => df,
+ };
+ fit_core(py, estimator, &df)
}
/// The fit of a native estimator whose core cannot fit it, as Pipeline and
CrossValidator.
-/// The core raises NOT_IMPLEMENTED before any request, whatever its params
are, so the params
-/// are not serialized first, and PySpark's serialization errors of them are
not raised.
-fn fit_unimplemented<T>(slf: &Bound<'_, T>, df: &PyDataFrame) ->
PyResult<PyMLModel>
+/// 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.
+fn fit_unimplemented<T>(
+ slf: &Bound<'_, T>,
+ dataset: &Bound<'_, PyAny>,
+ feature: &str,
+) -> PyResult<PyMLModel>
where
T: Native + PyClass,
T::Core: Estimator,
{
- let estimator = slf.try_borrow()?.inner().clone();
- fit_core(slf.py(), estimator, &df.dataframe)
+ let py = slf.py();
+ match dataset.extract::<PyRef<'_, PyDataFrame>>() {
+ Ok(df) => fit_core(py, slf.try_borrow()?.inner().clone(),
&df.dataframe),
+ Err(_) => Err(crate::column::raise_pyspark(
+ py,
+ "PySparkNotImplementedError",
+ "NOT_IMPLEMENTED",
+ &[("feature", feature)],
+ )),
+ }
}
fn fit_core<C: Estimator>(py: Python<'_>, mut estimator: C, df: &DataFrame) ->
PyResult<PyMLModel> {
@@ -302,8 +432,8 @@ fn fit_core<C: Estimator>(py: Python<'_>, mut estimator: C,
df: &DataFrame) -> P
/// as ML vectors, as their fit and transform send them, so that they take the
columns of PySpark's
/// `pyspark.ml.connect` classes, which compute with numpy and torch on
arrays: an array of numbers
/// of the `input` column is sent as a vector by `array_to_vector`, and a
vector as it is, while the
-/// `output` vector of a scaler is converted to an `array<double>` by
`vector_to_array`, as
-/// PySpark's scalers output (their `_output_columns`).
+/// `output` vector of a scaler is converted to the `array<double>` that
PySpark's scalers output
+/// (their `_output_columns`, see [`vector_array`]).
#[derive(Default)]
struct Vectors {
input: Option<String>,
@@ -462,6 +592,22 @@ fn vector_to_array(name: &str) -> spark_connect::Column {
))
}
+/// The `array<double>` of the ML vector column `name`, of the values of
`vector_to_array`, as a
+/// `pandas_udf` of PySpark's `transform_dataframe_column` outputs it: a
nullable column of
+/// nullable elements (`containsNull`), where `vector_to_array` is of neither.
Its elements are
+/// cast to nullable doubles, and it is the array where the vector is not
null, else null.
+fn vector_array(name: &str) -> spark_connect::Column {
+ use spark_connect::types::DataType;
+
+ spark_connect::column::when(
+ exact_column(name).is_not_null(),
+ vector_to_array(name).cast(DataType::Array {
+ element_type: Box::new(DataType::Double),
+ contains_null: true,
+ }),
+ )
+}
+
/// 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.
@@ -490,36 +636,14 @@ where
})
}
-/// The dataset of `evaluate`, as PySpark's evaluators take it: a DataFrame,
or a pandas DataFrame,
-/// which PySpark evaluates locally, and which is sent here with
`createDataFrame` of the active
-/// session, as the evaluators of this client run on the server. Another
object raises the
-/// `AttributeError` of the `select` that PySpark's `aggregate_dataframe`
calls on it.
+/// 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.
fn evaluation_dataset(dataset: &Bound<'_, PyAny>) -> PyResult<DataFrame> {
- let py = dataset.py();
- if let Ok(df) = dataset.extract::<PyRef<'_, PyDataFrame>>() {
- return Ok(df.dataframe.clone());
- }
- // A pandas DataFrame is of an imported pandas.
- let pandas = py
- .import("sys")?
- .getattr("modules")?
- .get_item("pandas")
- .ok();
- if let Some(pandas) = pandas {
- if dataset.is_instance(&pandas.getattr("DataFrame")?)? {
- let df = py
- .import("pyspark.sql")?
- .getattr("SparkSession")?
- .call_method0("active")?
- .call_method1("createDataFrame", (dataset,))?;
- return Ok(df.extract::<PyRef<'_,
PyDataFrame>>()?.dataframe.clone());
- }
+ match dataset_of(dataset, "evaluate", "select")? {
+ Dataset::Spark(df) => Ok(df),
+ Dataset::Pandas(pdf) => active_dataframe(&pdf),
}
- dataset.getattr("select")?;
- Err(PyTypeError::new_err(format!(
- "evaluate() takes a DataFrame or a pandas DataFrame, not '{}'",
- dataset.get_type().name()?
- )))
}
/// `df` as the JVM evaluator reads it, with its columns of `inputs`
converted: a prediction
@@ -554,6 +678,143 @@ 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.
+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`),
+ /// 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>,
+ },
+ /// MaxAbsScalerModel or StandardScalerModel: of its `inputCol`, and its
`array<double>`
+ /// `outputCol` (see [`Vectors`]).
+ Scaler {
+ input: Option<String>,
+ output: String,
+ },
+}
+
+impl PySparkModel {
+ fn of(operator: &MlOperator, params: &Params) -> Option<Self> {
+ match operator.name.as_str() {
+ "org.apache.spark.ml.classification.LogisticRegressionModel" => {
+ // An empty output column is not output, as by PySpark's `if
prob_col`.
+ let output = |name, default| {
+ 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"),
+ })
+ }
+ "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,
+ }
+ }
+
+ /// The column that PySpark's transform reads (`_input_columns`).
+ fn input(&self) -> Option<&str> {
+ match self {
+ Self::LogisticRegression { features, .. } => features.as_deref(),
+ Self::Scaler { input, .. } => input.as_deref(),
+ }
+ }
+
+ /// The columns that PySpark's transform appends, in their order
(`_output_columns`).
+ fn outputs(&self) -> Vec<String> {
+ match self {
+ Self::LogisticRegression {
+ prediction,
+ probability,
+ ..
+ } => prediction.iter().chain(probability).cloned().collect(),
+ Self::Scaler { output, .. } => vec![output.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<()> {
+ let existing = dataset
+ .py()
+ .get_type::<PyList>()
+ .call1((dataset.getattr("columns")?,))?;
+ for output in self.outputs() {
+ if existing.contains(output)? {
+ return Err(PyValueError::new_err(
+ "Transformers does not allow output column having the same
name with \
+ existing columns.",
+ ));
+ }
+ }
+ Ok(())
+ }
+}
+
+/// 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(),
+ };
+ 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 {
@@ -564,24 +825,66 @@ pub struct PyMLModel {
#[pymethods]
impl PyMLModel {
- /// Apply the model to a DataFrame. As PySpark's models of
`pyspark.ml.connect`, it takes an
- /// array of numbers where the JVM model reads a vector, and keeps that
column as it is in its
- /// output, and a scaler outputs an `array<double>` (see [`Vectors`]).
- fn transform(&self, py: Python<'_>, df: &PyDataFrame) ->
PyResult<PyDataFrame> {
+ /// 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());
+ let input = dataset_of(dataset, "transform", "columns")?;
+ 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(),
+ })
+ }
+}
+
+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.
+ fn transform_dataframe(
+ &self,
+ py: Python<'_>,
+ df: &DataFrame,
+ pyspark: Option<&PySparkModel>,
+ ) -> PyResult<DataFrame> {
+ use spark_connect::types::DataType;
+
let mut model = self.model.clone_box();
- let session = df.dataframe.spark_session();
+ let session = df.spark_session();
let vectors = Vectors::of(model.operator(), model.params());
+ // The JVM model appends its probability vector before its prediction:
it is output in a
+ // column of its own, whose array is appended after the prediction, as
PySpark's is.
+ let probability = match pyspark {
+ Some(PySparkModel::LogisticRegression {
+ probability: Some(probability),
+ ..
+ }) => {
+ let vector = format!("{}__probability", model.operator().uid);
+ let params = std::mem::take(model.params_mut());
+ *model.params_mut() =
params.set_param_string("probabilityCol", &vector);
+ Some((probability.clone(), vector))
+ }
+ _ => None,
+ };
// An array input is sent as its vector, which the JVM model reads,
and kept as it is in a
// column of its own, which takes its place again in the output.
let array = vectors
- .array_input(py, &df.dataframe, true)?
+ .array_input(py, df, true)?
.map(|field| (format!("{}__input", model.operator().uid), field));
let input = match &array {
- Some((kept, field)) => df.dataframe.with_columns(vec![
+ Some((kept, field)) => df.with_columns(vec![
(kept.clone(), exact_column(&field.name)),
(field.name.clone(), vector_of(field)),
]),
- None => df.dataframe.clone(),
+ None => df.clone(),
};
let out = if session.session_id() != self.session_id {
// As PySpark, the transform of a DataFrame of another session
refers to the model
@@ -604,22 +907,41 @@ impl PyMLModel {
.to_pyerr()?
};
// The JVM model appends its output columns, and keeps the columns of
its input, in place.
+ // The columns that take the place of others keep it, and the others
are appended in
+ // their order, as by PySpark's `withColumns` of its outputs.
let mut columns = Vec::new();
+ let mut dropped = Vec::new();
if let Some((kept, field)) = &array {
columns.push((field.name.clone(), exact_column(kept)));
+ dropped.push(kept.as_str());
}
if let Some(output) = &vectors.output {
- columns.push((output.clone(), vector_to_array(output)));
+ columns.push((output.clone(), vector_array(output)));
+ }
+ if let Some(PySparkModel::LogisticRegression {
+ prediction: Some(prediction),
+ ..
+ }) = pyspark
+ {
+ columns.push((
+ prediction.clone(),
+ exact_column(prediction).cast(DataType::Long),
+ ));
+ }
+ if let Some((probability, vector)) = &probability {
+ columns.push((probability.clone(), vector_array(vector)));
+ dropped.push(vector.as_str());
}
let out = if columns.is_empty() {
out
} else {
out.with_columns(columns)
};
- Ok(PyDataFrame::new(match &array {
- Some((kept, _)) => out.drop(vec![kept.as_str()]),
- None => out,
- }))
+ Ok(if dropped.is_empty() {
+ out
+ } else {
+ out.drop(dropped)
+ })
}
}
@@ -668,8 +990,8 @@ impl PyStandardScaler {
) -> PyResult<Bound<'py, Self>> {
set_param(slf, "outputCol", Kind::Str, value)
}
- fn fit(slf: &Bound<'_, Self>, df: &PyDataFrame) -> PyResult<PyMLModel> {
- fit_native(slf, df)
+ fn fit(slf: &Bound<'_, Self>, dataset: &Bound<'_, PyAny>) ->
PyResult<PyMLModel> {
+ fit_native(slf, dataset, Some(SCALER_READS))
}
}
@@ -706,8 +1028,8 @@ impl PyMaxAbsScaler {
) -> PyResult<Bound<'py, Self>> {
set_param(slf, "outputCol", Kind::Str, value)
}
- fn fit(slf: &Bound<'_, Self>, df: &PyDataFrame) -> PyResult<PyMLModel> {
- fit_native(slf, df)
+ fn fit(slf: &Bound<'_, Self>, dataset: &Bound<'_, PyAny>) ->
PyResult<PyMLModel> {
+ fit_native(slf, dataset, Some(SCALER_READS))
}
}
@@ -744,8 +1066,8 @@ impl PyStringIndexer {
) -> PyResult<Bound<'py, Self>> {
set_param(slf, "outputCol", Kind::Str, value)
}
- fn fit(slf: &Bound<'_, Self>, df: &PyDataFrame) -> PyResult<PyMLModel> {
- fit_native(slf, df)
+ fn fit(slf: &Bound<'_, Self>, dataset: &Bound<'_, PyAny>) ->
PyResult<PyMLModel> {
+ fit_native(slf, dataset, None)
}
}
@@ -783,13 +1105,22 @@ impl PyVectorAssembler {
) -> PyResult<Bound<'py, Self>> {
set_param(slf, "outputCol", Kind::Str, value)
}
- fn transform(slf: &Bound<'_, Self>, df: &PyDataFrame) ->
PyResult<PyDataFrame> {
+ /// 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>> {
+ let py = slf.py();
+ let input = dataset_of(dataset, "transform", "columns")?;
let mut transformer = snapshot(slf)?;
- let out = slf
- .py()
- .detach(|| transformer.transform(&df.dataframe).map_err(Box::new))
- .to_pyerr()?;
- Ok(PyDataFrame::new(out))
+ 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()
+ }
+ })
}
}
@@ -803,25 +1134,43 @@ pub struct PyLogisticRegression {
unsendable: Vec<&'static str>,
}
+/// The params of LogisticRegression, in the order of PySpark's constructor,
which also takes the
+/// params of its PyTorch training, `numTrainWorkers`, `batchSize`,
`learningRate`, `momentum` and
+/// `seed`. The L-BFGS of the JVM estimator has none of them, so the
constructor raises the TypeError
+/// of an unexpected keyword argument for them, rather than take a value that
no fit would use.
+const LOGISTIC_REGRESSION_PARAMS: &[(&str, Kind)] = &[
+ ("featuresCol", Kind::Str),
+ ("labelCol", Kind::Str),
+ ("predictionCol", Kind::Str),
+ ("probabilityCol", Kind::Str),
+ ("maxIter", Kind::Int),
+ ("tol", Kind::Float),
+];
+
#[pymethods]
impl PyLogisticRegression {
#[new]
#[pyo3(
signature = (*args, **kwargs),
- text_signature = "(*, featuresCol=None, labelCol=None,
predictionCol=None, maxIter=None)"
+ text_signature = "(*, featuresCol='features', labelCol='label',
predictionCol='prediction', probabilityCol='probability', maxIter=100,
tol=1e-06)"
)]
fn new(args: &Bound<'_, PyTuple>, kwargs: Option<&Bound<'_, PyDict>>) ->
PyResult<Self> {
let mut this = Self {
inner: LogisticRegression::new(),
unsendable: Vec::new(),
};
- let params = &[
- ("featuresCol", Kind::Str),
- ("labelCol", Kind::Str),
- ("predictionCol", Kind::Str),
- ("maxIter", Kind::Int),
- ];
- init_params(&mut this, "LogisticRegression", &[], params, args,
kwargs)?;
+ // As PySpark's, whose model outputs no raw prediction: the JVM model
outputs none of an
+ // empty rawPredictionCol, a param that PySpark's LogisticRegression
does not have, so that
+ // a dataset with a `rawPrediction` column is fitted and transformed,
as with PySpark.
+ apply(&mut this, "rawPredictionCol", Converted::Str(String::new()));
+ init_params(
+ &mut this,
+ "LogisticRegression",
+ &[],
+ LOGISTIC_REGRESSION_PARAMS,
+ args,
+ kwargs,
+ )?;
Ok(this)
}
#[pyo3(name = "setFeaturesCol")]
@@ -845,6 +1194,13 @@ impl PyLogisticRegression {
) -> PyResult<Bound<'py, Self>> {
set_param(slf, "predictionCol", Kind::Str, value)
}
+ #[pyo3(name = "setProbabilityCol")]
+ fn set_probability_col<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "probabilityCol", Kind::Str, value)
+ }
#[pyo3(name = "setMaxIter")]
fn set_max_iter<'py>(
slf: Bound<'py, Self>,
@@ -852,8 +1208,22 @@ impl PyLogisticRegression {
) -> PyResult<Bound<'py, Self>> {
set_param(slf, "maxIter", Kind::Int, value)
}
- fn fit(slf: &Bound<'_, Self>, df: &PyDataFrame) -> PyResult<PyMLModel> {
- fit_native(slf, df)
+ #[pyo3(name = "setTol")]
+ fn set_tol<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ 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.
+ 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(slf, dataset, Some(LOGISTIC_REGRESSION_READS))
}
}
@@ -997,8 +1367,8 @@ impl PyLinearSVC {
set_param(slf, "maxBlockSizeInMB", Kind::Float, value)
}
- fn fit(slf: &Bound<'_, Self>, df: &PyDataFrame) -> PyResult<PyMLModel> {
- fit_native(slf, df)
+ fn fit(slf: &Bound<'_, Self>, dataset: &Bound<'_, PyAny>) ->
PyResult<PyMLModel> {
+ fit_native(slf, dataset, None)
}
}
@@ -1167,8 +1537,8 @@ impl PyLinearRegression {
set_param(slf, "maxBlockSizeInMB", Kind::Float, value)
}
- fn fit(slf: &Bound<'_, Self>, df: &PyDataFrame) -> PyResult<PyMLModel> {
- fit_native(slf, df)
+ fn fit(slf: &Bound<'_, Self>, dataset: &Bound<'_, PyAny>) ->
PyResult<PyMLModel> {
+ fit_native(slf, dataset, None)
}
}
@@ -1375,8 +1745,8 @@ impl PyDecisionTreeClassifier {
set_param(slf, "thresholds", Kind::FloatList, value)
}
- fn fit(slf: &Bound<'_, Self>, df: &PyDataFrame) -> PyResult<PyMLModel> {
- fit_native(slf, df)
+ fn fit(slf: &Bound<'_, Self>, dataset: &Bound<'_, PyAny>) ->
PyResult<PyMLModel> {
+ fit_native(slf, dataset, None)
}
}
@@ -1491,8 +1861,8 @@ impl PyNaiveBayes {
set_param(slf, "weightCol", Kind::Str, value)
}
- fn fit(slf: &Bound<'_, Self>, df: &PyDataFrame) -> PyResult<PyMLModel> {
- fit_native(slf, df)
+ fn fit(slf: &Bound<'_, Self>, dataset: &Bound<'_, PyAny>) ->
PyResult<PyMLModel> {
+ fit_native(slf, dataset, None)
}
}
@@ -1740,8 +2110,8 @@ impl PyGBTClassifier {
set_param(slf, "validationIndicatorCol", Kind::Str, value)
}
- fn fit(slf: &Bound<'_, Self>, df: &PyDataFrame) -> PyResult<PyMLModel> {
- fit_native(slf, df)
+ fn fit(slf: &Bound<'_, Self>, dataset: &Bound<'_, PyAny>) ->
PyResult<PyMLModel> {
+ fit_native(slf, dataset, None)
}
}
@@ -1984,8 +2354,8 @@ impl PyRandomForestClassifier {
set_param(slf, "thresholds", Kind::FloatList, value)
}
- fn fit(slf: &Bound<'_, Self>, df: &PyDataFrame) -> PyResult<PyMLModel> {
- fit_native(slf, df)
+ fn fit(slf: &Bound<'_, Self>, dataset: &Bound<'_, PyAny>) ->
PyResult<PyMLModel> {
+ fit_native(slf, dataset, None)
}
}
@@ -2209,8 +2579,8 @@ impl PyGBTRegressor {
set_param(slf, "validationIndicatorCol", Kind::Str, value)
}
- fn fit(slf: &Bound<'_, Self>, df: &PyDataFrame) -> PyResult<PyMLModel> {
- fit_native(slf, df)
+ fn fit(slf: &Bound<'_, Self>, dataset: &Bound<'_, PyAny>) ->
PyResult<PyMLModel> {
+ fit_native(slf, dataset, None)
}
}
@@ -2391,8 +2761,8 @@ impl PyDecisionTreeRegressor {
set_param(slf, "varianceCol", Kind::Str, value)
}
- fn fit(slf: &Bound<'_, Self>, df: &PyDataFrame) -> PyResult<PyMLModel> {
- fit_native(slf, df)
+ fn fit(slf: &Bound<'_, Self>, dataset: &Bound<'_, PyAny>) ->
PyResult<PyMLModel> {
+ fit_native(slf, dataset, None)
}
}
/// Random forest regressor fitted and cached by Spark Connect.
@@ -2599,8 +2969,8 @@ impl PyRandomForestRegressor {
set_param(slf, "bootstrap", Kind::Bool, value)
}
- fn fit(slf: &Bound<'_, Self>, df: &PyDataFrame) -> PyResult<PyMLModel> {
- fit_native(slf, df)
+ fn fit(slf: &Bound<'_, Self>, dataset: &Bound<'_, PyAny>) ->
PyResult<PyMLModel> {
+ fit_native(slf, dataset, None)
}
}
@@ -2732,8 +3102,8 @@ impl PyKMeans {
set_param(slf, "maxBlockSizeInMB", Kind::Float, value)
}
- fn fit(slf: &Bound<'_, Self>, df: &PyDataFrame) -> PyResult<PyMLModel> {
- fit_native(slf, df)
+ fn fit(slf: &Bound<'_, Self>, dataset: &Bound<'_, PyAny>) ->
PyResult<PyMLModel> {
+ fit_native(slf, dataset, None)
}
}
@@ -2998,8 +3368,8 @@ impl PyBisectingKMeans {
set_param(slf, "minDivisibleClusterSize", Kind::Float, value)
}
- fn fit(slf: &Bound<'_, Self>, df: &PyDataFrame) -> PyResult<PyMLModel> {
- fit_native(slf, df)
+ fn fit(slf: &Bound<'_, Self>, dataset: &Bound<'_, PyAny>) ->
PyResult<PyMLModel> {
+ fit_native(slf, dataset, None)
}
}
@@ -3030,8 +3400,8 @@ impl PyPipeline {
) -> PyResult<Bound<'py, Self>> {
set_param(slf, "stages", Kind::StrList, value)
}
- fn fit(slf: &Bound<'_, Self>, df: &PyDataFrame) -> PyResult<PyMLModel> {
- fit_unimplemented(slf, df)
+ fn fit(slf: &Bound<'_, Self>, dataset: &Bound<'_, PyAny>) ->
PyResult<PyMLModel> {
+ fit_unimplemented(slf, dataset, "Pipeline.fit")
}
}
@@ -3161,8 +3531,8 @@ impl PyCrossValidator {
) -> PyResult<Bound<'py, Self>> {
set_param(slf, "seed", Kind::Int, value)
}
- fn fit(slf: &Bound<'_, Self>, df: &PyDataFrame) -> PyResult<PyMLModel> {
- fit_unimplemented(slf, df)
+ fn fit(slf: &Bound<'_, Self>, dataset: &Bound<'_, PyAny>) ->
PyResult<PyMLModel> {
+ fit_unimplemented(slf, dataset, "CrossValidator.fit")
}
}
diff --git a/docs/compatibility.md b/docs/compatibility.md
index bd6a8910..d6732368 100644
--- a/docs/compatibility.md
+++ b/docs/compatibility.md
@@ -169,9 +169,19 @@ The native `spark_connect::ml::LogisticRegression` fits
Spark's JVM
protocol. In the Rust API, training features must be ML vectors; convert an
array column
with `array_to_vector` before fitting. The Python class takes an array column
of numbers too,
as the deprecated `pyspark.ml.connect.classification.LogisticRegression` of
PySpark does (see
-below), but fits the JVM estimator, where PySpark's trains with PyTorch: its
model outputs the
-JVM's `rawPrediction` and `probability` vectors and a double `prediction`,
where PySpark's
-outputs a `bigint` prediction and an `array<double>` probability.
+below), but fits the JVM estimator, where PySpark's trains with PyTorch. Its
constructor takes
+the params of PySpark's that the JVM estimator honors, `featuresCol`,
`labelCol`,
+`predictionCol`, `probabilityCol`, `maxIter` and `tol`, whose defaults are
PySpark's, and it has
+their setters. The params of PySpark's PyTorch training, `numTrainWorkers`,
`batchSize`,
+`learningRate`, `momentum` and `seed`, have no counterpart in the L-BFGS of
the JVM estimator,
+and raise the `TypeError` of an unexpected keyword argument. Its model outputs
the columns of
+PySpark's: a `bigint` prediction, and then the `array<double>` of the
probabilities unless
+`probabilityCol` is empty, and no raw prediction: the constructor sends an
empty
+`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`.
Fitting returns a server-cached model. Prediction uses that model's object
reference and must use the same Spark session. Models are obtained through
@@ -193,23 +203,9 @@ 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. The evaluators take a
DataFrame or a pandas
-DataFrame, as PySpark's do, and run on the server: a pandas DataFrame is sent
through
-`createDataFrame` of the active session. A prediction or a probability of
another numeric type
-is cast to a double, and an array of probabilities is sent as a vector
(`array_to_vector`),
-whose element 1 is scored, as PySpark's evaluator reads the column 1 of an
array. The values
-are the JVM evaluators' doubles, where PySpark's are of float32 tensors (`0.6`
where PySpark
-returns `0.6000000238418579`). The native scalers, and the native estimators
of a
-`featuresCol`, take the array columns of numbers that PySpark's take, as well
as ML vectors: a
-fit, and the transform of its model, read the schema of the DataFrame, as
PySpark's transform
-reads its columns, and send an array `inputCol` of a scaler, or `featuresCol`
of another
-estimator, as the vector (`array_to_vector`) that the JVM reads; the transform
outputs the
-array column as it was. The models of `StandardScaler` and `MaxAbsScaler`
output an
-`array<double>` (`vector_to_array`), as PySpark's do, also of a vector input,
which PySpark's
-scalers do not take. The scaled values are the JVM's doubles, also of an array
of floats
-(`0.3333333333333333` where PySpark's float32 give `0.3333333432674408`).
-`StandardScaler` scales to `(x - mean) / std`, as PySpark's does: its
constructor sends the
-`withMean` of Spark's scaler, which is false by default and which PySpark's
scaler does not have.
+`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.
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
@@ -221,6 +217,38 @@ 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
+`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
+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.
+
## Native RandomForestRegressor
`spark_connect::ml::RandomForestRegressor` fits Spark's JVM random forest
regressor
diff --git a/python/tests/test_ml_e2e.py b/python/tests/test_ml_e2e.py
index 8d3338ac..c90bdd1d 100644
--- a/python/tests/test_ml_e2e.py
+++ b/python/tests/test_ml_e2e.py
@@ -536,32 +536,164 @@ def
test_ml_connect_scalers_and_estimators_take_the_array_columns_of_pyspark(ses
[0.3779644730092272, 1.1208970766356101], rel=1e-12)
# LogisticRegression is Spark's JVM estimator here, without the torch
params of PySpark's
- # (learningRate), and the labels are ints, as in PySpark's example.
+ # (learningRate), and the labels are ints, as in PySpark's example, whose
columns its model
+ # outputs: a bigint prediction, and then the array<double> of the
probabilities.
labeled = session.createDataFrame(
[([1.0, 2.0], 1), ([2.0, -1.0], 1), ([-3.0, -2.0], 0), ([-1.0, -2.0],
0)],
schema=["features", "label"],
)
model = LogisticRegression(maxIter=20).fit(labeled)
transformed = model.transform(labeled)
- assert transformed.columns[:2] == ["features", "label"]
- assert transformed.schema["features"].dataType.simpleString() ==
"array<double>"
- assert [(row.features, row.prediction) for row in transformed.collect()]
== [
- ([1.0, 2.0], 1.0),
- ([2.0, -1.0], 1.0),
- ([-3.0, -2.0], 0.0),
- ([-1.0, -2.0], 0.0),
+ assert transformed.schema.simpleString() == (
+
"struct<features:array<double>,label:bigint,prediction:bigint,probability:array<double>>"
+ )
+ rows = transformed.collect()
+ assert [(row.features, row.prediction) for row in rows] == [
+ ([1.0, 2.0], 1),
+ ([2.0, -1.0], 1),
+ ([-3.0, -2.0], 0),
+ ([-1.0, -2.0], 0),
]
+ assert all(type(row.prediction) is int for row in rows)
+ for row in rows:
+ assert sum(row.probability) == pytest.approx(1.0)
+ assert row.probability.index(max(row.probability)) == row.prediction
# The array<double> of a scaler is the input of the next estimator, as in
PySpark.
scaler = MaxAbsScaler(inputCol="features", outputCol="scaled")
scaled = scaler.fit(labeled).transform(labeled)
model = LogisticRegression(featuresCol="scaled", maxIter=20).fit(scaled)
- assert [row.prediction for row in model.transform(scaled).collect()] ==
[1.0, 1.0, 0.0, 0.0]
+ assert [row.prediction for row in model.transform(scaled).collect()] ==
[1, 1, 0, 0]
clusters = KMeans(featuresCol="scaled", k=2,
seed=1).fit(scaled).transform(scaled)
assert clusters.schema["scaled"].dataType.simpleString() == "array<double>"
assert len({row.prediction for row in clusters.collect()}) == 2
+def
test_ml_connect_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
+ # of nullable elements, with no metadata, a probability only of a
probabilityCol, and no raw
+ # prediction. As PySpark's, a transform raises its ValueError of an output
column that the
+ # DataFrame has, of its exact name, while a fit reads only its input
columns, so that the
+ # output columns of another transform (a rawPrediction, say) are there.
+ from pyspark.ml.connect.classification import LogisticRegression
+ from pyspark.ml.connect.feature import MaxAbsScaler, StandardScaler
+ from pyspark.sql import functions as F
+
+ def field(name, data_type):
+ return {"metadata": {}, "name": name, "nullable": True, "type":
data_type}
+
+ doubles = {"containsNull": True, "elementType": "double", "type": "array"}
+ inputs = [field("features", doubles), field("label", "long")]
+ labeled = session.createDataFrame(
+ [([1.0, 2.0], 1), ([2.0, -1.0], 1), ([-3.0, -2.0], 0), ([-1.0, -2.0],
0)],
+ schema=["features", "label"],
+ )
+ for estimator, outputs in [
+ (LogisticRegression(maxIter=5), [field("prediction", "long"),
field("probability", doubles)]),
+ (LogisticRegression(maxIter=5, predictionCol="p", probabilityCol="q"),
+ [field("p", "long"), field("q", doubles)]),
+ (LogisticRegression(maxIter=5, probabilityCol=""),
[field("prediction", "long")]),
+ (MaxAbsScaler(inputCol="features", outputCol="scaled"),
[field("scaled", doubles)]),
+ (StandardScaler(inputCol="features", outputCol="scaled"),
[field("scaled", doubles)]),
+ ]:
+ transformed = estimator.fit(labeled).transform(labeled)
+ assert transformed.schema.jsonValue() == {"fields": inputs + outputs,
"type": "struct"}
+ assert len(transformed.collect()) == 4
+
+ message = "Transformers does not allow output column having the same name
with existing columns."
+ model = LogisticRegression(maxIter=5).fit(labeled)
+ for column in ("prediction", "probability"):
+ with pytest.raises(ValueError) as error:
+ model.transform(labeled.withColumn(column, F.lit(0)))
+ assert str(error.value) == message
+ scaler = MaxAbsScaler(inputCol="features", outputCol="scaled").fit(labeled)
+ with pytest.raises(ValueError) as error:
+ scaler.transform(labeled.withColumn("scaled", F.lit(0)))
+ assert str(error.value) == message
+ # Not of the exact name: Spark replaces the column of the other case, as
with PySpark.
+ assert scaler.transform(labeled.withColumnRenamed("label",
"Scaled")).columns == [
+ "features", "scaled"
+ ]
+
+ for column in ("rawPrediction", "probability", "prediction"):
+ extra = labeled.withColumn(column, F.lit(0))
+ if column == "rawPrediction":
+ assert model.transform(extra).columns == [
+ "features", "label", "rawPrediction", "prediction",
"probability"
+ ]
+ fitted = LogisticRegression(maxIter=5).fit(extra)
+ assert [row.prediction for row in fitted.transform(labeled).collect()]
== [1, 1, 0, 0]
+ fitted = MaxAbsScaler(inputCol="features", outputCol="scaled").fit(
+ labeled.withColumn("scaled", F.lit(0)))
+ 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), of the
+ # values of the JVM. 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
+ 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
+
+ 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])
+
+ def appended(transformed, columns):
+ # The output columns of the transform of pdf, which is a shallow copy
of it.
+ assert transformed is not pdf and list(pdf.columns) == ["features",
"label"]
+ assert list(transformed.columns) == ["features", "label"] + columns
+ assert list(transformed.index) == [10, 20, 30]
+ assert transformed["features"].tolist() == features
+ assert np.shares_memory(transformed["label"].to_numpy(),
pdf["label"].to_numpy())
+ return transformed[columns]
+
+ scaled = appended(MaxAbsScaler(inputCol="features",
outputCol="o").fit(pdf).transform(pdf), ["o"])
+ assert scaled.dtypes.astype(str).tolist() == ["object"]
+ assert [type(value) for value in scaled["o"]] == [np.ndarray] * 3
+ assert [value.tolist() for value in scaled["o"]] == [
+ [1 / 3, 1.0], [2 / 3, -0.5], [-1.0, -1.0]
+ ]
+ # The output column of PySpark's default, <uid>__output.
+ transformed = StandardScaler(inputCol="features").fit(pdf).transform(pdf)
+ output = transformed.columns[-1]
+ assert output.startswith("StandardScaler_") and output.endswith("__output")
+ # The first row of PySpark 4.3.0's StandardScaler of pdf.
+ 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_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 4b4d04ee..b738fe4c 100644
--- a/python/tests/test_ml_offline.py
+++ b/python/tests/test_ml_offline.py
@@ -100,6 +100,22 @@ def _operator_info(ref_id):
)
+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.
+ import pyarrow as pa
+
+ sink = pa.BufferOutputStream()
+ with pa.ipc.new_stream(sink, table.schema) as writer:
+ writer.write_table(table)
+ batch = pb2.ExecutePlanResponse.ArrowBatch(
+ row_count=table.num_rows, data=sink.getvalue().to_pybytes()
+ )
+ return pb2.ExecutePlanResponse(
+ schema=_data_type_proto(schema), arrow_batch=batch
+ ).SerializeToString()
+
+
def _commands(service):
# The commands of the ExecutePlanRequests that the mock server received.
return [pb2.ExecutePlanRequest.FromString(r).plan.command for r in
service.execute_requests]
@@ -187,14 +203,19 @@ def
test_ml_connect_fitted_scalers_transform_the_cached_model(ml_mock):
"outputCol": pb2.Expression.Literal(string="o"),
**({"withMean": pb2.Expression.Literal(boolean=True)} if cls is
StandardScaler else {}),
}
- assert fit.dataset == _relation(df)
+ 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_to_array("o"))]
+ 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")
@@ -224,6 +245,23 @@ def _vector_to_array(name):
)
+def _vector_array(name):
+ # The text of PySpark's when(col("`name`").isNotNull(),
+ # vector_to_array(col("`name`")).cast(ArrayType(DoubleType()))): the
array<double> of the
+ # vector, nullable and of nullable elements, as the pandas_udf of
PySpark's transform outputs.
+ return (
+ 'unresolved_function { function_name: "when" arguments {
unresolved_function { '
+ f'function_name: "isNotNull" arguments {{ {_attribute(name)} }} }} }}
arguments {{ cast {{ '
+ f"expr {{ {_vector_to_array(name)} }} type {{ array {{ element_type {{
double {{ }} }} "
+ "contains_null: true } } } } }"
+ )
+
+
+def _bigint(name):
+ # The text of PySpark's col("`name`").cast(LongType()).
+ return f"cast {{ expr {{ {_attribute(name)} }} type {{ long {{ }} }} }}"
+
+
def _aliases(with_columns):
# The names and the expressions of the columns of a WithColumns relation.
return [(list(alias.name), _text(alias.expr)) for alias in
with_columns.aliases]
@@ -236,8 +274,10 @@ def
test_ml_connect_native_estimators_take_the_array_columns_of_pyspark(ml_mock)
# send an array of numbers as PySpark's array_to_vector of it, the vector
that the JVM reads.
# The transform keeps the array in a column of its own, which takes its
place again in the
# output, as PySpark's transform keeps its input columns, and the vector
that a scaler outputs
- # is PySpark's vector_to_array of it, an array<double>. A vector, another
type and the column
- # of StringIndexer, which reads no vector, are sent as they are.
+ # 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.
import pyspark.ml.connect as connect
from _mock_connect_server import ddl_data_type
from pyspark.ml.linalg import VectorUDT
@@ -246,6 +286,14 @@ def
test_ml_connect_native_estimators_take_the_array_columns_of_pyspark(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.
+ if columns is None:
+ return relation == _relation(df)
+ return relation.project.input == _relation(df) and [
+ _text(expression) for expression in relation.project.expressions
+ ] == [_attribute(column) for column in columns]
+
def requests(estimator, reads=1):
# The Fit of estimator, and the relation of the transform of its
model, of a new
# DataFrame, whose schema the mock server answers.
@@ -269,21 +317,26 @@ def
test_ml_connect_native_estimators_take_the_array_columns_of_pyspark(ml_mock)
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"],
+ }
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.
+ # 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 {}
- sent = {k: v.string for k, v in fit.params.params.items() if k !=
"withMean"}
+ sent = {k: v.string for k, v in fit.params.params.items() if k not in
_defaults_sent(name)}
assert sent == params, name
- assert ("withMean" in fit.params.params) == (name ==
"StandardScaler"), name
- assert fit.dataset.with_columns.input == _relation(df), 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) == [
(["Features"], _array_to_vector("Features"))
], name
- (kept,) = transformed.drop.column_names
+ kept = transformed.drop.column_names[0]
output = transformed.drop.input.with_columns
transform = output.input.ml_relation.transform
assert transform.obj_ref == pb2.ObjectRef(id="model-1"), name
@@ -292,8 +345,18 @@ def
test_ml_connect_native_estimators_take_the_array_columns_of_pyspark(ml_mock)
([kept], _attribute("Features")),
(["Features"], _array_to_vector("Features")),
], name
- scaled = [(["o"], _vector_to_array("o"))] if type(estimator) in
scalers else []
- assert _aliases(output) == [(["Features"], _attribute(kept))] +
scaled, name
+ vectors = []
+ outputs = [(["o"], _vector_array("o"))] if type(estimator) in scalers
else []
+ 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).
+ vectors = [f"{fit.estimator.uid}__probability"]
+ outputs = [
+ (["prediction"], _bigint("prediction")),
+ (["probability"], _vector_array(vectors[0])),
+ ]
+ 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"))
@@ -304,13 +367,15 @@ def
test_ml_connect_native_estimators_take_the_array_columns_of_pyspark(ml_mock)
vector = f'unresolved_function {{ function_name: "array_to_vector"
arguments {{ {cast} }} }}'
assert _aliases(fit.dataset.with_columns) == [(["d"], vector)]
- for estimator, reads in [
- (connect.LogisticRegression(featuresCol="s"), 1),
- (connect.KMeans(featuresCol="words"), 1),
- (connect.StringIndexer(inputCol="features", outputCol="o"), 0),
+ for estimator, columns, analyzed in [
+ (connect.LogisticRegression(featuresCol="s"), ["s", "label"], 1),
+ (connect.KMeans(featuresCol="words"), None, 1),
+ (connect.StringIndexer(inputCol="features", outputCol="o"), None, 0),
]:
- df, fit, transformed = requests(estimator, reads)
- assert fit.dataset == _relation(df), estimator
+ df, fit, transformed = requests(estimator, analyzed)
+ assert selected(fit.dataset, df, columns), estimator
+ if columns:
+ transformed = transformed.drop.input.with_columns.input
assert transformed.ml_relation.transform.input == _relation(df),
estimator
service.data_type = _data_type_proto(
@@ -318,13 +383,259 @@ def
test_ml_connect_native_estimators_take_the_array_columns_of_pyspark(ml_mock)
).SerializeToString()
for estimator in [connect.MaxAbsScaler(inputCol="features",
outputCol="o"), connect.KMeans()]:
df, fit, transformed = requests(estimator)
- assert fit.dataset == _relation(df), estimator
- if type(estimator) in scalers:
- assert _aliases(transformed.with_columns) == [(["o"],
_vector_to_array("o"))]
+ 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
+def
test_ml_connect_logistic_regression_outputs_the_columns_of_pyspark(ml_mock):
+ # As PySpark's LogisticRegression of pyspark.ml.connect, of the signature
of its constructor
+ # but the params of its PyTorch training, which the JVM estimator has no
counterpart of. Its
+ # fit sends the select of the features and the labels, which PySpark's fit
reads, and an empty
+ # rawPredictionCol, so that the JVM model outputs no raw prediction, as
PySpark's. Its model
+ # outputs PySpark's _output_columns: the prediction cast to a bigint, and
then the probability,
+ # the array<double> of the vector that the JVM model outputs in a column
of its own, unless
+ # probabilityCol is empty.
+ import inspect
+
+ from pyspark.ml.connect import LogisticRegression
+
+ spark, service = ml_mock
+ assert str(inspect.signature(LogisticRegression)) == (
+ "(*, featuresCol='features', labelCol='label',
predictionCol='prediction', "
+ "probabilityCol='probability', maxIter=100, tol=1e-06)"
+ )
+ for param in ("numTrainWorkers", "batchSize", "learningRate", "momentum",
"seed"):
+ with pytest.raises(TypeError) as error:
+ LogisticRegression(**{param: 1})
+ assert str(error.value) == (
+ f"LogisticRegression.__init__() got an unexpected keyword argument
'{param}'"
+ )
+ assert not hasattr(LogisticRegression, "set" + param[0].upper() +
param[1:])
+
+ df = spark.range(1)
+ models = [] # Kept alive, so that no model is released during the checks.
+ for estimator, columns, outputs in [
+ (LogisticRegression(), ["features", "label"], ["prediction",
"probability"]),
+ (
+ LogisticRegression(labelCol="y",
predictionCol="p").setFeaturesCol("f")
+ .setProbabilityCol("q").setTol(0.5),
+ ["f", "y"],
+ ["p", "q"],
+ ),
+ (LogisticRegression(probabilityCol=""), ["features", "label"],
["prediction"]),
+ ]:
+ sent = len(service.execute_requests)
+ service.execute_payload = _operator_info("model-1")
+ models.append(estimator.fit(df))
+ fit = _commands_but_deletes(service, sent)[0].ml_command.fit
+ assert fit.params.params["rawPredictionCol"] ==
pb2.Expression.Literal(string="")
+ assert fit.dataset.project.input == _relation(df)
+ assert [_text(e) for e in fit.dataset.project.expressions] == [
+ _attribute(column) for column in columns
+ ]
+
+ relation = _relation(models[-1].transform(df))
+ prediction = outputs[0]
+ if len(outputs) == 2:
+ vector = f"{fit.estimator.uid}__probability"
+ assert list(relation.drop.column_names) == [vector]
+ relation = relation.drop.input
+ assert _aliases(relation.with_columns) == [
+ ([prediction], _bigint(prediction)),
+ ([outputs[1]], _vector_array(vector)),
+ ]
+ else:
+ vector = ""
+ assert _aliases(relation.with_columns) == [([prediction],
_bigint(prediction))]
+ transform = relation.with_columns.input.ml_relation.transform
+ assert transform.input == _relation(df)
+ assert transform.params.params["rawPredictionCol"] ==
pb2.Expression.Literal(string="")
+ assert transform.params.params["probabilityCol"] ==
pb2.Expression.Literal(string=vector)
+
+
+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.
+ import pandas as pd
+ import pyspark.ml.connect as connect
+ from _mock_connect_server import ddl_data_type
+
+ spark, service = ml_mock
+ message = (
+ "Transformers does not allow output column having the same name with
existing columns."
+ )
+ models = [] # Kept alive, so that no model is released during the checks.
+
+ def fitted(estimator):
+ # The model of estimator, and the uid of its fit.
+ sent = len(service.execute_requests)
+ service.execute_payload = _operator_info("model-1")
+ models.append(estimator.fit(spark.range(1)))
+ 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)
+ with pytest.raises(ValueError) as error:
+ model.transform(spark.range(1))
+ assert str(error.value) == message, column
+ with pytest.raises(ValueError) as error:
+ 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 [
+ (lr, "Prediction"),
+ (unprobable, "probability"),
+ (scaler, "O"),
+ (kmeans, "prediction"),
+ ]:
+ service.data_type = ddl_data_type(f"f array<double>, `{column}`
double")
+ 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,
+ # 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.
+ import pandas as pd
+ import pyarrow as pa
+ 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.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"]
+
+ 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"
+ 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")
+ models.append(connect.LogisticRegression().fit(spark.range(1)))
+ 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 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]]
+
+ class Columns:
+ # An object of the attributes that PySpark reads, which is not a
DataFrame.
+ columns = ["features"]
+ select = None
+
+ for other in ([1], None):
+ name = type(other).__name__
+ with pytest.raises(AttributeError) as error:
+ scaler.transform(other)
+ assert str(error.value) == f"'{name}' object has no attribute
'columns'"
+ for estimator in (
+ connect.LogisticRegression(),
+ connect.MaxAbsScaler(inputCol="features"),
+ 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())
+ assert str(error.value) == "transform() takes a DataFrame or a pandas
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_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
@@ -374,7 +685,13 @@ def
test_ml_connect_setters_set_the_params_of_their_receiver_as_pyspark(ml_mock)
(MaxAbsScaler, dict(inputCol="in", outputCol="out")),
(StringIndexer, dict(inputCol="in", outputCol="out")),
(VectorAssembler, dict(inputCols=["a", "b"], outputCol="out")),
- (LogisticRegression, dict(featuresCol="f", labelCol="y",
predictionCol="p", maxIter=7)),
+ (
+ LogisticRegression,
+ dict(
+ featuresCol="f", labelCol="y", predictionCol="p",
probabilityCol="q", maxIter=7,
+ tol=0.25,
+ ),
+ ),
(
LinearSVC,
dict(
@@ -470,7 +787,8 @@ _NATIVE_PARAMS = {
"StringIndexer": dict(inputCol="str", outputCol="str"),
"VectorAssembler": dict(inputCols="str_list", outputCol="str"),
"LogisticRegression": dict(
- featuresCol="str", labelCol="str", predictionCol="str", maxIter="int"
+ featuresCol="str", labelCol="str", predictionCol="str",
probabilityCol="str",
+ maxIter="int", tol="float",
),
"LinearSVC": dict(
featuresCol="str", labelCol="str", predictionCol="str", maxIter="int",
regParam="float",
@@ -617,14 +935,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, and the
centering of
- # StandardScaler, as PySpark's scales to (x - mean) / std.
+ # 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.
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 {}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]