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 fa8d1a7a [SPARK-61619][CONNECT][PYTHON] Name the int columns of a
pandas frame as createDataFrame does, evaluate only the read columns, and
resolve the case of featuresCol, in the native ML of the Python client
fa8d1a7a is described below
commit fa8d1a7a3c28a1d81603e8794dbb575f3b088be5
Author: Hyukjin Kwon <[email protected]>
AuthorDate: Fri Nov 13 15:49:46 2026 +0900
[SPARK-61619][CONNECT][PYTHON] Name the int columns of a pandas frame as
createDataFrame does, evaluate only the read columns, and resolve the case of
featuresCol, in the native ML of the Python client
### What changes were proposed in this pull request?
A follow-up of the post-merge review of #599. The native ML of the Python
client now:
- names the columns of a pandas frame by the `str` of each label, as
`createDataFrame` does (`pyspark/sql/connect/session.py`);
- selects only the columns that an evaluator reads (the prediction or
probability column, and the label) from a pandas frame before the Arrow
conversion, as PySpark's evaluators read only their input columns;
- spells the column params (`featuresCol`, `labelCol`, and the evaluator's
`predictionCol` and `rawPredictionCol`) as the schema of the dataset spells
them, in fit, transform and evaluate, and selects the fit's columns by that
spelling. Spark resolves a column name in any case, but the JVM estimator reads
the struct field by its exact name.
In the Rust API, `Evaluator` gains a provided `params_mut` method. It
returns `None` by default, and the three in-tree evaluators override it, so an
external implementation still compiles unchanged.
### Why are the changes needed?
Before this change, against PySpark 4.3.0:
- `RegressionEvaluator(labelCol="label",
predictionCol="prediction").evaluate(pd.DataFrame({0: [...], "label": [...],
"prediction": [...]}))` raised `TypeError: expected bytes, int found`. PySpark
gives `0.2886...`, and so does the client after this change. A frame from
`pd.DataFrame(ndarray)` has int labels.
- With an unused `uint64` column in that frame, evaluate failed with
`UNSUPPORTED_DATA_TYPE_FOR_ARROW_CONVERSION`. PySpark gives the same value as
without the column.
- `LogisticRegression(featuresCol="FEATURES").fit(df)` over an
`array<double>` column `features` failed with `FIELD_NOT_FOUND: No such struct
field FEATURES in features, label`. The same held for
`KMeans(featuresCol="FEATURES")` on a vector column and
`RegressionEvaluator(predictionCol="PREDICTION")`. PySpark resolves them.
### Does this PR introduce _any_ user-facing change?
Yes. A native fit, transform or evaluate takes column names that differ
from the schema only in case, and a pandas evaluate no longer fails on int
labels or unread columns. A default `featuresCol` with a `Features` column is
sent as `"Features"`.
### How was this patch tested?
- New tests, each checked to fail without the fix:
- offline:
`test_ml_connect_pandas_frames_name_and_read_their_columns_as_pyspark` and
`test_ml_connect_native_columns_are_spelled_as_the_schema_of_the_dataset`;
- e2e, against Spark 4.3.0:
`test_ml_connect_pandas_frames_name_int_labels_and_read_their_columns_as_pyspark`
and
`test_ml_connect_columns_spelled_in_another_case_than_the_schema_as_pyspark`;
- Rust unit:
`evaluator_params_mut_is_optional_for_external_implementations`.
- On the tree merged with the latest master (#616 included):
- the Rust lib tests: 680 and 220 passed;
- `test_ml_offline.py`: 153 passed;
- the ML e2e files: 154 passed;
- the `--no-run` builds, `cargo fmt`, the stub audit and ruff.
- CI's offline set passed on the branch before the merge, with 3308 passed.
### 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 #624 from HyukjinKwon/SPARK-61619-native-ml-pandas.
Authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
crates/pyspark-rs/src/ml.rs | 236 ++++++++++++++++++++++++++++------------
crates/spark-connect/src/ml.rs | 50 +++++++++
python/tests/test_ml_e2e.py | 64 +++++++++++
python/tests/test_ml_offline.py | 101 ++++++++++++++++-
4 files changed, 378 insertions(+), 73 deletions(-)
diff --git a/crates/pyspark-rs/src/ml.rs b/crates/pyspark-rs/src/ml.rs
index ae67e4ae..368dd776 100644
--- a/crates/pyspark-rs/src/ml.rs
+++ b/crates/pyspark-rs/src/ml.rs
@@ -25,6 +25,7 @@ use spark_connect::ml::{
RandomForestClassifier, RandomForestRegressor, RegressionEvaluator,
StringIndexer, Transformer,
VectorAssembler,
};
+use spark_connect::types::StructField;
use spark_connect::DataFrame;
use crate::dataframe::PyDataFrame;
@@ -342,7 +343,8 @@ fn dataset_of<'py>(
/// 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.
+/// 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")?;
@@ -357,7 +359,7 @@ fn active_dataframe(pdf: &Bound<'_, PyAny>) ->
PyResult<DataFrame> {
Err(_) => pa.call_method1("array", (column,))?,
};
arrays.append(array)?;
- names.append(name)?;
+ names.append(name.str()?)?;
}
let table = pa
.getattr("Table")?
@@ -434,7 +436,7 @@ where
{
let py = slf.py();
let dataset = dataset_of(dataset, "fit", "select")?;
- let estimator = snapshot(slf)?;
+ let mut estimator = snapshot(slf)?;
let columns = reads.and_then(|reads| read_columns(estimator.params(),
reads));
let (df, select) = match dataset {
Dataset::Spark(df) => (df, columns),
@@ -448,10 +450,23 @@ where
};
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.
- let array = vectors.array_input(py, &df, false)?;
+ // of it: the selection keeps the columns as they are. The JVM estimator
reads its columns by
+ // the spelling of the schema (see [`spell_param`]).
+ let labelled = estimator.params().get_param("labelCol").is_some();
+ let fields = if vectors.input.is_some() || labelled {
+ schema_fields(py, &df)?
+ } else {
+ Vec::new()
+ };
+ let array = vectors.input_field(&fields).filter(is_number_array);
+ let params =
vectors.spell_features(std::mem::take(estimator.params_mut()), &fields);
+ *estimator.params_mut() = spell_param(params, &fields, "labelCol", None);
let df = match select {
- Some(columns) => df.select(columns.iter().map(|name|
exact_column(name))),
+ Some(columns) => df.select(
+ columns
+ .iter()
+ .map(|name| exact_column(spelling(&fields, name))),
+ ),
None => df,
};
check(py, &estimator, &df)?;
@@ -572,51 +587,86 @@ impl Vectors {
}
}
- /// The field of the `input` column in the schema of `df`, found
regardless of case as Spark
- /// resolves it, when it is an array of numbers. Another type is sent as
it is, which the JVM
- /// estimator checks. The schema is read only for an `input`. With
`lazily`, of a transform,
- /// which is lazy as the transforms of PySpark's JVM models are, a schema
that the server does
- /// not give (of a DataFrame too deep for it, say) leaves the column as it
is: the server
- /// raises its error when the transformed DataFrame is analyzed or run, as
without the read.
- fn array_input(
- &self,
- py: Python<'_>,
- df: &DataFrame,
- lazily: bool,
- ) -> PyResult<Option<spark_connect::types::StructField>> {
- use spark_connect::types::DataType;
-
- let Some(input) = &self.input else {
- return Ok(None);
- };
- let fields = if lazily {
- let session = df.spark_session();
- // A signal still raises: it is the outer error.
- match crate::interrupt::interruptible_outcome(py, &session, || {
- df.schema().map_err(Box::new)
- })? {
- Ok(DataType::Struct { fields }) => fields,
- _ => return Ok(None),
- }
- } else {
- schema_fields(py, df)?
- };
- Ok(fields
- .into_iter()
+ /// The field of the `input` column in `fields`, the schema of a
DataFrame, found regardless of
+ /// case as Spark resolves it, of any type. None when there is no `input`,
or no such column.
+ fn input_field(&self, fields: &[StructField]) -> Option<StructField> {
+ let input = self.input.as_ref()?;
+ fields
+ .iter()
.find(|field| field.name.eq_ignore_ascii_case(input))
- .filter(|field| match &field.data_type {
- DataType::Array { element_type, .. } => matches!(
- **element_type,
- DataType::Byte
- | DataType::Short
- | DataType::Integer
- | DataType::Long
- | DataType::Float
- | DataType::Double
- | DataType::Decimal { .. }
- ),
- _ => false,
- }))
+ .cloned()
+ }
+
+ /// `params`, with the featuresCol spelled as the input column of `fields`
is (see
+ /// [`spell_param`]), where the JVM estimator or model reads a vector of
its featuresCol.
+ fn spell_features(&self, params: Params, fields: &[StructField]) -> Params
{
+ match self.input {
+ Some(_) => spell_param(params, fields, "featuresCol",
Some("features")),
+ None => params,
+ }
+ }
+}
+
+/// Whether `field` is an array of numbers, which an input column sends as its
ML vector.
+fn is_number_array(field: &StructField) -> bool {
+ use spark_connect::types::DataType;
+
+ match &field.data_type {
+ DataType::Array { element_type, .. } => matches!(
+ **element_type,
+ DataType::Byte
+ | DataType::Short
+ | DataType::Integer
+ | DataType::Long
+ | DataType::Float
+ | DataType::Double
+ | DataType::Decimal { .. }
+ ),
+ _ => false,
+ }
+}
+
+/// `params`, whose string param `name` is spelled as the field of `fields`
that it names. Spark
+/// resolves a column name regardless of case, but the JVM reads the param as
it is given, so the
+/// param takes the spelling of the schema where the two differ. An unset
param names `default`,
+/// and is set only where that differs too. Without a `default`, an unset
param is left as it is.
+fn spell_param(
+ params: Params,
+ fields: &[StructField],
+ name: &str,
+ default: Option<&str>,
+) -> Params {
+ let Some(given) = string_or(¶ms, name, default) else {
+ return params;
+ };
+ let spelled = spelling(fields, &given);
+ if spelled == given {
+ params
+ } else {
+ params.set_param_string(name, spelled)
+ }
+}
+
+/// The spelling in `fields`, the schema of a DataFrame, of the column `name`,
which Spark resolves
+/// regardless of case; `name` itself when `fields` has no such column.
+fn spelling<'a>(fields: &'a [StructField], name: &'a str) -> &'a str {
+ fields
+ .iter()
+ .find(|field| field.name.eq_ignore_ascii_case(name))
+ .map_or(name, |field| field.name.as_str())
+}
+
+/// The fields of the schema of `df`, read lazily, as a transform is, which is
lazy as the
+/// transforms of PySpark's JVM models are: a schema that the server does not
give (of a DataFrame
+/// too deep for it, say) is empty, and leaves the columns as they are, as the
server raises its
+/// error when the transformed DataFrame is analyzed or run, as without the
read. A signal raises.
+fn lazy_schema_fields(py: Python<'_>, df: &DataFrame) ->
PyResult<Vec<StructField>> {
+ use spark_connect::types::DataType;
+
+ let session = df.spark_session();
+ match crate::interrupt::interruptible_outcome(py, &session, ||
df.schema().map_err(Box::new))? {
+ Ok(DataType::Struct { fields }) => Ok(fields),
+ _ => Ok(Vec::new()),
}
}
@@ -713,14 +763,30 @@ 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.
+/// 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.
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`]).
+/// PySpark's evaluators evaluate it (see [`evaluation_dataset`] and
[`evaluator_input`]). The
+/// JVM evaluator reads its columns by the spelling of the schema of the
dataset.
fn evaluate_native<T>(
slf: &Bound<'_, T>,
dataset: &Bound<'_, PyAny>,
@@ -731,9 +797,23 @@ where
T::Core: Evaluator,
{
let py = slf.py();
- let evaluator = snapshot(slf)?;
- let df = evaluation_dataset(dataset)?;
- let df = evaluator_input(py, df, inputs(&evaluator))?;
+ 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() {
+ let mut params = std::mem::take(evaluator_params);
+ params = spell_param(params, &fields, "labelCol", Some("label"));
+ if !inputs.doubles.is_empty() {
+ params = spell_param(params, &fields, "predictionCol",
Some("prediction"));
+ }
+ if inputs.score.is_some() {
+ params = spell_param(params, &fields, "rawPredictionCol",
Some("rawPrediction"));
+ }
+ *evaluator_params = params;
+ }
+ let df = evaluator_input(df, &fields, inputs);
interruptible(py, &df.spark_session(), || {
evaluator.evaluate(&df).map_err(Box::new)
})
@@ -741,25 +821,31 @@ 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.
-fn evaluation_dataset(dataset: &Bound<'_, PyAny>) -> PyResult<DataFrame> {
+/// 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) => active_dataframe(&pdf),
+ Dataset::Pandas(pdf) => {
+ let columns = PyList::new(pdf.py(), inputs.reads())?;
+ active_dataframe(&pdf.get_item(columns)?)
+ }
}
}
-/// `df` as the JVM evaluator reads it, 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 as a vector by
`array_to_vector`, which
-/// the JVM evaluator reads at its element 1, as PySpark's reads the column 1
of an array. The
-/// columns are found in the schema of `df` regardless of case, as Spark
resolves them; another
-/// type is sent as it is, which the JVM evaluator checks.
-fn evaluator_input(py: Python<'_>, df: DataFrame, inputs: EvaluatorInputs) ->
PyResult<DataFrame> {
+/// `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
+/// as a vector by `array_to_vector`, which the JVM evaluator reads at its
element 1, as PySpark's
+/// reads the column 1 of an array. The columns are found in `fields`
regardless of case, as Spark
+/// resolves them; another type is sent as it is, which the JVM evaluator
checks.
+fn evaluator_input(
+ mut df: DataFrame,
+ fields: &[StructField],
+ inputs: EvaluatorInputs,
+) -> DataFrame {
use spark_connect::types::DataType;
- let fields = schema_fields(py, &df)?;
- let mut df = df;
for field in fields {
let named = |name: &String| name.eq_ignore_ascii_case(&field.name);
let score = inputs.score.as_ref().is_some_and(named);
@@ -778,7 +864,7 @@ fn evaluator_input(py: Python<'_>, df: DataFrame, inputs:
EvaluatorInputs) -> Py
};
df = df.with_column(&field.name, converted);
}
- Ok(df)
+ df
}
/// The model of a class of PySpark's `pyspark.ml.connect`,
LogisticRegression, whose transform
@@ -963,6 +1049,14 @@ impl PyMLModel {
let mut model = self.model.clone_box();
let session = df.spark_session();
let vectors = Vectors::of(model.operator(), model.params());
+ // The JVM model reads its featuresCol by the spelling of the schema
of the input.
+ let fields = if vectors.input.is_some() {
+ lazy_schema_fields(py, df)?
+ } else {
+ Vec::new()
+ };
+ let params = std::mem::take(model.params_mut());
+ *model.params_mut() = vectors.spell_features(params, &fields);
// 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 {
@@ -980,7 +1074,8 @@ impl PyMLModel {
// 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, true)?
+ .input_field(&fields)
+ .filter(is_number_array)
.map(|field| (format!("{}__input", model.operator().uid), field));
let input = match &array {
Some((kept, field)) => df.with_columns(vec![
@@ -4304,6 +4399,7 @@ impl PyRegressionEvaluator {
evaluate_native(slf, dataset, |evaluator| EvaluatorInputs {
doubles: vec![evaluator.prediction_col().to_string()],
score: None,
+ label: evaluator.label_col().to_string(),
})
}
}
@@ -4408,6 +4504,7 @@ 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(),
})
}
}
@@ -4735,6 +4832,7 @@ 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/crates/spark-connect/src/ml.rs b/crates/spark-connect/src/ml.rs
index d6117e39..8a0108ff 100644
--- a/crates/spark-connect/src/ml.rs
+++ b/crates/spark-connect/src/ml.rs
@@ -691,6 +691,12 @@ pub trait Evaluator: Send + Sync {
/// Get the parameters of this evaluator.
fn params(&self) -> &Params;
+ /// Get mutable parameters, where the evaluator exposes them. The default
is None, so that an
+ /// implementation outside this crate needs no change.
+ fn params_mut(&mut self) -> Option<&mut Params> {
+ None
+ }
+
/// Evaluate a DataFrame and return a metric value.
fn evaluate(&self, _df: &DataFrame) ->
spark_connect_core::error::Result<f64>;
}
@@ -7016,6 +7022,10 @@ impl Evaluator for RegressionEvaluator {
&self.params
}
+ fn params_mut(&mut self) -> Option<&mut Params> {
+ Some(&mut self.params)
+ }
+
fn evaluate(&self, df: &DataFrame) ->
spark_connect_core::error::Result<f64> {
evaluate_via_command(&self.operator, &self.params, df)
}
@@ -7091,6 +7101,10 @@ impl Evaluator for BinaryClassificationEvaluator {
&self.params
}
+ fn params_mut(&mut self) -> Option<&mut Params> {
+ Some(&mut self.params)
+ }
+
fn evaluate(&self, df: &DataFrame) ->
spark_connect_core::error::Result<f64> {
evaluate_via_command(&self.operator, &self.params, df)
}
@@ -7257,6 +7271,9 @@ impl Evaluator for MulticlassClassificationEvaluator {
fn params(&self) -> &Params {
&self.params
}
+ fn params_mut(&mut self) -> Option<&mut Params> {
+ Some(&mut self.params)
+ }
fn evaluate(&self, df: &DataFrame) ->
spark_connect_core::error::Result<f64> {
evaluate_via_command(&self.operator, &self.params, df)
}
@@ -7384,6 +7401,39 @@ mod tests {
// Used only by the tests below (the non-test build does not reference it).
use crate::session::SparkSession;
+ /// An evaluator outside this crate, which implements only the methods
that were required
+ /// before `params_mut`: it must still compile, and it exposes no params
to mutate.
+ struct ExternalEvaluator {
+ operator: MlOperator,
+ params: Params,
+ }
+
+ impl Evaluator for ExternalEvaluator {
+ fn operator(&self) -> &MlOperator {
+ &self.operator
+ }
+
+ fn params(&self) -> &Params {
+ &self.params
+ }
+
+ fn evaluate(&self, _df: &DataFrame) ->
spark_connect_core::error::Result<f64> {
+ Ok(0.0)
+ }
+ }
+
+ #[test]
+ fn evaluator_params_mut_is_optional_for_external_implementations() {
+ let mut evaluator = ExternalEvaluator {
+ operator: MlOperator::new("external.Evaluator",
OperatorType::Evaluator),
+ params: Params::new(),
+ };
+ assert!(evaluator.params_mut().is_none());
+ assert!(evaluator.params().get_param("labelCol").is_none());
+ let mut regression = RegressionEvaluator::new();
+ assert!(Evaluator::params_mut(&mut regression).is_some());
+ }
+
#[test]
fn test_params_creation() {
let params = Params::new()
diff --git a/python/tests/test_ml_e2e.py b/python/tests/test_ml_e2e.py
index 795d855b..817e4131 100644
--- a/python/tests/test_ml_e2e.py
+++ b/python/tests/test_ml_e2e.py
@@ -494,6 +494,70 @@ def
test_ml_connect_evaluators_take_the_columns_and_the_pandas_frames_of_pyspark
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
+ 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]
+
+
+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
+ # whose params spell a column FEATURES, LABEL or PREDICTION, which the
schema spells in lower
+ # case, read the column as the schema spells it, as the JVM reads the
params it is given.
+ from pyspark.ml.connect import KMeans
+ from pyspark.ml.connect.classification import LogisticRegression
+ from pyspark.ml.connect.evaluation import RegressionEvaluator
+
+ train = session.sql(
+ "select * from values (array(0.0D, 1.0D), 0.0D), (array(1.0D, 0.0D),
1.0D), "
+ "(array(2.0D, 2.0D), 1.0D), (array(3.0D, 1.0D), 0.0D) as t(features,
label)"
+ )
+ model = KMeans(k=2, seed=1, featuresCol="FEATURES").fit(train)
+ out = model.transform(train.selectExpr("features AS FEATURES",
"label")).toPandas()
+ assert list(out.columns) == ["FEATURES", "label", "prediction"]
+ assert set(out["prediction"]) <= {0, 1}
+
+ fitted = LogisticRegression(featuresCol="FEATURES", labelCol="LABEL",
maxIter=5).fit(
+ train.selectExpr("features AS FEATURES", "label AS LABEL")
+ )
+ out = fitted.transform(train.selectExpr("features AS FEATURES",
"label")).toPandas()
+ assert list(out.columns) == ["FEATURES", "label", "prediction",
"probability"]
+
+ # The schema spells the label LABEL and the prediction prediction: the
evaluator reads both.
+ scored = session.sql(
+ "select label AS LABEL, cast(label AS double) AS prediction "
+ "from values (1.0D), (2.0D) as t(label)"
+ )
+ metric = RegressionEvaluator(labelCol="LABEL",
predictionCol="PREDICTION").evaluate(scored)
+ assert metric == pytest.approx(0.0)
+
+
def
test_ml_connect_scalers_and_estimators_take_the_array_columns_of_pyspark(session):
# The examples of PySpark's MaxAbsScaler, StandardScaler and
LogisticRegression, whose
# pyspark.ml.connect classes compute on arrays: the scalers are PySpark's
own, and output an
diff --git a/python/tests/test_ml_offline.py b/python/tests/test_ml_offline.py
index 52d575f2..732713f5 100644
--- a/python/tests/test_ml_offline.py
+++ b/python/tests/test_ml_offline.py
@@ -373,14 +373,16 @@ def
test_ml_connect_native_estimators_take_the_array_columns_of_pyspark(ml_mock)
featured = [name for name, params in _NATIVE_PARAMS.items() if
"featuresCol" in params]
assert {"LogisticRegression", "KMeans"} <= set(featured)
estimators = [getattr(connect, name)() for name in featured]
- reads = {"LogisticRegression": ["features", "label"]}
+ # The fit of LogisticRegression selects its columns by the spelling of the
schema too.
+ reads = {"LogisticRegression": ["Features", "label"]}
for estimator in estimators:
name = type(estimator).__name__
df, fit, transformed = requests(estimator)
- # The params name the column as they were given, and the dataset has
the vector of the
- # array in its place. (The params that a class sends of itself: see
_defaults_sent.)
+ # The params name the column as the schema spells it, "Features" (the
default featuresCol
+ # is "features"), and the dataset has the vector of the array in its
place. (The params
+ # that a class sends of itself: see _defaults_sent.)
sent = {k: v.string for k, v in fit.params.params.items() if k not in
_defaults_sent(name)}
- assert sent == {}, name
+ assert sent == {"featuresCol": "Features"}, 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) == [
@@ -721,6 +723,97 @@ def
test_ml_connect_pandas_frames_send_their_nan_as_pyspark(ml_mock):
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
+
+ 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):
+ # As Spark resolves a column name regardless of case, but the JVM reads
the column params as
+ # they are given: a native fit, transform or evaluate spells its
featuresCol and labelCol as
+ # the schema of the dataset spells them, which is also the name of the
columns that its select
+ # and its array of numbers take. PySpark's LogisticRegression selects its
columns, which Spark
+ # resolves regardless of case, so the fit sends the schema's spelling of
them too.
+ import pyspark.ml.connect as connect
+ from _mock_connect_server import ddl_data_type
+
+ spark, service = ml_mock
+ service.data_type = ddl_data_type("id bigint, features array<double>,
label double")
+ df = spark.range(1)
+ models = [] # Kept alive, so that no model is released during the checks.
+
+ def fit(estimator):
+ sent = len(service.execute_requests)
+ service.execute_payload = _operator_info("model-1")
+ service.query_payload = _labels_result()
+ models.append(estimator.fit(df))
+ service.query_payload = None
+ return _commands_but_deletes(service, sent)[0].ml_command.fit
+
+ kmeans = fit(connect.KMeans(featuresCol="FEATURES"))
+ assert kmeans.params.params == {"featuresCol":
pb2.Expression.Literal(string="features")}
+ assert _aliases(kmeans.dataset.with_columns) == [(["features"],
_array_to_vector("features"))]
+
+ logistic = fit(connect.LogisticRegression(featuresCol="FEATURES",
labelCol="LABEL"))
+ assert logistic.params.params["featuresCol"] ==
pb2.Expression.Literal(string="features")
+ assert logistic.params.params["labelCol"] ==
pb2.Expression.Literal(string="label")
+ columns = logistic.dataset.with_columns.input.project.expressions
+ assert [_text(column) for column in columns] == [_attribute("features"),
_attribute("label")]
+
+ # The transform of a model whose featuresCol is given in another case than
the schema of the
+ # transformed DataFrame, which spells it FEATURES, sends the spelling of
that schema.
+ service.data_type = ddl_data_type("id bigint, FEATURES array<double>,
label double")
+ transformed = _relation(models[-1].transform(spark.range(1)))
+ transform = transformed.drop.input.with_columns.input.ml_relation.transform
+ assert transform.params.params["featuresCol"] ==
pb2.Expression.Literal(string="FEATURES")
+
+ # The evaluate of a DataFrame sends the labelCol and the predictionCol
that the schema spells.
+ service.data_type = ddl_data_type("label double, prediction double")
+ sent = len(service.execute_requests)
+ service.execute_payload =
_ml_result(param=pb2.Expression.Literal(double=0.5))
+ evaluator = connect.RegressionEvaluator(labelCol="LABEL",
predictionCol="PREDICTION")
+ assert evaluator.evaluate(spark.range(1)) == 0.5
+ evaluate = _commands_but_deletes(service, sent)[0].ml_command.evaluate
+ assert evaluate.params.params["labelCol"] ==
pb2.Expression.Literal(string="label")
+ 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
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]