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 529a5582 [SPARK-61612][CONNECT] Support native FMClassifier,
MultilayerPerceptronClassifier and OneVsRest
529a5582 is described below
commit 529a558255b4d7ed440a288675c413e1b6de7806
Author: Ruifeng Zheng <[email protected]>
AuthorDate: Fri Nov 13 13:02:11 2026 +0900
[SPARK-61612][CONNECT] Support native FMClassifier,
MultilayerPerceptronClassifier and OneVsRest
### What changes were proposed in this pull request?
Add the three remaining native classification estimators in Rust and
`pyspark.ml.connect.classification`:
- `FMClassifier` fits Spark's JVM factorization machine classifier and
returns a cached model.
- `MultilayerPerceptronClassifier` fits Spark's JVM neural-network
classifier, including integer layer arrays and dense/sparse initial-weight
vectors.
- `OneVsRest` performs multiclass reduction in Rust, fitting independent
binary classifiers with bounded parallelism and combining their positive-class
raw scores. It supports all eight native base classifiers, instance weights
where supported, custom columns, temporary-cache cleanup and lazy model
ownership. Score selection preserves PySpark's first-tie and NaN/null behavior.
Expose all constructor parameters and named setters (17 for FM, 13 for the
perceptron plus `setThresholds`, and 7 for OneVsRest), with typed Rust
setters/getters. Add official parameter goldens, Rust/Python tests, CI coverage
and compatibility documentation.
### Why are the changes needed?
These are the remaining classifier estimator classes missing from the
native ML APIs. They enable interaction-based binary classification, multilayer
neural networks and multiclass reduction using existing native binary
classifiers.
### Does this PR introduce _any_ user-facing change?
Yes. Rust and native Python users can configure, fit and transform with
these three classifiers. Python `fit` returns the shared native `MLModel`.
OneVsRest accepts native base classifiers and observes their parameter changes
made before fitting, while keeping independent snapshots for its binary fits.
This adds estimator configuration, fitting and DataFrame predictions. Model
inspection, training summaries, persistence and single-vector prediction remain
separate API work.
### How was this patch tested?
- 665 Rust unit tests and four live Rust classifier tests passed. The live
tests cover numerical predictions, dense/sparse initial weights, parallel
OneVsRest fits, model cloning/lifetime, session checks and the composite ML
relation.
- Seven parameter cases captured with official PySpark 4.3.0 match Rust
encoding. Native Python constructor/setter requests also match the
direct-classifier fixtures.
- 36 behavior cases were verified with official PySpark and the native
Python client, covering both FM solvers, both perceptron solvers, hidden
layers, every OneVsRest base classifier, weights, independent/lazy models,
ties/NaNs, empty-data behavior and invalid parameters. Two shared native
model-lifetime/session tests also passed.
- 2,099 Python offline tests passed (8 skips, 14 passing subtests), plus
the final focused parameter checks. Constructor order/defaults and named
setters match official PySpark. The SQL API introspection check found no
missing public members beyond the documented transport-internal exclusions.
- Official Spark 4.3.0 Connect suite through the Rust transport: 2,638
passed, 589 skipped across 87 files, with zero unexpected failures. The three
artifact/local-cluster test files require a separate cluster environment and
were excluded.
- All integration tests compile with and without `wasm-udf`. Rust
formatting, Ruff lint/format and whitespace checks passed. Clippy passed for
the core and new test targets; workspace/Python Clippy still reports errors at
code unchanged from the base commit.
### Was this patch authored or co-authored using generative AI tooling?
Generated-by: Codex (GPT-6)
This pull request and its description were written by Isaac.
Closes #605 from zhengruifeng/add-remaining-classifiers.
Authored-by: Ruifeng Zheng <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
.github/workflows/build_python_connect.yml | 4 +-
crates/pyspark-rs/src/lib.rs | 4 +
crates/pyspark-rs/src/ml.rs | 601 +++++++-
crates/spark-connect/src/ml.rs | 1551 +++++++++++++++++++-
.../tests/e2e_remaining_classifiers.rs | 147 ++
.../tests/remaining_classifiers_golden.rs | 99 ++
docs/compatibility.md | 53 +
python/pyspark/ml/connect/__init__.py | 6 +
python/pyspark/ml/connect/classification.py | 16 +-
python/tests/test_ml_e2e.py | 4 +
python/tests/test_ml_offline.py | 93 ++
python/tests/test_remaining_classifiers_e2e.py | 323 ++++
scripts/capture_remaining_classifiers_golden.py | 140 ++
tests/golden/remaining_classifiers.json | 142 ++
14 files changed, 3150 insertions(+), 33 deletions(-)
diff --git a/.github/workflows/build_python_connect.yml
b/.github/workflows/build_python_connect.yml
index 7fdf98a3..df841a25 100644
--- a/.github/workflows/build_python_connect.yml
+++ b/.github/workflows/build_python_connect.yml
@@ -227,7 +227,7 @@ jobs:
env:
SPARK_REMOTE: sc://localhost:15002
PYTHONPATH: ${{ github.workspace }}/python
- run: python -m pytest tests/test_arrow_e2e.py tests/test_dropin_e2e.py
tests/test_ml_e2e.py tests/test_gbt_classifier_e2e.py
tests/test_gbt_regressor_e2e.py tests/test_naive_bayes_e2e.py
tests/test_bisecting_kmeans_e2e.py tests/test_gaussian_mixture_e2e.py
tests/test_generalized_linear_regression_e2e.py -q
+ run: python -m pytest tests/test_arrow_e2e.py tests/test_dropin_e2e.py
tests/test_ml_e2e.py tests/test_gbt_classifier_e2e.py
tests/test_gbt_regressor_e2e.py tests/test_naive_bayes_e2e.py
tests/test_bisecting_kmeans_e2e.py tests/test_gaussian_mixture_e2e.py
tests/test_generalized_linear_regression_e2e.py
tests/test_remaining_classifiers_e2e.py -q
- name: Restart Connect server in local-cluster mode
# Resource profiles and artifact distribution across executors can
only be
@@ -556,7 +556,7 @@ jobs:
run: |
cargo test -p apache-spark-connect \
--test e2e_functions --test e2e_columns --test e2e_dataframe \
- --test e2e_coverage --test e2e_linear_svc --test
e2e_linear_regression --test e2e_generalized_linear_regression --test
e2e_kmeans --test e2e_bisecting_kmeans --test e2e_gaussian_mixture --test
e2e_decision_tree_regressor --test e2e_decision_tree_classifier --test
e2e_gbt_regressor --test e2e_naive_bayes --test e2e_gbt_classifier --test
e2e_random_forest --test e2e_random_forest_regressor --test e2e_integration \
+ --test e2e_coverage --test e2e_linear_svc --test
e2e_linear_regression --test e2e_generalized_linear_regression --test
e2e_remaining_classifiers --test e2e_kmeans --test e2e_bisecting_kmeans --test
e2e_gaussian_mixture --test e2e_decision_tree_regressor --test
e2e_decision_tree_classifier --test e2e_gbt_regressor --test e2e_naive_bayes
--test e2e_gbt_classifier --test e2e_random_forest --test
e2e_random_forest_regressor --test e2e_integration \
--test arrow_map_input --test array_literal --test
execute_plan_hook --test raw_relation \
--test types_roundtrip \
--test e2e_reattach_drop \
diff --git a/crates/pyspark-rs/src/lib.rs b/crates/pyspark-rs/src/lib.rs
index 1a29f76f..eedec08d 100644
--- a/crates/pyspark-rs/src/lib.rs
+++ b/crates/pyspark-rs/src/lib.rs
@@ -244,6 +244,10 @@ fn _pyspark(_py: Python<'_>, m: &Bound<'_, PyModule>) ->
PyResult<()> {
m.add_class::<ml::PyVectorAssembler>()?;
m.add_class::<ml::PyLogisticRegression>()?;
m.add_class::<ml::PyLinearSVC>()?;
+ m.add_class::<ml::PyFMClassifier>()?;
+ m.add_class::<ml::PyMultilayerPerceptronClassifier>()?;
+ m.add_class::<ml::PyOneVsRest>()?;
+
m.add_class::<ml::PyLinearRegression>()?;
m.add_class::<ml::PyGeneralizedLinearRegression>()?;
m.add_class::<ml::PyDecisionTreeClassifier>()?;
diff --git a/crates/pyspark-rs/src/ml.rs b/crates/pyspark-rs/src/ml.rs
index 25135041..0ba22f09 100644
--- a/crates/pyspark-rs/src/ml.rs
+++ b/crates/pyspark-rs/src/ml.rs
@@ -16,12 +16,13 @@ use pyo3::pyclass::boolean_struct::False;
use pyo3::types::{PyDict, PyList, PyTuple, PyType};
use pyo3::PyClass;
use spark_connect::ml::{
- BinaryClassificationEvaluator, BisectingKMeans, CrossValidator,
DecisionTreeClassifier,
- DecisionTreeRegressor, Estimator, Evaluator, GBTClassifier, GBTRegressor,
GaussianMixture,
- GeneralizedLinearRegression, KMeans, LinearRegression, LinearSVC,
LogisticRegression,
- MaxAbsScaler, MlOperator, Model, MulticlassClassificationEvaluator,
NaiveBayes, Params,
- Pipeline, RandomForestClassifier, RandomForestRegressor,
RegressionEvaluator, StandardScaler,
- StringIndexer, Transformer, VectorAssembler,
+ BinaryClassificationEvaluator, BisectingKMeans, Classifier, CrossValidator,
+ DecisionTreeClassifier, DecisionTreeRegressor, Estimator, Evaluator,
FMClassifier,
+ GBTClassifier, GBTRegressor, GaussianMixture, GeneralizedLinearRegression,
KMeans,
+ LinearRegression, LinearSVC, LogisticRegression, MaxAbsScaler, MlOperator,
MlVector, Model,
+ MulticlassClassificationEvaluator, MultilayerPerceptronClassifier,
NaiveBayes, OneVsRest,
+ Params, Pipeline, RandomForestClassifier, RandomForestRegressor,
RegressionEvaluator,
+ StandardScaler, StringIndexer, Transformer, VectorAssembler,
};
use spark_connect::DataFrame;
@@ -45,6 +46,8 @@ enum Kind {
StrList,
/// `toListFloat`: an array literal of doubles.
FloatList,
+ IntList,
+ Vector,
}
impl Kind {
@@ -56,6 +59,8 @@ impl Kind {
Kind::Bool => "toBoolean",
Kind::StrList => "toListString",
Kind::FloatList => "toListFloat",
+ Kind::IntList => "toListInt",
+ Kind::Vector => "toVector",
}
}
}
@@ -76,6 +81,8 @@ enum Converted {
Bool(bool),
StrList(Vec<String>),
FloatList(Vec<f64>),
+ IntList(Vec<i64>),
+ Vector(MlVector),
}
/// Convert `value` of the param `name` with its `TypeConverters` method,
raising PySpark's
@@ -107,6 +114,28 @@ fn convert(name: &str, kind: Kind, value: &Bound<'_,
PyAny>) -> PyResult<Convert
Kind::Bool => Converted::Bool(converted.extract()?),
Kind::StrList => Converted::StrList(converted.extract()?),
Kind::FloatList => Converted::FloatList(converted.extract()?),
+ Kind::IntList => converted
+ .extract::<Vec<i64>>()
+ .map_or(Converted::Unsendable, Converted::IntList),
+ Kind::Vector => {
+ let linalg = py.import("pyspark.ml.linalg")?;
+ let values = converted
+ .getattr("values")?
+ .call_method0("tolist")?
+ .extract()?;
+ if converted.is_instance(&linalg.getattr("SparseVector")?)? {
+ Converted::Vector(MlVector::Sparse {
+ size: converted.getattr("size")?.extract()?,
+ indices: converted
+ .getattr("indices")?
+ .call_method0("tolist")?
+ .extract()?,
+ values,
+ })
+ } else {
+ Converted::Vector(MlVector::Dense(values))
+ }
+ }
})
}
@@ -166,6 +195,8 @@ fn apply<T: Native>(target: &mut T, name: &'static str,
value: Converted) {
Converted::Bool(value) => params.set_param_bool(jvm, value),
Converted::StrList(values) => params.set_param_string_array(jvm,
values),
Converted::FloatList(values) => params.set_param_double_array(jvm,
values),
+ Converted::IntList(values) => params.set_param_int_array(jvm, values),
+ Converted::Vector(value) => params.set_param_vector(jvm, value),
};
*target.params_mut() = params;
}
@@ -1458,6 +1489,561 @@ impl PyLinearSVC {
}
}
+/// Native FMClassifier.
+#[pyclass(name = "FMClassifier", module = "pyspark.ml.connect.classification")]
+pub struct PyFMClassifier {
+ inner: FMClassifier,
+ unsendable: Vec<&'static str>,
+}
+
+const FMCLASSIFIER_PARAMS: &[(&str, Kind)] = &[
+ ("featuresCol", Kind::Str),
+ ("labelCol", Kind::Str),
+ ("predictionCol", Kind::Str),
+ ("probabilityCol", Kind::Str),
+ ("rawPredictionCol", Kind::Str),
+ ("factorSize", Kind::Int),
+ ("fitIntercept", Kind::Bool),
+ ("fitLinear", Kind::Bool),
+ ("regParam", Kind::Float),
+ ("miniBatchFraction", Kind::Float),
+ ("initStd", Kind::Float),
+ ("maxIter", Kind::Int),
+ ("stepSize", Kind::Float),
+ ("tol", Kind::Float),
+ ("solver", Kind::Str),
+ ("thresholds", Kind::FloatList),
+ ("seed", Kind::Int),
+];
+
+#[pymethods]
+impl PyFMClassifier {
+ #[new]
+ #[pyo3(signature = (*args, **kwargs), text_signature = "(*,
featuresCol='features', labelCol='label', predictionCol='prediction',
probabilityCol='probability', rawPredictionCol='rawPrediction', factorSize=8,
fitIntercept=True, fitLinear=True, regParam=0.0, miniBatchFraction=1.0,
initStd=0.01, maxIter=100, stepSize=1.0, tol=1e-06, solver='adamW',
thresholds=None, seed=None)")]
+ fn new(args: &Bound<'_, PyTuple>, kwargs: Option<&Bound<'_, PyDict>>) ->
PyResult<Self> {
+ let mut this = Self {
+ inner: FMClassifier::new(),
+ unsendable: Vec::new(),
+ };
+ init_params(
+ &mut this,
+ "FMClassifier",
+ &[],
+ FMCLASSIFIER_PARAMS,
+ args,
+ kwargs,
+ )?;
+ Ok(this)
+ }
+
+ #[pyo3(name = "setFeaturesCol")]
+ fn set_feature_col<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "featuresCol", Kind::Str, value)
+ }
+
+ #[pyo3(name = "setLabelCol")]
+ fn set_label_col<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "labelCol", Kind::Str, value)
+ }
+
+ #[pyo3(name = "setPredictionCol")]
+ fn set_prediction_col<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> 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 = "setRawPredictionCol")]
+ fn set_raw_prediction_col<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "rawPredictionCol", Kind::Str, value)
+ }
+
+ #[pyo3(name = "setFactorSize")]
+ fn set_factor_size<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "factorSize", Kind::Int, value)
+ }
+
+ #[pyo3(name = "setFitIntercept")]
+ fn set_fit_intercept<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "fitIntercept", Kind::Bool, value)
+ }
+
+ #[pyo3(name = "setFitLinear")]
+ fn set_fit_linear<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "fitLinear", Kind::Bool, value)
+ }
+
+ #[pyo3(name = "setRegParam")]
+ fn set_reg_param<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "regParam", Kind::Float, value)
+ }
+
+ #[pyo3(name = "setMiniBatchFraction")]
+ fn set_mini_batch_fraction<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "miniBatchFraction", Kind::Float, value)
+ }
+
+ #[pyo3(name = "setInitStd")]
+ fn set_init_std<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "initStd", Kind::Float, value)
+ }
+
+ #[pyo3(name = "setMaxIter")]
+ fn set_max_iter<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "maxIter", Kind::Int, value)
+ }
+
+ #[pyo3(name = "setStepSize")]
+ fn set_step_size<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "stepSize", Kind::Float, value)
+ }
+
+ #[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)
+ }
+
+ #[pyo3(name = "setSolver")]
+ fn set_solver<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "solver", Kind::Str, value)
+ }
+
+ #[pyo3(name = "setThresholds")]
+ fn set_thresholds<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "thresholds", Kind::FloatList, value)
+ }
+
+ #[pyo3(name = "setSeed")]
+ fn set_seed<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "seed", Kind::Int, value)
+ }
+
+ fn fit(slf: &Bound<'_, Self>, dataset: &Bound<'_, PyAny>) ->
PyResult<PyMLModel> {
+ fit_native(slf, dataset, None)
+ }
+}
+
+/// Native MultilayerPerceptronClassifier.
+#[pyclass(
+ name = "MultilayerPerceptronClassifier",
+ module = "pyspark.ml.connect.classification"
+)]
+pub struct PyMultilayerPerceptronClassifier {
+ inner: MultilayerPerceptronClassifier,
+ unsendable: Vec<&'static str>,
+}
+
+const MULTILAYER_PERCEPTRON_CLASSIFIER_PARAMS: &[(&str, Kind)] = &[
+ ("featuresCol", Kind::Str),
+ ("labelCol", Kind::Str),
+ ("predictionCol", Kind::Str),
+ ("maxIter", Kind::Int),
+ ("tol", Kind::Float),
+ ("seed", Kind::Int),
+ ("layers", Kind::IntList),
+ ("blockSize", Kind::Int),
+ ("stepSize", Kind::Float),
+ ("solver", Kind::Str),
+ ("initialWeights", Kind::Vector),
+ ("probabilityCol", Kind::Str),
+ ("rawPredictionCol", Kind::Str),
+];
+
+#[pymethods]
+impl PyMultilayerPerceptronClassifier {
+ #[new]
+ #[pyo3(signature = (*args, **kwargs), text_signature = "(*,
featuresCol='features', labelCol='label', predictionCol='prediction',
maxIter=100, tol=1e-06, seed=None, layers=None, blockSize=128, stepSize=0.03,
solver='l-bfgs', initialWeights=None, probabilityCol='probability',
rawPredictionCol='rawPrediction')")]
+ fn new(args: &Bound<'_, PyTuple>, kwargs: Option<&Bound<'_, PyDict>>) ->
PyResult<Self> {
+ let mut this = Self {
+ inner: MultilayerPerceptronClassifier::new(),
+ unsendable: Vec::new(),
+ };
+ init_params(
+ &mut this,
+ "MultilayerPerceptronClassifier",
+ &[],
+ MULTILAYER_PERCEPTRON_CLASSIFIER_PARAMS,
+ args,
+ kwargs,
+ )?;
+ Ok(this)
+ }
+
+ #[pyo3(name = "setFeaturesCol")]
+ fn set_feature_col<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "featuresCol", Kind::Str, value)
+ }
+
+ #[pyo3(name = "setLabelCol")]
+ fn set_label_col<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "labelCol", Kind::Str, value)
+ }
+
+ #[pyo3(name = "setPredictionCol")]
+ fn set_prediction_col<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "predictionCol", Kind::Str, value)
+ }
+
+ #[pyo3(name = "setMaxIter")]
+ fn set_max_iter<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "maxIter", Kind::Int, value)
+ }
+
+ #[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)
+ }
+
+ #[pyo3(name = "setSeed")]
+ fn set_seed<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "seed", Kind::Int, value)
+ }
+
+ #[pyo3(name = "setLayers")]
+ fn set_layers<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "layers", Kind::IntList, value)
+ }
+
+ #[pyo3(name = "setBlockSize")]
+ fn set_block_size<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "blockSize", Kind::Int, value)
+ }
+
+ #[pyo3(name = "setStepSize")]
+ fn set_step_size<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "stepSize", Kind::Float, value)
+ }
+
+ #[pyo3(name = "setSolver")]
+ fn set_solver<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "solver", Kind::Str, value)
+ }
+
+ #[pyo3(name = "setInitialWeights")]
+ fn set_initial_weights<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "initialWeights", Kind::Vector, 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 = "setRawPredictionCol")]
+ fn set_raw_prediction_col<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "rawPredictionCol", Kind::Str, value)
+ }
+
+ #[pyo3(name = "setThresholds")]
+ fn set_thresholds<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "thresholds", Kind::FloatList, value)
+ }
+
+ fn fit(slf: &Bound<'_, Self>, dataset: &Bound<'_, PyAny>) ->
PyResult<PyMLModel> {
+ fit_native(slf, dataset, None)
+ }
+}
+
+/// Native OneVsRest.
+#[pyclass(name = "OneVsRest", module = "pyspark.ml.connect.classification")]
+pub struct PyOneVsRest {
+ inner: OneVsRest,
+ unsendable: Vec<&'static str>,
+ classifier: Option<Py<PyAny>>,
+}
+
+const ONE_VS_REST_PARAMS: &[(&str, Kind)] = &[
+ ("featuresCol", Kind::Str),
+ ("labelCol", Kind::Str),
+ ("predictionCol", Kind::Str),
+ ("rawPredictionCol", Kind::Str),
+ ("weightCol", Kind::Str),
+ ("parallelism", Kind::Int),
+];
+
+#[pymethods]
+impl PyOneVsRest {
+ #[new]
+ #[pyo3(signature = (*args, **kwargs), text_signature = "(*,
featuresCol='features', labelCol='label', predictionCol='prediction',
rawPredictionCol='rawPrediction', classifier=None, weightCol=None,
parallelism=1)")]
+ fn new(args: &Bound<'_, PyTuple>, kwargs: Option<&Bound<'_, PyDict>>) ->
PyResult<Self> {
+ let mut this = Self {
+ inner: OneVsRest::new(),
+ unsendable: Vec::new(),
+ classifier: None,
+ };
+ let remaining = kwargs.map(|kw| kw.copy()).transpose()?;
+ if let Some(kw) = &remaining {
+ if let Some(classifier) = kw.get_item("classifier")? {
+ if !classifier.is_none() {
+ native_classifier(&classifier, false)?;
+ this.classifier = Some(classifier.unbind());
+ }
+ kw.del_item("classifier")?;
+ }
+ }
+ init_params(
+ &mut this,
+ "OneVsRest",
+ &[],
+ ONE_VS_REST_PARAMS,
+ args,
+ remaining.as_ref(),
+ )?;
+ Ok(this)
+ }
+
+ #[pyo3(name = "setFeaturesCol")]
+ fn set_feature_col<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "featuresCol", Kind::Str, value)
+ }
+
+ #[pyo3(name = "setLabelCol")]
+ fn set_label_col<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "labelCol", Kind::Str, value)
+ }
+
+ #[pyo3(name = "setPredictionCol")]
+ fn set_prediction_col<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "predictionCol", Kind::Str, value)
+ }
+
+ #[pyo3(name = "setRawPredictionCol")]
+ fn set_raw_prediction_col<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "rawPredictionCol", Kind::Str, value)
+ }
+
+ #[pyo3(name = "setWeightCol")]
+ fn set_weight_col<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "weightCol", Kind::Str, value)
+ }
+
+ #[pyo3(name = "setParallelism")]
+ fn set_parallelism<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "parallelism", Kind::Int, value)
+ }
+
+ #[pyo3(name = "setClassifier")]
+ fn set_classifier<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ if value.is_none() {
+ slf.try_borrow_mut()?.classifier = None;
+ } else {
+ native_classifier(value, false)?;
+ slf.try_borrow_mut()?.classifier = Some(value.clone().unbind());
+ }
+ Ok(slf)
+ }
+
+ fn fit(slf: &Bound<'_, Self>, dataset: &Bound<'_, PyAny>) ->
PyResult<PyMLModel> {
+ let classifier = slf
+ .try_borrow()?
+ .classifier
+ .as_ref()
+ .map(|x| x.clone_ref(slf.py()))
+ .ok_or_else(|| PyValueError::new_err("OneVsRest requires a native
classifier"))?;
+ let classifier = native_classifier(classifier.bind(slf.py()), true)?;
+ {
+ let mut this = slf.try_borrow_mut()?;
+ if !classifier.supports_weight()
+ && this.inner.weight_col().is_some_and(|s| !s.is_empty())
+ {
+ slf.py().import("warnings")?.call_method1(
+ "warn",
+ ("weightCol is ignored, as it is not supported by this
classifier",),
+ )?;
+ }
+ this.inner = this.inner.clone().set_classifier(classifier);
+ }
+ fit_native(slf, dataset, None)
+ }
+}
+
+// Snapshot at fit time, retaining PySpark's reference semantics for a
classifier
+// mutated after it was assigned to OneVsRest.
+fn native_classifier(value: &Bound<'_, PyAny>, validate_params: bool) ->
PyResult<Classifier> {
+ if let Ok(value) = value.cast::<PyLogisticRegression>() {
+ return Ok(if validate_params {
+ snapshot(value)?
+ } else {
+ value.try_borrow()?.inner.clone()
+ }
+ .into());
+ }
+ if let Ok(value) = value.cast::<PyLinearSVC>() {
+ return Ok(if validate_params {
+ snapshot(value)?
+ } else {
+ value.try_borrow()?.inner.clone()
+ }
+ .into());
+ }
+ if let Ok(value) = value.cast::<PyDecisionTreeClassifier>() {
+ return Ok(if validate_params {
+ snapshot(value)?
+ } else {
+ value.try_borrow()?.inner.clone()
+ }
+ .into());
+ }
+ if let Ok(value) = value.cast::<PyRandomForestClassifier>() {
+ return Ok(if validate_params {
+ snapshot(value)?
+ } else {
+ value.try_borrow()?.inner.clone()
+ }
+ .into());
+ }
+ if let Ok(value) = value.cast::<PyGBTClassifier>() {
+ return Ok(if validate_params {
+ snapshot(value)?
+ } else {
+ value.try_borrow()?.inner.clone()
+ }
+ .into());
+ }
+ if let Ok(value) = value.cast::<PyNaiveBayes>() {
+ return Ok(if validate_params {
+ snapshot(value)?
+ } else {
+ value.try_borrow()?.inner.clone()
+ }
+ .into());
+ }
+ if let Ok(value) = value.cast::<PyFMClassifier>() {
+ return Ok(if validate_params {
+ snapshot(value)?
+ } else {
+ value.try_borrow()?.inner.clone()
+ }
+ .into());
+ }
+ if let Ok(value) = value.cast::<PyMultilayerPerceptronClassifier>() {
+ return Ok(if validate_params {
+ snapshot(value)?
+ } else {
+ value.try_borrow()?.inner.clone()
+ }
+ .into());
+ }
+ Err(PyTypeError::new_err("classifier must be a native classification
estimator from pyspark.ml.connect.classification"))
+}
+
/// Linear regression backed by Spark Connect's JVM ML API.
#[pyclass(name = "LinearRegression", module = "pyspark.ml.connect.regression")]
pub struct PyLinearRegression {
@@ -3924,6 +4510,9 @@ native!(
PyVectorAssembler => VectorAssembler,
PyLogisticRegression => LogisticRegression,
PyLinearSVC => LinearSVC,
+ PyFMClassifier => FMClassifier,
+ PyMultilayerPerceptronClassifier => MultilayerPerceptronClassifier,
+ PyOneVsRest => OneVsRest,
PyLinearRegression => LinearRegression,
PyGeneralizedLinearRegression => GeneralizedLinearRegression,
PyDecisionTreeClassifier => DecisionTreeClassifier,
diff --git a/crates/spark-connect/src/ml.rs b/crates/spark-connect/src/ml.rs
index a8740bba..6ee230cf 100644
--- a/crates/spark-connect/src/ml.rs
+++ b/crates/spark-connect/src/ml.rs
@@ -18,6 +18,113 @@ use crate::plan::{LogicalPlan, RelationOwner};
use crate::session::SparkSession;
use crate::types::DataType;
+/// A dense or sparse ML vector used as an estimator parameter.
+#[derive(Debug, Clone, PartialEq)]
+pub enum MlVector {
+ Dense(Vec<f64>),
+ Sparse {
+ size: i32,
+ indices: Vec<i32>,
+ values: Vec<f64>,
+ },
+}
+
+impl From<Vec<f64>> for MlVector {
+ fn from(values: Vec<f64>) -> Self {
+ Self::Dense(values)
+ }
+}
+
+impl<const N: usize> From<[f64; N]> for MlVector {
+ fn from(values: [f64; N]) -> Self {
+ Self::Dense(values.into())
+ }
+}
+
+impl MlVector {
+ #[allow(deprecated)] // PySpark's ML serializer uses struct_type for
vector UDTs.
+ fn to_literal(&self) -> proto::expression::Literal {
+ use proto::expression::literal::{specialized_array::ValueType as A,
LiteralType as L};
+ let lit = |value| proto::expression::Literal {
+ literal_type: Some(value),
+ ..Default::default()
+ };
+ let null = || lit(L::Null(DataType::Null.to_proto()));
+ let doubles = |values: Vec<f64>| {
+ lit(L::SpecializedArray(
+ proto::expression::literal::SpecializedArray {
+ value_type: Some(A::Doubles(proto::Doubles { values })),
+ },
+ ))
+ };
+ let elements = match self {
+ Self::Dense(values) => vec![lit(L::Byte(1)), null(), null(),
doubles(values.clone())],
+ Self::Sparse {
+ size,
+ indices,
+ values,
+ } => vec![
+ lit(L::Byte(0)),
+ lit(L::Integer(*size)),
+ lit(L::SpecializedArray(
+ proto::expression::literal::SpecializedArray {
+ value_type: Some(A::Ints(proto::Ints {
+ values: indices.clone(),
+ })),
+ },
+ )),
+ doubles(values.clone()),
+ ],
+ };
+ lit(L::Struct(proto::expression::literal::Struct {
+ struct_type: Some(proto::DataType {
+ kind: Some(proto::data_type::Kind::Udt(Box::new(
+ proto::data_type::Udt {
+ r#type: "udt".into(),
+ jvm_class:
Some("org.apache.spark.ml.linalg.VectorUDT".into()),
+ ..Default::default()
+ },
+ ))),
+ }),
+ elements,
+ }))
+ }
+
+ fn from_literal(value: &proto::expression::literal::LiteralType) ->
Option<Self> {
+ use proto::expression::literal::{specialized_array::ValueType as A,
LiteralType as L};
+ let L::Struct(value) = value else {
+ return None;
+ };
+ let fields = &value.elements;
+ let L::SpecializedArray(array) = fields.get(3)?.literal_type.as_ref()?
else {
+ return None;
+ };
+ let A::Doubles(values) = array.value_type.as_ref()? else {
+ return None;
+ };
+ match fields.first()?.literal_type.as_ref()? {
+ L::Byte(1) => Some(Self::Dense(values.values.clone())),
+ L::Byte(0) => {
+ let L::Integer(size) = fields.get(1)?.literal_type.as_ref()?
else {
+ return None;
+ };
+ let L::SpecializedArray(array) =
fields.get(2)?.literal_type.as_ref()? else {
+ return None;
+ };
+ let A::Ints(indices) = array.value_type.as_ref()? else {
+ return None;
+ };
+ Some(Self::Sparse {
+ size: *size,
+ indices: indices.values.clone(),
+ values: values.values.clone(),
+ })
+ }
+ _ => None,
+ }
+ }
+}
+
/// ML parameter handling: stores name -> literal value mappings.
///
/// Mirrors the structure of parameter handling in `pyspark.ml.param.Params`.
@@ -123,6 +230,65 @@ impl Params {
self
}
+ /// Set a parameter to an integer array, preserving PySpark's literal
width.
+ #[allow(deprecated)] // Matches the array representation of PySpark's ML
parameters.
+ pub fn set_param_int_array(
+ mut self,
+ name: &str,
+ values: impl IntoIterator<Item = i64>,
+ ) -> Self {
+ use proto::expression::literal::LiteralType as L;
+ let values: Vec<i64> = values.into_iter().collect();
+ let narrow = values.iter().all(|v| i32::try_from(*v).is_ok());
+ let elements = values
+ .into_iter()
+ .map(|v| proto::expression::Literal {
+ literal_type: Some(if narrow {
+ L::Integer(v as i32)
+ } else {
+ L::Long(v)
+ }),
+ ..Default::default()
+ })
+ .collect();
+ let literal = proto::expression::Literal {
+ literal_type: Some(L::Array(proto::expression::literal::Array {
+ element_type: Some(
+ if narrow {
+ DataType::Integer
+ } else {
+ DataType::Long
+ }
+ .to_proto(),
+ ),
+ elements,
+ })),
+ ..Default::default()
+ };
+ self.params.insert(
+ name.into(),
+ proto::Expression {
+ expr_type: Some(proto::expression::ExprType::Literal(literal)),
+ ..Default::default()
+ },
+ );
+ self
+ }
+
+ /// Set a vector parameter using Spark's VectorUDT representation.
+ pub fn set_param_vector(mut self, name: &str, value: impl Into<MlVector>)
-> Self {
+ self.params.insert(
+ name.into(),
+ proto::Expression {
+ expr_type: Some(proto::expression::ExprType::Literal(
+ value.into().to_literal(),
+ )),
+ ..Default::default()
+ },
+ );
+ self
+ }
+
/// Set a parameter to a double value.
pub fn set_param_double(mut self, name: &str, value: f64) -> Self {
let mut literal = proto::Expression::default();
@@ -1534,13 +1700,788 @@ impl LinearSVC {
}
}
-impl Default for LinearSVC {
- fn default() -> Self {
- Self::new()
- }
+impl Default for LinearSVC {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl Estimator for LinearSVC {
+ fn operator(&self) -> &MlOperator {
+ &self.operator
+ }
+ fn operator_mut(&mut self) -> &mut MlOperator {
+ &mut self.operator
+ }
+ fn params(&self) -> &Params {
+ &self.params
+ }
+ fn params_mut(&mut self) -> &mut Params {
+ &mut self.params
+ }
+
+ fn fit_impl(&mut self, df: &DataFrame) ->
spark_connect_core::error::Result<Box<dyn Model>> {
+ let info = fit_via_command(&self.operator, &self.params, df)?;
+ Ok(Box::new(self.model_from_info(info, &df.session)?))
+ }
+}
+
+/// A LinearSVC model fitted by Spark Connect and cached for its fitting
session.
+/// Obtain it through [`Estimator::fit`]; prediction uses the cached model
object,
+/// which the server deletes once no model, clone or transformed DataFrame
refers to it.
+#[derive(Debug, Clone)]
+pub struct LinearSVCModel {
+ operator: MlOperator,
+ params: Params,
+ cached: CachedModel,
+}
+
+impl Transformer for LinearSVCModel {
+ fn operator(&self) -> &MlOperator {
+ &self.operator
+ }
+ fn operator_mut(&mut self) -> &mut MlOperator {
+ &mut self.operator
+ }
+ fn params(&self) -> &Params {
+ &self.params
+ }
+ fn params_mut(&mut self) -> &mut Params {
+ &mut self.params
+ }
+
+ fn build_ml_relation(
+ &self,
+ input: &DataFrame,
+ ) -> spark_connect_core::error::Result<proto::MlRelation> {
+ self.cached.build_ml_relation(input, &self.params)
+ }
+
+ fn transform_impl(&mut self, df: &DataFrame) ->
spark_connect_core::error::Result<DataFrame> {
+ self.cached.transform(df, &self.params)
+ }
+}
+
+impl Model for LinearSVCModel {
+ fn clone_box(&self) -> Box<dyn Model> {
+ Box::new(self.clone())
+ }
+}
+
+/// FMClassifier using Spark's JVM implementation and ML vectors.
+/// Unset parameters use Spark's defaults.
+#[derive(Debug, Clone)]
+pub struct FMClassifier {
+ operator: MlOperator,
+ params: Params,
+}
+
+impl FMClassifier {
+ pub fn new() -> Self {
+ Self {
+ operator: MlOperator::new(
+ "org.apache.spark.ml.classification.FMClassifier",
+ OperatorType::Estimator,
+ ),
+ params: Params::new(),
+ }
+ }
+
+ /// Set `featuresCol`.
+ pub fn set_feature_col(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("featuresCol", value);
+ self
+ }
+
+ /// Get `featuresCol` (default: "features").
+ pub fn feature_col(&self) -> &str {
+ self.params.string_or("featuresCol", "features")
+ }
+
+ /// Set `labelCol`.
+ pub fn set_label_col(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("labelCol", value);
+ self
+ }
+
+ /// Get `labelCol` (default: "label").
+ pub fn label_col(&self) -> &str {
+ self.params.string_or("labelCol", "label")
+ }
+
+ /// Set `predictionCol`.
+ pub fn set_prediction_col(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("predictionCol", value);
+ self
+ }
+
+ /// Get `predictionCol` (default: "prediction").
+ pub fn prediction_col(&self) -> &str {
+ self.params.string_or("predictionCol", "prediction")
+ }
+
+ /// Set `probabilityCol`.
+ pub fn set_probability_col(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("probabilityCol", value);
+ self
+ }
+
+ /// Get `probabilityCol` (default: "probability").
+ pub fn probability_col(&self) -> &str {
+ self.params.string_or("probabilityCol", "probability")
+ }
+
+ /// Set `rawPredictionCol`.
+ pub fn set_raw_prediction_col(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("rawPredictionCol", value);
+ self
+ }
+
+ /// Get `rawPredictionCol` (default: "rawPrediction").
+ pub fn raw_prediction_col(&self) -> &str {
+ self.params.string_or("rawPredictionCol", "rawPrediction")
+ }
+
+ /// Set `factorSize`.
+ pub fn set_factor_size(mut self, value: i32) -> Self {
+ self.params = self.params.set_param_int32("factorSize", value);
+ self
+ }
+
+ /// Get `factorSize` (default: 8).
+ pub fn factor_size(&self) -> i32 {
+ self.params.int_or("factorSize", 8)
+ }
+
+ /// Set `fitIntercept`.
+ pub fn set_fit_intercept(mut self, value: bool) -> Self {
+ self.params = self.params.set_param_bool("fitIntercept", value);
+ self
+ }
+
+ /// Get `fitIntercept` (default: true).
+ pub fn fit_intercept(&self) -> bool {
+ self.params.bool_or("fitIntercept", true)
+ }
+
+ /// Set `fitLinear`.
+ pub fn set_fit_linear(mut self, value: bool) -> Self {
+ self.params = self.params.set_param_bool("fitLinear", value);
+ self
+ }
+
+ /// Get `fitLinear` (default: true).
+ pub fn fit_linear(&self) -> bool {
+ self.params.bool_or("fitLinear", true)
+ }
+
+ /// Set `regParam`.
+ pub fn set_reg_param(mut self, value: f64) -> Self {
+ self.params = self.params.set_param_double("regParam", value);
+ self
+ }
+
+ /// Get `regParam` (default: 0.0).
+ pub fn reg_param(&self) -> f64 {
+ self.params.double_or("regParam", 0.0)
+ }
+
+ /// Set `miniBatchFraction`.
+ pub fn set_mini_batch_fraction(mut self, value: f64) -> Self {
+ self.params = self.params.set_param_double("miniBatchFraction", value);
+ self
+ }
+
+ /// Get `miniBatchFraction` (default: 1.0).
+ pub fn mini_batch_fraction(&self) -> f64 {
+ self.params.double_or("miniBatchFraction", 1.0)
+ }
+
+ /// Set `initStd`.
+ pub fn set_init_std(mut self, value: f64) -> Self {
+ self.params = self.params.set_param_double("initStd", value);
+ self
+ }
+
+ /// Get `initStd` (default: 0.01).
+ pub fn init_std(&self) -> f64 {
+ self.params.double_or("initStd", 0.01)
+ }
+
+ /// Set `maxIter`.
+ pub fn set_max_iter(mut self, value: i32) -> Self {
+ self.params = self.params.set_param_int32("maxIter", value);
+ self
+ }
+
+ /// Get `maxIter` (default: 100).
+ pub fn max_iter(&self) -> i32 {
+ self.params.int_or("maxIter", 100)
+ }
+
+ /// Set `stepSize`.
+ pub fn set_step_size(mut self, value: f64) -> Self {
+ self.params = self.params.set_param_double("stepSize", value);
+ self
+ }
+
+ /// Get `stepSize` (default: 1.0).
+ pub fn step_size(&self) -> f64 {
+ self.params.double_or("stepSize", 1.0)
+ }
+
+ /// Set `tol`.
+ pub fn set_tol(mut self, value: f64) -> Self {
+ self.params = self.params.set_param_double("tol", value);
+ self
+ }
+
+ /// Get `tol` (default: 1e-06).
+ pub fn tol(&self) -> f64 {
+ self.params.double_or("tol", 1e-06)
+ }
+
+ /// Set `solver`.
+ pub fn set_solver(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("solver", value);
+ self
+ }
+
+ /// Get `solver` (default: "adamW").
+ pub fn solver(&self) -> &str {
+ self.params.string_or("solver", "adamW")
+ }
+
+ /// Set `thresholds`.
+ pub fn set_thresholds(mut self, value: impl IntoIterator<Item = f64>) ->
Self {
+ self.params = self.params.set_param_double_array("thresholds", value);
+ self
+ }
+
+ /// Get `thresholds` (unset by default).
+ pub fn thresholds(&self) -> Option<Vec<f64>> {
+ self.params.double_array_opt("thresholds")
+ }
+
+ /// Set `seed`.
+ pub fn set_seed(mut self, value: i64) -> Self {
+ self.params = self.params.set_param_int_narrow("seed", value);
+ self
+ }
+
+ /// Get `seed` (unset by default).
+ pub fn seed(&self) -> Option<i64> {
+ self.params.long_opt("seed")
+ }
+
+ fn model_from_info(
+ &self,
+ info: proto::ml_command_result::MlOperatorInfo,
+ session: &SparkSession,
+ ) -> spark_connect_core::error::Result<FMClassificationModel> {
+ let cached = CachedModel::from_info(&info, session, "FMClassifier")?;
+ Ok(FMClassificationModel {
+ operator: MlOperator::with_uid(
+ "org.apache.spark.ml.classification.FMClassificationModel",
+ info.uid.as_deref().unwrap_or(&self.operator.uid),
+ OperatorType::Model,
+ ),
+ params: self.params.clone(),
+ cached,
+ })
+ }
+}
+
+impl Default for FMClassifier {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl Estimator for FMClassifier {
+ fn operator(&self) -> &MlOperator {
+ &self.operator
+ }
+ fn operator_mut(&mut self) -> &mut MlOperator {
+ &mut self.operator
+ }
+ fn params(&self) -> &Params {
+ &self.params
+ }
+ fn params_mut(&mut self) -> &mut Params {
+ &mut self.params
+ }
+
+ fn fit_impl(&mut self, df: &DataFrame) ->
spark_connect_core::error::Result<Box<dyn Model>> {
+ let info = fit_via_command(&self.operator, &self.params, df)?;
+ Ok(Box::new(self.model_from_info(info, &df.session)?))
+ }
+}
+
+/// A FMClassifier model fitted by Spark Connect.
+///
+/// Obtain it through [`Estimator::fit`]. The model, its clones and transformed
+/// DataFrames retain the server-cached object until the last owner is dropped.
+#[derive(Debug, Clone)]
+pub struct FMClassificationModel {
+ operator: MlOperator,
+ params: Params,
+ cached: CachedModel,
+}
+
+impl Transformer for FMClassificationModel {
+ fn operator(&self) -> &MlOperator {
+ &self.operator
+ }
+ fn operator_mut(&mut self) -> &mut MlOperator {
+ &mut self.operator
+ }
+ fn params(&self) -> &Params {
+ &self.params
+ }
+ fn params_mut(&mut self) -> &mut Params {
+ &mut self.params
+ }
+
+ fn build_ml_relation(
+ &self,
+ input: &DataFrame,
+ ) -> spark_connect_core::error::Result<proto::MlRelation> {
+ self.cached.build_ml_relation(input, &self.params)
+ }
+
+ fn transform_impl(&mut self, df: &DataFrame) ->
spark_connect_core::error::Result<DataFrame> {
+ self.cached.transform(df, &self.params)
+ }
+}
+
+impl Model for FMClassificationModel {
+ fn clone_box(&self) -> Box<dyn Model> {
+ Box::new(self.clone())
+ }
+}
+
+/// MultilayerPerceptronClassifier using Spark's JVM implementation and ML
vectors.
+/// Unset parameters use Spark's defaults.
+#[derive(Debug, Clone)]
+pub struct MultilayerPerceptronClassifier {
+ operator: MlOperator,
+ params: Params,
+}
+
+impl MultilayerPerceptronClassifier {
+ pub fn new() -> Self {
+ Self {
+ operator: MlOperator::new(
+
"org.apache.spark.ml.classification.MultilayerPerceptronClassifier",
+ OperatorType::Estimator,
+ ),
+ params: Params::new(),
+ }
+ }
+
+ /// Set `featuresCol`.
+ pub fn set_feature_col(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("featuresCol", value);
+ self
+ }
+
+ /// Get `featuresCol` (default: "features").
+ pub fn feature_col(&self) -> &str {
+ self.params.string_or("featuresCol", "features")
+ }
+
+ /// Set `labelCol`.
+ pub fn set_label_col(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("labelCol", value);
+ self
+ }
+
+ /// Get `labelCol` (default: "label").
+ pub fn label_col(&self) -> &str {
+ self.params.string_or("labelCol", "label")
+ }
+
+ /// Set `predictionCol`.
+ pub fn set_prediction_col(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("predictionCol", value);
+ self
+ }
+
+ /// Get `predictionCol` (default: "prediction").
+ pub fn prediction_col(&self) -> &str {
+ self.params.string_or("predictionCol", "prediction")
+ }
+
+ /// Set `maxIter`.
+ pub fn set_max_iter(mut self, value: i32) -> Self {
+ self.params = self.params.set_param_int32("maxIter", value);
+ self
+ }
+
+ /// Get `maxIter` (default: 100).
+ pub fn max_iter(&self) -> i32 {
+ self.params.int_or("maxIter", 100)
+ }
+
+ /// Set `tol`.
+ pub fn set_tol(mut self, value: f64) -> Self {
+ self.params = self.params.set_param_double("tol", value);
+ self
+ }
+
+ /// Get `tol` (default: 1e-06).
+ pub fn tol(&self) -> f64 {
+ self.params.double_or("tol", 1e-06)
+ }
+
+ /// Set `seed`.
+ pub fn set_seed(mut self, value: i64) -> Self {
+ self.params = self.params.set_param_int_narrow("seed", value);
+ self
+ }
+
+ /// Get `seed` (unset by default).
+ pub fn seed(&self) -> Option<i64> {
+ self.params.long_opt("seed")
+ }
+
+ /// Set `layers`.
+ pub fn set_layers(mut self, value: impl IntoIterator<Item = i32>) -> Self {
+ self.params = self
+ .params
+ .set_param_int_array("layers", value.into_iter().map(i64::from));
+ self
+ }
+
+ /// Get `layers` (unset by default).
+ pub fn layers(&self) -> Option<Vec<i32>> {
+ self.params
+ .array_opt("layers")?
+ .iter()
+ .map(|lit| match lit.literal_type.as_ref()? {
+ proto::expression::literal::LiteralType::Integer(v) =>
Some(*v),
+ proto::expression::literal::LiteralType::Long(v) => Some(*v as
i32),
+ _ => None,
+ })
+ .collect()
+ }
+
+ /// Set `blockSize`.
+ pub fn set_block_size(mut self, value: i32) -> Self {
+ self.params = self.params.set_param_int32("blockSize", value);
+ self
+ }
+
+ /// Get `blockSize` (default: 128).
+ pub fn block_size(&self) -> i32 {
+ self.params.int_or("blockSize", 128)
+ }
+
+ /// Set `stepSize`.
+ pub fn set_step_size(mut self, value: f64) -> Self {
+ self.params = self.params.set_param_double("stepSize", value);
+ self
+ }
+
+ /// Get `stepSize` (default: 0.03).
+ pub fn step_size(&self) -> f64 {
+ self.params.double_or("stepSize", 0.03)
+ }
+
+ /// Set `solver`.
+ pub fn set_solver(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("solver", value);
+ self
+ }
+
+ /// Get `solver` (default: "l-bfgs").
+ pub fn solver(&self) -> &str {
+ self.params.string_or("solver", "l-bfgs")
+ }
+
+ /// Set `initialWeights`.
+ pub fn set_initial_weights(mut self, value: impl Into<MlVector>) -> Self {
+ self.params = self.params.set_param_vector("initialWeights", value);
+ self
+ }
+
+ /// Get `initialWeights` (unset by default).
+ pub fn initial_weights(&self) -> Option<MlVector> {
+ MlVector::from_literal(self.params.literal("initialWeights")?)
+ }
+
+ /// Set `probabilityCol`.
+ pub fn set_probability_col(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("probabilityCol", value);
+ self
+ }
+
+ /// Get `probabilityCol` (default: "probability").
+ pub fn probability_col(&self) -> &str {
+ self.params.string_or("probabilityCol", "probability")
+ }
+
+ /// Set `rawPredictionCol`.
+ pub fn set_raw_prediction_col(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("rawPredictionCol", value);
+ self
+ }
+
+ /// Get `rawPredictionCol` (default: "rawPrediction").
+ pub fn raw_prediction_col(&self) -> &str {
+ self.params.string_or("rawPredictionCol", "rawPrediction")
+ }
+
+ /// Set `thresholds`.
+ pub fn set_thresholds(mut self, value: impl IntoIterator<Item = f64>) ->
Self {
+ self.params = self.params.set_param_double_array("thresholds", value);
+ self
+ }
+
+ /// Get `thresholds` (unset by default).
+ pub fn thresholds(&self) -> Option<Vec<f64>> {
+ self.params.double_array_opt("thresholds")
+ }
+
+ fn model_from_info(
+ &self,
+ info: proto::ml_command_result::MlOperatorInfo,
+ session: &SparkSession,
+ ) ->
spark_connect_core::error::Result<MultilayerPerceptronClassificationModel> {
+ let cached = CachedModel::from_info(&info, session,
"MultilayerPerceptronClassifier")?;
+ Ok(MultilayerPerceptronClassificationModel {
+ operator: MlOperator::with_uid(
+
"org.apache.spark.ml.classification.MultilayerPerceptronClassificationModel",
+ info.uid.as_deref().unwrap_or(&self.operator.uid),
+ OperatorType::Model,
+ ),
+ params: self.params.clone(),
+ cached,
+ })
+ }
+}
+
+impl Default for MultilayerPerceptronClassifier {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl Estimator for MultilayerPerceptronClassifier {
+ fn operator(&self) -> &MlOperator {
+ &self.operator
+ }
+ fn operator_mut(&mut self) -> &mut MlOperator {
+ &mut self.operator
+ }
+ fn params(&self) -> &Params {
+ &self.params
+ }
+ fn params_mut(&mut self) -> &mut Params {
+ &mut self.params
+ }
+
+ fn fit_impl(&mut self, df: &DataFrame) ->
spark_connect_core::error::Result<Box<dyn Model>> {
+ let info = fit_via_command(&self.operator, &self.params, df)?;
+ Ok(Box::new(self.model_from_info(info, &df.session)?))
+ }
+}
+
+/// A MultilayerPerceptronClassifier model fitted by Spark Connect.
+///
+/// Obtain it through [`Estimator::fit`]. The model, its clones and transformed
+/// DataFrames retain the server-cached object until the last owner is dropped.
+#[derive(Debug, Clone)]
+pub struct MultilayerPerceptronClassificationModel {
+ operator: MlOperator,
+ params: Params,
+ cached: CachedModel,
+}
+
+impl Transformer for MultilayerPerceptronClassificationModel {
+ fn operator(&self) -> &MlOperator {
+ &self.operator
+ }
+ fn operator_mut(&mut self) -> &mut MlOperator {
+ &mut self.operator
+ }
+ fn params(&self) -> &Params {
+ &self.params
+ }
+ fn params_mut(&mut self) -> &mut Params {
+ &mut self.params
+ }
+
+ fn build_ml_relation(
+ &self,
+ input: &DataFrame,
+ ) -> spark_connect_core::error::Result<proto::MlRelation> {
+ self.cached.build_ml_relation(input, &self.params)
+ }
+
+ fn transform_impl(&mut self, df: &DataFrame) ->
spark_connect_core::error::Result<DataFrame> {
+ self.cached.transform(df, &self.params)
+ }
+}
+
+impl Model for MultilayerPerceptronClassificationModel {
+ fn clone_box(&self) -> Box<dyn Model> {
+ Box::new(self.clone())
+ }
+}
+
+/// A native binary classifier that can be fitted independently for each
OneVsRest class.
+#[derive(Debug, Clone)]
+pub enum Classifier {
+ LogisticRegression(LogisticRegression),
+ LinearSVC(LinearSVC),
+ DecisionTreeClassifier(DecisionTreeClassifier),
+ RandomForestClassifier(RandomForestClassifier),
+ GBTClassifier(GBTClassifier),
+ NaiveBayes(NaiveBayes),
+ FMClassifier(FMClassifier),
+ MultilayerPerceptronClassifier(MultilayerPerceptronClassifier),
+}
+
+macro_rules! classifier_from {
+ ($($name:ident),* $(,)?) => {$(
+ impl From<$name> for Classifier {
+ fn from(value: $name) -> Self { Self::$name(value) }
+ }
+ )*};
+}
+classifier_from!(
+ LogisticRegression,
+ LinearSVC,
+ DecisionTreeClassifier,
+ RandomForestClassifier,
+ GBTClassifier,
+ NaiveBayes,
+ FMClassifier,
+ MultilayerPerceptronClassifier
+);
+
+impl Classifier {
+ fn estimator_mut(&mut self) -> &mut dyn Estimator {
+ match self {
+ Self::LogisticRegression(x) => x,
+ Self::LinearSVC(x) => x,
+ Self::DecisionTreeClassifier(x) => x,
+ Self::RandomForestClassifier(x) => x,
+ Self::GBTClassifier(x) => x,
+ Self::NaiveBayes(x) => x,
+ Self::FMClassifier(x) => x,
+ Self::MultilayerPerceptronClassifier(x) => x,
+ }
+ }
+
+ /// Whether this classifier accepts instance weights.
+ pub fn supports_weight(&self) -> bool {
+ !matches!(
+ self,
+ Self::FMClassifier(_) | Self::MultilayerPerceptronClassifier(_)
+ )
+ }
+}
+
+/// Multiclass reduction that fits one native binary classifier per class.
+///
+/// As in PySpark, class indices run from zero through the maximum label. Fits
use
+/// independent snapshots of the base classifier and at most `parallelism`
threads.
+#[derive(Debug, Clone)]
+pub struct OneVsRest {
+ operator: MlOperator,
+ params: Params,
+ classifier: Option<Classifier>,
+}
+
+impl OneVsRest {
+ pub fn new() -> Self {
+ Self {
+ operator: MlOperator::new(
+ "org.apache.spark.ml.classification.OneVsRest",
+ OperatorType::Estimator,
+ ),
+ params: Params::new(),
+ classifier: None,
+ }
+ }
+
+ /// Set the native binary classifier. Fits do not mutate the supplied
estimator.
+ pub fn set_classifier(mut self, classifier: impl Into<Classifier>) -> Self
{
+ self.classifier = Some(classifier.into());
+ self
+ }
+
+ pub fn classifier(&self) -> Option<&Classifier> {
+ self.classifier.as_ref()
+ }
+ pub fn set_feature_col(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("featuresCol", value);
+ self
+ }
+ pub fn feature_col(&self) -> &str {
+ self.params.string_or("featuresCol", "features")
+ }
+ pub fn set_label_col(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("labelCol", value);
+ self
+ }
+ pub fn label_col(&self) -> &str {
+ self.params.string_or("labelCol", "label")
+ }
+ pub fn set_prediction_col(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("predictionCol", value);
+ self
+ }
+ pub fn prediction_col(&self) -> &str {
+ self.params.string_or("predictionCol", "prediction")
+ }
+ pub fn set_raw_prediction_col(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("rawPredictionCol", value);
+ self
+ }
+ pub fn raw_prediction_col(&self) -> &str {
+ self.params.string_or("rawPredictionCol", "rawPrediction")
+ }
+ pub fn set_weight_col(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("weightCol", value);
+ self
+ }
+ pub fn weight_col(&self) -> Option<&str> {
+ self.params.string_opt("weightCol")
+ }
+ pub fn set_parallelism(mut self, value: i32) -> Self {
+ self.params = self.params.set_param_int32("parallelism", value);
+ self
+ }
+ pub fn parallelism(&self) -> i32 {
+ self.params.int_or("parallelism", 1)
+ }
+}
+
+impl Default for OneVsRest {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+// Release only the cache created for this fit, including after a failed
binary fit.
+struct OneVsRestTrainingCache(Option<DataFrame>);
+impl Drop for OneVsRestTrainingCache {
+ fn drop(&mut self) {
+ if let Some(df) = &self.0 {
+ let _ = df.unpersist(false);
+ }
+ }
+}
+
+fn ml_exact_column(name: &str) -> crate::column::Column {
+ crate::column::col(&format!("`{}`", name.replace('`', "``")))
}
-impl Estimator for LinearSVC {
+impl Estimator for OneVsRest {
fn operator(&self) -> &MlOperator {
&self.operator
}
@@ -1553,24 +2494,275 @@ impl Estimator for LinearSVC {
fn params_mut(&mut self) -> &mut Params {
&mut self.params
}
-
fn fit_impl(&mut self, df: &DataFrame) ->
spark_connect_core::error::Result<Box<dyn Model>> {
- let info = fit_via_command(&self.operator, &self.params, df)?;
- Ok(Box::new(self.model_from_info(info, &df.session)?))
+ use crate::column::{lit_double, when};
+ use std::sync::atomic::{AtomicUsize, Ordering};
+ for name in [
+ "featuresCol",
+ "labelCol",
+ "predictionCol",
+ "rawPredictionCol",
+ "parallelism",
+ ] {
+ if matches!(
+ self.params.literal(name),
+ Some(proto::expression::literal::LiteralType::Null(_))
+ ) {
+ return Err(SparkError::value_msg(format!(
+ "OneVsRest parameter {name} cannot be null"
+ )));
+ }
+ }
+ let classifier = self
+ .classifier
+ .as_ref()
+ .ok_or_else(|| SparkError::value_msg("OneVsRest requires a native
classifier"))?;
+ if self.parallelism() < 1 {
+ return Err(SparkError::value_msg("parallelism must be at least
1"));
+ }
+ let rows = df
+ .agg([crate::functions::max(
+ ml_exact_column(self.label_col()).cast(DataType::Double),
+ )])
+ .collect()?;
+ let max = rows
+ .first()
+ .and_then(|r| r.get(0))
+ .and_then(|v| v.as_f64())
+ .ok_or_else(|| {
+ SparkError::value_msg("OneVsRest cannot fit an empty or
null-labeled dataset")
+ })?;
+ if !max.is_finite() || max < 0.0 || max >= i32::MAX as f64 {
+ return Err(SparkError::value_msg(
+ "OneVsRest requires a finite nonnegative maximum class label",
+ ));
+ }
+ let count = max as usize + 1;
+ let weight = self
+ .weight_col()
+ .filter(|name| !name.is_empty() && classifier.supports_weight());
+ let mut columns = vec![
+ ml_exact_column(self.label_col()),
+ ml_exact_column(self.feature_col()),
+ ];
+ if let Some(weight) = weight {
+ columns.push(ml_exact_column(weight));
+ }
+ let training = df.select(columns);
+ let level = df.storage_level()?;
+ let _cache = OneVsRestTrainingCache(if !level.use_memory &&
!level.use_disk {
+ Some(training.persist(proto::StorageLevel {
+ use_memory: true,
+ use_disk: true,
+ replication: 1,
+ ..Default::default()
+ })?)
+ } else {
+ None
+ });
+ let next = AtomicUsize::new(0);
+ let results = std::thread::scope(|scope| {
+ let mut workers = Vec::new();
+ for _ in 0..(self.parallelism() as usize).min(count) {
+ let next = &next;
+ let training = &training;
+ let this = &self;
+ workers.push(scope.spawn(move || {
+ let mut results = Vec::new();
+ loop {
+ let index = next.fetch_add(1, Ordering::Relaxed);
+ if index >= count {
+ break;
+ }
+ let binary_label = format!("{}_label_{}",
this.operator.uid, index);
+ let binary = training.with_column(
+ &binary_label,
+ when(
+
ml_exact_column(this.label_col()).eq(lit_double(index as f64)),
+ lit_double(1.0),
+ )
+ .otherwise(lit_double(0.0)),
+ );
+ let mut base = classifier.clone();
+ let estimator = base.estimator_mut();
+ let mut params = std::mem::take(estimator.params_mut())
+ .set_param_string("labelCol", &binary_label)
+ .set_param_string("featuresCol",
this.feature_col())
+ .set_param_string("predictionCol",
this.prediction_col());
+ if let Some(weight) = weight {
+ params = params.set_param_string("weightCol",
weight);
+ }
+ *estimator.params_mut() = params;
+ results.push((index, estimator.fit(&binary)));
+ }
+ results
+ }));
+ }
+ let mut results = Vec::new();
+ for worker in workers {
+ results.extend(
+ worker
+ .join()
+ .map_err(|_| SparkError::connect_msg("OneVsRest worker
panicked"))?,
+ );
+ }
+ Ok::<_, SparkError>(results)
+ })?;
+ let mut results = results;
+ results.sort_by_key(|(index, _)| *index);
+ let models = results
+ .into_iter()
+ .map(|(_, model)| model)
+ .collect::<spark_connect_core::error::Result<Vec<_>>>()?;
+ Ok(Box::new(OneVsRestModel {
+ operator: MlOperator::with_uid(
+ "org.apache.spark.ml.classification.OneVsRestModel",
+ &self.operator.uid,
+ OperatorType::Model,
+ ),
+ params: self.params.clone(),
+ models,
+ session_id: df.session.session_id().to_string(),
+ }))
}
}
-/// A LinearSVC model fitted by Spark Connect and cached for its fitting
session.
-/// Obtain it through [`Estimator::fit`]; prediction uses the cached model
object,
-/// which the server deletes once no model, clone or transformed DataFrame
refers to it.
-#[derive(Debug, Clone)]
-pub struct LinearSVCModel {
+/// A composite model whose submodels remain alive through lazy transformed
DataFrames.
+pub struct OneVsRestModel {
operator: MlOperator,
params: Params,
- cached: CachedModel,
+ models: Vec<Box<dyn Model>>,
+ session_id: String,
}
-impl Transformer for LinearSVCModel {
+impl Clone for OneVsRestModel {
+ fn clone(&self) -> Self {
+ Self {
+ operator: self.operator.clone(),
+ params: self.params.clone(),
+ models: self.models.iter().map(|m| m.clone_box()).collect(),
+ session_id: self.session_id.clone(),
+ }
+ }
+}
+
+impl OneVsRestModel {
+ pub fn num_classes(&self) -> usize {
+ self.models.len()
+ }
+
+ fn transformed(&self, df: &DataFrame) ->
spark_connect_core::error::Result<DataFrame> {
+ use crate::column::{lit, Column};
+ use crate::expression::Expression;
+ use crate::functions::{array, array_append, get};
+ if df.session.session_id() != self.session_id {
+ return Err(SparkError::value_msg(
+ "A fitted ML model must transform data from its fitting
session",
+ ));
+ }
+ let original = df.columns()?;
+ let uid = Uuid::new_v4().to_string();
+ let acc = format!("{uid}_scores");
+ let raw = format!("{uid}_raw");
+ let mut result = df.clone();
+ for (index, base) in self.models.iter().enumerate() {
+ let mut model = base.clone_box();
+ let mut params = std::mem::take(model.params_mut())
+ .set_param_string(
+ "featuresCol",
+ self.params.string_or("featuresCol", "features"),
+ )
+ .set_param_string("rawPredictionCol", &raw)
+ .set_param_string("predictionCol", "");
+ if !model.operator().name.ends_with("LinearSVCModel") {
+ params = params.set_param_string("probabilityCol", "");
+ }
+ *model.params_mut() = params;
+ let transformed = model.transform(&result)?;
+ let values = Column::new(Expression::function(
+ "vector_to_array",
+ vec![
+ ml_exact_column(&raw).expression().clone(),
+ crate::column::lit_string("float64").expression().clone(),
+ ],
+ ));
+ let score = get(values, lit(1));
+ result = transformed
+ .with_column(
+ &acc,
+ if index == 0 {
+ array([score])
+ } else {
+ array_append(ml_exact_column(&acc), score)
+ },
+ )
+ .select(
+ original
+ .iter()
+ .map(|name| ml_exact_column(name))
+ .chain(std::iter::once(ml_exact_column(&acc))),
+ );
+ }
+ let raw_output = self.params.string_or("rawPredictionCol",
"rawPrediction");
+ if !raw_output.is_empty() {
+ result = result.with_column(
+ raw_output,
+ Column::new(Expression::function(
+ "array_to_vector",
+ vec![ml_exact_column(&acc).expression().clone()],
+ )),
+ );
+ }
+ let prediction = self.params.string_or("predictionCol", "prediction");
+ if !prediction.is_empty() {
+ result = result.with_column(prediction,
one_vs_rest_prediction(ml_exact_column(&acc)));
+ }
+ Ok(result.drop_columns(std::iter::empty::<Column>(), [acc]))
+ }
+}
+
+// PySpark's array_argmax ignores NaN/null, keeps the first tie and returns -1
+// when no score exceeds negative infinity.
+fn one_vs_rest_prediction(scores: crate::column::Column) ->
crate::column::Column {
+ use crate::column::{lit, lit_double, when};
+ use crate::functions::{aggregate_with_finish, r#struct};
+ aggregate_with_finish(
+ scores,
+ r#struct([
+ lit_double(f64::NEG_INFINITY).alias("v"),
+ lit(-1).alias("i"),
+ lit(0).alias("j"),
+ ]),
+ |args| {
+ let value = args[1].clone();
+ let best = args[0].clone().get_field("v");
+ let index = args[0].clone().get_field("i");
+ let current = args[0].clone().get_field("j");
+ when(
+ value
+ .clone()
+ .is_nan()
+ .not()
+ .and(value.clone().is_null().not())
+ .and(value.clone().gt(best.clone())),
+ r#struct([
+ value.alias("v"),
+ current.clone().alias("i"),
+ (current.clone() + lit(1)).alias("j"),
+ ]),
+ )
+ .otherwise(r#struct([
+ best.alias("v"),
+ index.alias("i"),
+ (current + lit(1)).alias("j"),
+ ]))
+ },
+ |args| args[0].clone().get_field("i"),
+ )
+ .cast(DataType::Double)
+}
+
+impl Transformer for OneVsRestModel {
fn operator(&self) -> &MlOperator {
&self.operator
}
@@ -1583,20 +2775,38 @@ impl Transformer for LinearSVCModel {
fn params_mut(&mut self) -> &mut Params {
&mut self.params
}
-
+ fn transform_impl(&mut self, df: &DataFrame) ->
spark_connect_core::error::Result<DataFrame> {
+ self.transformed(df)
+ }
fn build_ml_relation(
&self,
- input: &DataFrame,
+ df: &DataFrame,
) -> spark_connect_core::error::Result<proto::MlRelation> {
- self.cached.build_ml_relation(input, &self.params)
- }
-
- fn transform_impl(&mut self, df: &DataFrame) ->
spark_connect_core::error::Result<DataFrame> {
- self.cached.transform(df, &self.params)
+ // The composite transform is a SQL plan, represented as the input of
an identity
+ // SQLTransformer when a caller specifically requests an MlRelation.
+ Ok(proto::MlRelation {
+ ml_type: Some(proto::ml_relation::MlType::Transform(Box::new(
+ proto::ml_relation::Transform {
+ operator:
Some(proto::ml_relation::transform::Operator::Transformer(
+ MlOperator::new(
+ "org.apache.spark.ml.feature.SQLTransformer",
+ OperatorType::Transformer,
+ )
+ .to_proto(),
+ )),
+ input: Some(Box::new(self.transformed(df)?.relation()?)),
+ params: Some(
+ Params::new()
+ .set_param_string("statement", "SELECT * FROM
__THIS__")
+ .to_proto(),
+ ),
+ },
+ ))),
+ ..Default::default()
+ })
}
}
-
-impl Model for LinearSVCModel {
+impl Model for OneVsRestModel {
fn clone_box(&self) -> Box<dyn Model> {
Box::new(self.clone())
}
@@ -6269,6 +7479,299 @@ mod tests {
assert!(model.clone_box().transform(&df).is_ok());
}
+ #[test]
+ fn fmclassifier_model_validates_the_reference_and_retains_its_metadata() {
+ let session = offline_session();
+ let estimator = FMClassifier::default().set_prediction_col("pred");
+ assert_eq!(
+ estimator.operator().name,
+ "org.apache.spark.ml.classification.FMClassifier"
+ );
+ for kind in [
+ None,
+ Some(proto::ml_command_result::ml_operator_info::Type::Name(
+ "model".into(),
+ )),
+ Some(proto::ml_command_result::ml_operator_info::Type::ObjRef(
+ proto::ObjectRef::default(),
+ )),
+ ] {
+ assert!(estimator
+ .model_from_info(
+ proto::ml_command_result::MlOperatorInfo {
+ r#type: kind,
+ ..Default::default()
+ },
+ &session
+ )
+ .is_err());
+ }
+ let mut model = estimator
+ .model_from_info(
+ proto::ml_command_result::MlOperatorInfo {
+ r#type:
Some(proto::ml_command_result::ml_operator_info::Type::ObjRef(
+ proto::ObjectRef {
+ id: "trained-model".into(),
+ },
+ )),
+ uid: Some("returned-uid".into()),
+ ..Default::default()
+ },
+ &session,
+ )
+ .unwrap();
+ assert_eq!(model.operator().uid, "returned-uid");
+ assert_eq!(
+ model.operator().name,
+ "org.apache.spark.ml.classification.FMClassificationModel"
+ );
+ assert_eq!(model.operator().op_type, OperatorType::Model);
+ let df = session.range(2).unwrap();
+ let proto::ml_relation::MlType::Transform(t) =
+ model.build_ml_relation(&df).unwrap().ml_type.unwrap()
+ else {
+ panic!("transform")
+ };
+ assert_eq!(
+ t.operator,
+ Some(proto::ml_relation::transform::Operator::ObjRef(
+ proto::ObjectRef {
+ id: "trained-model".into()
+ }
+ ))
+ );
+ assert_eq!(*t.input.unwrap(), df.relation().unwrap());
+ assert!(t.params.unwrap().params.contains_key("predictionCol"));
+ assert!(model
+ .transform(&session.new_session().range(2).unwrap())
+ .is_err());
+ assert!(model.clone_box().transform(&df).is_ok());
+ }
+
+ #[test]
+ fn
multilayer_perceptron_classifier_model_validates_the_reference_and_retains_its_metadata()
{
+ let session = offline_session();
+ let estimator =
MultilayerPerceptronClassifier::default().set_prediction_col("pred");
+ assert_eq!(
+ estimator.operator().name,
+ "org.apache.spark.ml.classification.MultilayerPerceptronClassifier"
+ );
+ for kind in [
+ None,
+ Some(proto::ml_command_result::ml_operator_info::Type::Name(
+ "model".into(),
+ )),
+ Some(proto::ml_command_result::ml_operator_info::Type::ObjRef(
+ proto::ObjectRef::default(),
+ )),
+ ] {
+ assert!(estimator
+ .model_from_info(
+ proto::ml_command_result::MlOperatorInfo {
+ r#type: kind,
+ ..Default::default()
+ },
+ &session
+ )
+ .is_err());
+ }
+ let mut model = estimator
+ .model_from_info(
+ proto::ml_command_result::MlOperatorInfo {
+ r#type:
Some(proto::ml_command_result::ml_operator_info::Type::ObjRef(
+ proto::ObjectRef {
+ id: "trained-model".into(),
+ },
+ )),
+ uid: Some("returned-uid".into()),
+ ..Default::default()
+ },
+ &session,
+ )
+ .unwrap();
+ assert_eq!(model.operator().uid, "returned-uid");
+ assert_eq!(
+ model.operator().name,
+
"org.apache.spark.ml.classification.MultilayerPerceptronClassificationModel"
+ );
+ assert_eq!(model.operator().op_type, OperatorType::Model);
+ let df = session.range(2).unwrap();
+ let proto::ml_relation::MlType::Transform(t) =
+ model.build_ml_relation(&df).unwrap().ml_type.unwrap()
+ else {
+ panic!("transform")
+ };
+ assert_eq!(
+ t.operator,
+ Some(proto::ml_relation::transform::Operator::ObjRef(
+ proto::ObjectRef {
+ id: "trained-model".into()
+ }
+ ))
+ );
+ assert_eq!(*t.input.unwrap(), df.relation().unwrap());
+ assert!(t.params.unwrap().params.contains_key("predictionCol"));
+ assert!(model
+ .transform(&session.new_session().range(2).unwrap())
+ .is_err());
+ assert!(model.clone_box().transform(&df).is_ok());
+ }
+
+ #[test]
+ fn fmclassifier_defaults_and_configured_getters() {
+ let default = FMClassifier::new();
+ assert_eq!(default.feature_col(), "features");
+ assert_eq!(default.label_col(), "label");
+ assert_eq!(default.prediction_col(), "prediction");
+ assert_eq!(default.probability_col(), "probability");
+ assert_eq!(default.raw_prediction_col(), "rawPrediction");
+ assert_eq!(default.factor_size(), 8);
+ assert!(default.fit_intercept());
+ assert!(default.fit_linear());
+ assert_eq!(default.reg_param(), 0.0);
+ assert_eq!(default.mini_batch_fraction(), 1.0);
+ assert_eq!(default.init_std(), 0.01);
+ assert_eq!(default.max_iter(), 100);
+ assert_eq!(default.step_size(), 1.0);
+ assert_eq!(default.tol(), 1e-06);
+ assert_eq!(default.solver(), "adamW");
+ assert_eq!(default.thresholds(), None);
+ assert_eq!(default.seed(), None);
+ let configured = FMClassifier::new()
+ .set_feature_col("input")
+ .set_label_col("target")
+ .set_prediction_col("pred")
+ .set_probability_col("prob")
+ .set_raw_prediction_col("scores")
+ .set_factor_size(2)
+ .set_fit_intercept(false)
+ .set_fit_linear(false)
+ .set_reg_param(0.1)
+ .set_mini_batch_fraction(0.5)
+ .set_init_std(0.2)
+ .set_max_iter(50)
+ .set_step_size(0.3)
+ .set_tol(1e-08)
+ .set_solver("gd")
+ .set_thresholds([1.0, 2.0])
+ .set_seed(8589934592);
+ assert_eq!(configured.feature_col(), "input");
+ assert_eq!(configured.label_col(), "target");
+ assert_eq!(configured.prediction_col(), "pred");
+ assert_eq!(configured.probability_col(), "prob");
+ assert_eq!(configured.raw_prediction_col(), "scores");
+ assert_eq!(configured.factor_size(), 2);
+ assert!(!configured.fit_intercept());
+ assert!(!configured.fit_linear());
+ assert_eq!(configured.reg_param(), 0.1);
+ assert_eq!(configured.mini_batch_fraction(), 0.5);
+ assert_eq!(configured.init_std(), 0.2);
+ assert_eq!(configured.max_iter(), 50);
+ assert_eq!(configured.step_size(), 0.3);
+ assert_eq!(configured.tol(), 1e-08);
+ assert_eq!(configured.solver(), "gd");
+ assert_eq!(configured.thresholds(), Some(vec![1.0, 2.0]));
+ assert_eq!(configured.seed(), Some(8589934592));
+ }
+
+ #[test]
+ fn multilayer_perceptron_classifier_defaults_and_configured_getters() {
+ let default = MultilayerPerceptronClassifier::new();
+ assert_eq!(default.feature_col(), "features");
+ assert_eq!(default.label_col(), "label");
+ assert_eq!(default.prediction_col(), "prediction");
+ assert_eq!(default.max_iter(), 100);
+ assert_eq!(default.tol(), 1e-06);
+ assert_eq!(default.seed(), None);
+ assert_eq!(default.layers(), None);
+ assert_eq!(default.block_size(), 128);
+ assert_eq!(default.step_size(), 0.03);
+ assert_eq!(default.solver(), "l-bfgs");
+ assert_eq!(default.initial_weights(), None);
+ assert_eq!(default.probability_col(), "probability");
+ assert_eq!(default.raw_prediction_col(), "rawPrediction");
+ assert_eq!(default.thresholds(), None);
+ let configured = MultilayerPerceptronClassifier::new()
+ .set_feature_col("input")
+ .set_label_col("target")
+ .set_prediction_col("pred")
+ .set_max_iter(50)
+ .set_tol(1e-08)
+ .set_seed(8589934592)
+ .set_layers([2, 3, 2])
+ .set_block_size(4)
+ .set_step_size(0.1)
+ .set_solver("gd")
+ .set_initial_weights(MlVector::Dense(vec![
+ 0.0, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09,
0.1, 0.11, 0.12, 0.13,
+ 0.14, 0.15, 0.16,
+ ]))
+ .set_probability_col("prob")
+ .set_raw_prediction_col("scores")
+ .set_thresholds([1.0, 2.0]);
+ assert_eq!(configured.feature_col(), "input");
+ assert_eq!(configured.label_col(), "target");
+ assert_eq!(configured.prediction_col(), "pred");
+ assert_eq!(configured.max_iter(), 50);
+ assert_eq!(configured.tol(), 1e-08);
+ assert_eq!(configured.seed(), Some(8589934592));
+ assert_eq!(configured.layers(), Some(vec![2, 3, 2]));
+ assert_eq!(configured.block_size(), 4);
+ assert_eq!(configured.step_size(), 0.1);
+ assert_eq!(configured.solver(), "gd");
+ assert_eq!(
+ configured.initial_weights(),
+ Some(MlVector::Dense(vec![
+ 0.0, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09,
0.1, 0.11, 0.12, 0.13,
+ 0.14, 0.15, 0.16
+ ]))
+ );
+ assert_eq!(configured.probability_col(), "prob");
+ assert_eq!(configured.raw_prediction_col(), "scores");
+ assert_eq!(configured.thresholds(), Some(vec![1.0, 2.0]));
+ }
+
+ #[test]
+ fn one_vs_rest_rejects_null_client_parameters_before_requests() {
+ let session = offline_session();
+ let df = session.range(1).unwrap();
+ for name in [
+ "featuresCol",
+ "labelCol",
+ "predictionCol",
+ "rawPredictionCol",
+ "parallelism",
+ ] {
+ let mut estimator =
OneVsRest::new().set_classifier(LinearSVC::new());
+ *estimator.params_mut() = Params::new().set_param_null(name);
+ assert!(estimator.fit(&df).is_err());
+ }
+ }
+
+ #[test]
+ fn one_vs_rest_defaults_and_configured_getters() {
+ let default = OneVsRest::new();
+ assert_eq!(default.feature_col(), "features");
+ assert_eq!(default.label_col(), "label");
+ assert_eq!(default.prediction_col(), "prediction");
+ assert_eq!(default.raw_prediction_col(), "rawPrediction");
+ assert_eq!(default.weight_col(), None);
+ assert_eq!(default.parallelism(), 1);
+ let configured = OneVsRest::new()
+ .set_feature_col("input")
+ .set_label_col("target")
+ .set_prediction_col("pred")
+ .set_raw_prediction_col("scores")
+ .set_weight_col("weight")
+ .set_parallelism(3);
+ assert_eq!(configured.feature_col(), "input");
+ assert_eq!(configured.label_col(), "target");
+ assert_eq!(configured.prediction_col(), "pred");
+ assert_eq!(configured.raw_prediction_col(), "scores");
+ assert_eq!(configured.weight_col(), Some("weight"));
+ assert_eq!(configured.parallelism(), 3);
+ }
+
#[test]
fn
generalized_linear_regression_model_validates_the_reference_and_retains_its_metadata()
{
let session = offline_session();
diff --git a/crates/spark-connect/tests/e2e_remaining_classifiers.rs
b/crates/spark-connect/tests/e2e_remaining_classifiers.rs
new file mode 100644
index 00000000..b9b0c386
--- /dev/null
+++ b/crates/spark-connect/tests/e2e_remaining_classifiers.rs
@@ -0,0 +1,147 @@
+//! Live numerical and ownership checks for the remaining native classifiers.
+mod common;
+use common::live_session;
+use spark_connect::column::{col, lit};
+use spark_connect::expression::Expression;
+use spark_connect::ml::{
+ Estimator, FMClassifier, LinearSVC, MlVector,
MultilayerPerceptronClassifier, OneVsRest,
+};
+use spark_connect::{Column, DataFrame};
+use std::sync::Arc;
+
+fn vectors(df: DataFrame) -> DataFrame {
+ df.with_column(
+ "features",
+ Column::new(Expression::function(
+ "array_to_vector",
+ vec![col("xs").expression().clone()],
+ )),
+ )
+}
+fn predictions(df: DataFrame) -> Vec<f64> {
+ df.order_by([col("id")])
+ .select([col("prediction")])
+ .collect()
+ .unwrap()
+ .iter()
+ .map(|r| r.get(0).unwrap().as_f64().unwrap())
+ .collect()
+}
+#[test]
+fn fm_classifier_learns_interactions_and_owns_lazy_models() {
+ let Some(s) = live_session() else {
+ return;
+ };
+ let frame=vectors(s.sql("SELECT id,array(x,y) xs,label FROM VALUES
(0,-1.0D,-1.0D,1.0D),(1,-1.0D,1.0D,0.0D),(2,1.0D,-1.0D,0.0D),(3,1.0D,1.0D,1.0D)
AS t(id,x,y,label)").unwrap());
+ let mut model = FMClassifier::new()
+ .set_factor_size(2)
+ .set_fit_linear(false)
+ .set_init_std(0.1)
+ .set_step_size(0.1)
+ .set_max_iter(200)
+ .set_seed(42)
+ .fit(&frame)
+ .unwrap();
+ let mut cloned = model.clone_box();
+ let lazy = model.transform(&frame).unwrap();
+ drop(model);
+ assert_eq!(
+ predictions(cloned.transform(&frame).unwrap()),
+ vec![1.0, 0.0, 0.0, 1.0]
+ );
+ assert!(cloned
+ .transform(&s.new_session().range(1).unwrap())
+ .is_err());
+ drop(cloned);
+ assert_eq!(predictions(lazy), vec![1.0, 0.0, 0.0, 1.0]);
+ s.stop().unwrap();
+}
+#[test]
+fn multilayer_perceptron_uses_dense_and_sparse_initial_weights() {
+ let Some(s) = live_session() else {
+ return;
+ };
+ let frame=vectors(s.sql("SELECT id,array(x,y) xs,label FROM VALUES
(0,-2.0D,-2.0D,0.0D),(1,2.0D,-2.0D,1.0D),(2,0.0D,2.0D,2.0D) AS
t(id,x,y,label)").unwrap());
+ for weights in [
+ MlVector::Dense((0..9).map(|i| i as f64 * 0.01).collect()),
+ MlVector::Sparse {
+ size: 9,
+ indices: vec![0, 8],
+ values: vec![0.1, -0.1],
+ },
+ ] {
+ let mut model = MultilayerPerceptronClassifier::new()
+ .set_layers([2, 3])
+ .set_initial_weights(weights)
+ .set_max_iter(100)
+ .set_seed(1_i64 << 33)
+ .fit(&frame)
+ .unwrap();
+ let lazy = model.transform(&frame).unwrap();
+ drop(model);
+ assert_eq!(predictions(lazy), vec![0.0, 1.0, 2.0]);
+ }
+ s.stop().unwrap();
+}
+#[test]
+fn one_vs_rest_parallel_models_and_ml_relations_keep_submodels_alive() {
+ let Some(s) = live_session() else {
+ return;
+ };
+ let frame=vectors(s.sql("SELECT id,array(x,y) xs,label FROM VALUES
(0,-2.0D,-2.0D,0.0D),(1,2.0D,-2.0D,1.0D),(2,0.0D,2.0D,2.0D) AS
t(id,x,y,label)").unwrap());
+ for parallelism in [1, 3] {
+ let mut estimator = OneVsRest::new()
+ .set_classifier(LinearSVC::new().set_max_iter(100))
+ .set_parallelism(parallelism);
+ let mut model = estimator.fit(&frame).unwrap();
+ let mut other = estimator
+ .fit(&frame.with_column("label", (col("label") + lit(1)) % lit(3)))
+ .unwrap();
+ let lazy = model.transform(&frame).unwrap();
+ let relation = model.build_ml_relation(&frame).unwrap();
+ let identity = DataFrame::from_relation(
+ s.clone(),
+ spark_connect_proto::Relation {
+ rel_type:
Some(spark_connect_proto::relation::RelType::MlRelation(
+ Box::new(relation),
+ )),
+ ..Default::default()
+ },
+ Some(Arc::new(model.clone_box())),
+ )
+ .unwrap();
+ assert!(model.transform(&s.new_session().range(1).unwrap()).is_err());
+ drop(model);
+ assert_eq!(predictions(lazy), vec![0.0, 1.0, 2.0]);
+ assert_eq!(predictions(identity), vec![0.0, 1.0, 2.0]);
+ assert_eq!(
+ predictions(other.transform(&frame).unwrap()),
+ vec![1.0, 2.0, 0.0]
+ );
+ }
+ s.stop().unwrap();
+}
+#[test]
+fn
new_classifiers_reject_invalid_parameters_and_missing_one_vs_rest_classifier() {
+ let Some(s) = live_session() else {
+ return;
+ };
+ let frame = vectors(s.sql("SELECT array(1.0D,2.0D) xs,0.0D
label").unwrap());
+ assert!(FMClassifier::new().set_factor_size(0).fit(&frame).is_err());
+ assert!(MultilayerPerceptronClassifier::new()
+ .set_layers([2])
+ .fit(&frame)
+ .is_err());
+ assert!(OneVsRest::new().fit(&frame).is_err());
+ assert!(OneVsRest::new()
+ .set_classifier(LinearSVC::new())
+ .set_parallelism(0)
+ .fit(&frame)
+ .is_err());
+ assert!(OneVsRest::new()
+ .set_classifier(LinearSVC::new().set_max_iter(-1))
+ .set_parallelism(2)
+ .fit(&frame)
+ .is_err());
+ s.stop().unwrap();
+}
diff --git a/crates/spark-connect/tests/remaining_classifiers_golden.rs
b/crates/spark-connect/tests/remaining_classifiers_golden.rs
new file mode 100644
index 00000000..74511410
--- /dev/null
+++ b/crates/spark-connect/tests/remaining_classifiers_golden.rs
@@ -0,0 +1,99 @@
+//! Parameter encodings independently captured with official PySpark 4.3.0.
+use base64::{engine::general_purpose::STANDARD, Engine};
+use prost::Message;
+use spark_connect::ml::{
+ Estimator, FMClassifier, MlVector, MultilayerPerceptronClassifier,
OneVsRest,
+};
+
+#[test]
+fn remaining_classifier_parameters_match_official_pyspark() {
+ let fixture: serde_json::Value = serde_json::from_str(include_str!(
+ "../../../tests/golden/remaining_classifiers.json"
+ ))
+ .unwrap();
+ let estimators: Vec<Box<dyn Estimator>> = vec![
+ Box::new(FMClassifier::new()),
+ Box::new(
+ FMClassifier::new()
+ .set_feature_col("input")
+ .set_label_col("target")
+ .set_prediction_col("pred")
+ .set_probability_col("prob")
+ .set_raw_prediction_col("scores")
+ .set_factor_size(2)
+ .set_fit_intercept(false)
+ .set_fit_linear(false)
+ .set_reg_param(0.1)
+ .set_mini_batch_fraction(0.5)
+ .set_init_std(0.2)
+ .set_max_iter(50)
+ .set_step_size(0.3)
+ .set_tol(1e-08)
+ .set_solver("gd")
+ .set_thresholds([1.0, 2.0])
+ .set_seed(8589934592),
+ ),
+ Box::new(MultilayerPerceptronClassifier::new()),
+ Box::new(
+ MultilayerPerceptronClassifier::new()
+ .set_feature_col("input")
+ .set_label_col("target")
+ .set_prediction_col("pred")
+ .set_max_iter(50)
+ .set_tol(1e-08)
+ .set_seed(8589934592)
+ .set_layers([2, 3, 2])
+ .set_block_size(4)
+ .set_step_size(0.1)
+ .set_solver("gd")
+ .set_initial_weights(MlVector::Dense(vec![
+ 0.0, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09,
0.1, 0.11, 0.12,
+ 0.13, 0.14, 0.15, 0.16,
+ ]))
+ .set_probability_col("prob")
+ .set_raw_prediction_col("scores")
+ .set_thresholds([1.0, 2.0]),
+ ),
+ Box::new(
+ MultilayerPerceptronClassifier::new()
+ .set_feature_col("input")
+ .set_label_col("target")
+ .set_prediction_col("pred")
+ .set_max_iter(50)
+ .set_tol(1e-08)
+ .set_seed(8589934592)
+ .set_layers([2, 3, 2])
+ .set_block_size(4)
+ .set_step_size(0.1)
+ .set_solver("gd")
+ .set_initial_weights(MlVector::Sparse {
+ size: 17,
+ indices: vec![0, 16],
+ values: vec![0.1, -0.2],
+ })
+ .set_probability_col("prob")
+ .set_raw_prediction_col("scores")
+ .set_thresholds([1.0, 2.0]),
+ ),
+ Box::new(OneVsRest::new()),
+ Box::new(
+ OneVsRest::new()
+ .set_feature_col("input")
+ .set_label_col("target")
+ .set_prediction_col("pred")
+ .set_raw_prediction_col("scores")
+ .set_weight_col("weight")
+ .set_parallelism(3),
+ ),
+ ];
+ for (estimator, case) in estimators
+ .into_iter()
+ .zip(fixture["cases"].as_array().unwrap())
+ {
+ let bytes = STANDARD
+ .decode(case["params_b64"].as_str().unwrap())
+ .unwrap();
+ let expected =
spark_connect_proto::MlParams::decode(bytes.as_slice()).unwrap();
+ assert_eq!(estimator.params().to_proto(), expected, "{}",
case["class"]);
+ }
+}
diff --git a/docs/compatibility.md b/docs/compatibility.md
index 757a2ee1..50368ea2 100644
--- a/docs/compatibility.md
+++ b/docs/compatibility.md
@@ -667,3 +667,56 @@ The native surface covers construction, parameter setters,
fit and DataFrame
transform. Component/weight/covariance inspection, training summaries,
single-vector prediction and persistence are outside this surface. The vendored
`pyspark.ml.clustering` API retains its existing implementation.
+
+## Native FMClassifier
+
+`spark_connect::ml::FMClassifier` and
+`pyspark.ml.connect.classification.FMClassifier` fit Spark's binary
factorization
+machine classifier. All 17 PySpark constructor parameters have Rust builder
+setters/getters and named Python setters. Fitted models produce prediction,
+probability and raw-prediction columns, with configurable thresholds. Both the
+`gd` and `adamW` solvers run on the Spark server.
+
+## Native MultilayerPerceptronClassifier
+
+`spark_connect::ml::MultilayerPerceptronClassifier` and its native Python
binding
+support all 13 PySpark constructor parameters plus `setThresholds`. Configure
+`layers` before fitting; input and output sizes must match the feature
dimension
+and number of classes. `initialWeights` accepts dense or sparse ML vectors:
+Rust uses `MlVector` (a `Vec<f64>` or array also converts to a dense vector),
and
+Python accepts the values supported by PySpark's `TypeConverters.toVector`.
+Layer arrays and vector parameters are encoded in Rust and checked against
+fixtures captured with official PySpark.
+
+The fitted model produces multiclass prediction, probability and raw-prediction
+columns. Both `l-bfgs` and `gd` are supported. As in PySpark, fitting an empty
+DataFrame can return a model; the native client preserves that server behavior.
+
+## Native OneVsRest
+
+`spark_connect::ml::OneVsRest` and
`pyspark.ml.connect.classification.OneVsRest`
+implement the multiclass reduction in Rust. Supply a native binary classifier,
+for example `OneVsRest::new().set_classifier(LinearSVC::new())` in Rust or
+`OneVsRest(classifier=LinearSVC())` in Python. The `Classifier` enum accepts
all
+eight native binary classifiers: LogisticRegression, LinearSVC,
+DecisionTreeClassifier, RandomForestClassifier, GBTClassifier, NaiveBayes,
+FMClassifier and MultilayerPerceptronClassifier. Perceptron base classifiers
need
+a two-unit output layer.
+
+All seven PySpark constructor parameters have named setters. Rust exposes
scalar
+parameter getters and the configured classifier. Fits clone the base classifier
+for each class and run at most `parallelism` fits at once. Python observes
+mutations to the supplied classifier made before `fit`, while fitting leaves
that
+classifier unchanged. Class indices run from zero through the maximum label, as
+in PySpark. Instance weights are forwarded when the base classifier supports
+them; Python warns when they are ignored for FMClassifier or the perceptron.
+
+The model aggregates positive-class raw scores into `rawPrediction` and chooses
+the first highest score for `prediction`, ignoring NaN/null scores as PySpark
+does. It produces no probability column. Temporary columns and fit-created
+caches are cleaned up, and transformed DataFrames retain the binary models for
+lazy evaluation. Models must transform data in their fitting session.
+
+These additions cover native estimator construction, parameters, fitting and
+DataFrame transforms. Model coefficient/weight inspection, training summaries,
+persistence and single-vector prediction remain separate API work.
diff --git a/python/pyspark/ml/connect/__init__.py
b/python/pyspark/ml/connect/__init__.py
index 117928f1..6472429e 100644
--- a/python/pyspark/ml/connect/__init__.py
+++ b/python/pyspark/ml/connect/__init__.py
@@ -14,6 +14,9 @@ from pyspark.ml.connect.feature import (
from pyspark.ml.connect.classification import (
GBTClassifier,
DecisionTreeClassifier,
+ FMClassifier,
+ MultilayerPerceptronClassifier,
+ OneVsRest,
LinearSVC,
LogisticRegression,
NaiveBayes,
@@ -59,6 +62,9 @@ __all__ = [
"VectorAssembler",
"LogisticRegression",
"NaiveBayes",
+ "FMClassifier",
+ "MultilayerPerceptronClassifier",
+ "OneVsRest",
"LinearSVC",
"DecisionTreeClassifier",
"GBTClassifier",
diff --git a/python/pyspark/ml/connect/classification.py
b/python/pyspark/ml/connect/classification.py
index 45d2b567..18902f2f 100644
--- a/python/pyspark/ml/connect/classification.py
+++ b/python/pyspark/ml/connect/classification.py
@@ -1,11 +1,25 @@
"""Classification estimators (pyspark.ml.connect.classification)."""
+
from pyspark._pyspark import (
DecisionTreeClassifier,
+ FMClassifier,
GBTClassifier,
LinearSVC,
LogisticRegression,
+ MultilayerPerceptronClassifier,
NaiveBayes,
+ OneVsRest,
RandomForestClassifier,
)
-__all__ = ["NaiveBayes", "GBTClassifier", "DecisionTreeClassifier",
"LinearSVC", "LogisticRegression", "RandomForestClassifier"]
+__all__ = [
+ "FMClassifier",
+ "MultilayerPerceptronClassifier",
+ "OneVsRest",
+ "NaiveBayes",
+ "GBTClassifier",
+ "DecisionTreeClassifier",
+ "LinearSVC",
+ "LogisticRegression",
+ "RandomForestClassifier",
+]
diff --git a/python/tests/test_ml_e2e.py b/python/tests/test_ml_e2e.py
index 2ab31e36..581af7c6 100644
--- a/python/tests/test_ml_e2e.py
+++ b/python/tests/test_ml_e2e.py
@@ -249,6 +249,7 @@ def _native_estimators():
BisectingKMeans,
DecisionTreeClassifier,
DecisionTreeRegressor,
+ FMClassifier,
GaussianMixture,
GBTClassifier,
GBTRegressor,
@@ -258,6 +259,7 @@ def _native_estimators():
LinearSVC,
LogisticRegression,
MaxAbsScaler,
+ MultilayerPerceptronClassifier,
NaiveBayes,
RandomForestClassifier,
RandomForestRegressor,
@@ -275,6 +277,8 @@ def _native_estimators():
(DecisionTreeRegressor(), ml +
"regression.DecisionTreeRegressionModel"),
(DecisionTreeClassifier(), ml +
"classification.DecisionTreeClassificationModel"),
(KMeans(k=2, seed=1), ml + "clustering.KMeansModel"),
+ (FMClassifier(maxIter=2, seed=42), ml +
"classification.FMClassificationModel"),
+ (MultilayerPerceptronClassifier(layers=[2,2],maxIter=2,seed=42), ml +
"classification.MultilayerPerceptronClassificationModel"),
(LinearSVC(maxIter=2), ml + "classification.LinearSVCModel"),
(GeneralizedLinearRegression(maxIter=2), ml +
"regression.GeneralizedLinearRegressionModel"),
(LinearRegression(maxIter=2), ml + "regression.LinearRegressionModel"),
diff --git a/python/tests/test_ml_offline.py b/python/tests/test_ml_offline.py
index c0c95fc8..05e9437b 100644
--- a/python/tests/test_ml_offline.py
+++ b/python/tests/test_ml_offline.py
@@ -931,6 +931,8 @@ _NATIVE_PARAMS = {
featuresCol="str", labelCol="str", predictionCol="str",
probabilityCol="str",
maxIter="int", tol="float",
),
+ "FMClassifier": dict(featuresCol="str", labelCol="str",
predictionCol="str", probabilityCol="str", rawPredictionCol="str",
factorSize="int", fitIntercept="bool", fitLinear="bool", regParam="float",
miniBatchFraction="float", initStd="float", maxIter="int", stepSize="float",
tol="float", solver="str", thresholds="float_list", seed="int"),
+ "MultilayerPerceptronClassifier": dict(featuresCol="str", labelCol="str",
predictionCol="str", maxIter="int", tol="float", seed="int", blockSize="int",
stepSize="float", solver="str", probabilityCol="str", rawPredictionCol="str",
thresholds="float_list"),
"LinearSVC": dict(
featuresCol="str", labelCol="str", predictionCol="str", maxIter="int",
regParam="float",
tol="float", rawPredictionCol="str", fitIntercept="bool",
standardization="bool",
@@ -3612,3 +3614,94 @@ def
test_generalized_linear_regression_native_parameters_match_official_fixture(
operator, params = _native_request(spark, service, estimator, models)
assert operator.name ==
"org.apache.spark.ml.regression.GeneralizedLinearRegression"
assert params ==
pb2.MlParams.FromString(base64.b64decode(case["params_b64"]))
+
+
[email protected]("name", ["FMClassifier",
"MultilayerPerceptronClassifier"])
[email protected]("use_setters", [False, True])
+def
test_remaining_classifier_native_parameters_match_official_fixture(ml_mock,
name, use_setters):
+ import base64
+ import inspect
+ import json
+ from pathlib import Path
+
+ from pyspark import _pyspark as native
+ from pyspark.ml.connect import classification
+ from pyspark.ml.linalg import Vectors
+
+ cls = getattr(classification, name)
+ assert cls is getattr(native, name)
+ defaults = {'FMClassifier': {'featuresCol': 'features', 'labelCol':
'label', 'predictionCol': 'prediction', 'probabilityCol': 'probability',
'rawPredictionCol': 'rawPrediction', 'factorSize': 8, 'fitIntercept': True,
'fitLinear': True, 'regParam': 0.0, 'miniBatchFraction': 1.0, 'initStd': 0.01,
'maxIter': 100, 'stepSize': 1.0, 'tol': 1e-06, 'solver': 'adamW', 'thresholds':
None, 'seed': None}, 'MultilayerPerceptronClassifier': {'featuresCol':
'features', 'labelCol': 'label', 'predict [...]
+ signature = inspect.signature(cls)
+ assert list(signature.parameters) == list(defaults)
+ for key, value in defaults.items():
+ assert signature.parameters[key].default == value
+ assert signature.parameters[key].kind == inspect.Parameter.KEYWORD_ONLY
+ fixture = json.loads((Path(__file__).resolve().parents[2] /
"tests/golden/remaining_classifiers.json").read_text())
+ spark, service = ml_mock
+ models = []
+ for case in fixture["cases"]:
+ if case["class"] != name:
+ continue
+ values = dict(case["values"])
+ if "initialWeights" in values:
+ vector = values["initialWeights"]
+ values["initialWeights"] = Vectors.dense(vector["dense"]) if
"dense" in vector else Vectors.sparse(vector["size"], vector["indices"],
vector["values"])
+ if use_setters:
+ estimator = cls()
+ for key, value in values.items():
+ assert getattr(estimator, "set" + key[0].upper() +
key[1:])(value) is estimator
+ else:
+ thresholds = values.pop("thresholds", None) if name ==
"MultilayerPerceptronClassifier" else None
+ estimator = cls(**values)
+ if thresholds is not None:
+ estimator.setThresholds(thresholds)
+ operator, params = _native_request(spark, service, estimator, models)
+ assert operator.name == "org.apache.spark.ml.classification." + name
+ assert params ==
pb2.MlParams.FromString(base64.b64decode(case["params_b64"]))
+
+
+def test_one_vs_rest_signature_and_native_classifier_validation():
+ import inspect
+
+ from pyspark import _pyspark as native
+ from pyspark.ml.connect import OneVsRest as exported
+ from pyspark.ml.connect.classification import LinearSVC, OneVsRest
+
+ assert OneVsRest is exported is native.OneVsRest
+ defaults = {'FMClassifier': {'featuresCol': 'features', 'labelCol':
'label', 'predictionCol': 'prediction', 'probabilityCol': 'probability',
'rawPredictionCol': 'rawPrediction', 'factorSize': 8, 'fitIntercept': True,
'fitLinear': True, 'regParam': 0.0, 'miniBatchFraction': 1.0, 'initStd': 0.01,
'maxIter': 100, 'stepSize': 1.0, 'tol': 1e-06, 'solver': 'adamW', 'thresholds':
None, 'seed': None}, 'MultilayerPerceptronClassifier': {'featuresCol':
'features', 'labelCol': 'label', 'predict [...]
+ signature = inspect.signature(OneVsRest)
+ assert list(signature.parameters) == list(defaults)
+ for key, value in defaults.items():
+ assert signature.parameters[key].default == value
+ assert signature.parameters[key].kind == inspect.Parameter.KEYWORD_ONLY
+ estimator = OneVsRest()
+ assert estimator.setClassifier(LinearSVC()) is estimator
+ for key, value in dict(featuresCol="x", labelCol="y", predictionCol="p",
rawPredictionCol="r", weightCol="w", parallelism=2).items():
+ assert getattr(estimator, "set" + key[0].upper() + key[1:])(value) is
estimator
+ with pytest.raises(TypeError):
+ estimator.setClassifier(object())
+ with pytest.raises(TypeError):
+ OneVsRest(LinearSVC())
+ with pytest.raises(TypeError):
+ OneVsRest(unknown=True)
+ with pytest.raises(ValueError, match="classifier"):
+ OneVsRest().fit(None)
+
+
[email protected]("name,value",
[("layers",[2,1.5]),("layers","abc"),("initialWeights","abc")])
+def test_multilayer_perceptron_rejects_invalid_parameter_types(name,value):
+ from pyspark.ml.connect.classification import
MultilayerPerceptronClassifier
+ with pytest.raises(TypeError):
+ MultilayerPerceptronClassifier(**{name:value})
+
+
+def test_one_vs_rest_defers_base_param_validation_until_fit():
+ from pyspark.ml.connect.classification import
MultilayerPerceptronClassifier, OneVsRest
+
+ base = MultilayerPerceptronClassifier(layers=[])
+ estimator = OneVsRest(classifier=base)
+ assert estimator.setClassifier(base) is estimator
+ base.setLayers([2, 2])
+ assert estimator.setClassifier(None) is estimator
+ with pytest.raises(ValueError, match="classifier"):
+ estimator.fit(None)
diff --git a/python/tests/test_remaining_classifiers_e2e.py
b/python/tests/test_remaining_classifiers_e2e.py
new file mode 100644
index 00000000..04fa3216
--- /dev/null
+++ b/python/tests/test_remaining_classifiers_e2e.py
@@ -0,0 +1,323 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+"""Native FMClassifier, MultilayerPerceptronClassifier and OneVsRest behaviors.
+
+Run unchanged against official PySpark to check the numerical expectations.
+"""
+
+import gc
+import math
+import os
+
+import pytest
+from pyspark.ml.linalg import Vectors
+from pyspark.sql import SparkSession
+from pyspark.sql import functions as F
+
+
[email protected]
+def session():
+ remote = os.environ.get("SPARK_REMOTE")
+ if not remote:
+ pytest.skip("SPARK_REMOTE is required for live tests")
+ spark = SparkSession.builder.remote(remote).getOrCreate()
+ try:
+ yield spark
+ finally:
+ spark.stop()
+
+
+def _classifier(name):
+ from pyspark.ml.connect import classification as native
+
+ if hasattr(native, "FMClassifier"):
+ return getattr(native, name)
+ from pyspark.ml import classification as official
+
+ return getattr(official, name)
+
+
+def _triangles(session, names=("features", "label")):
+ rows = []
+ for label, point in enumerate([[-2.0, -2.0], [2.0, -2.0], [0.0, 2.0]]):
+ for delta in [-0.1, 0.0, 0.1]:
+ rows.append((Vectors.dense([point[0] + delta, point[1]]),
float(label)))
+ return session.createDataFrame(rows, list(names))
+
+
+def _classes(frame, column="prediction"):
+ return [r[0] for r in frame.select(column).collect()]
+
+
[email protected]("use_setters", [False, True], ids=["constructor",
"setters"])
+def test_fm_classifier_learns_interactions_and_keeps_lazy_models(session,
use_setters):
+ rows = [(Vectors.dense([x, y]), float(x * y > 0)) for x in [-1.0, 1.0] for
y in [-1.0, 1.0]]
+ train = session.createDataFrame(rows, ["input", "target"])
+ options = dict(
+ featuresCol="input",
+ labelCol="target",
+ predictionCol="pred",
+ probabilityCol="prob",
+ rawPredictionCol="scores",
+ factorSize=2,
+ fitIntercept=True,
+ fitLinear=False,
+ regParam=0.0,
+ miniBatchFraction=1.0,
+ initStd=0.1,
+ maxIter=200,
+ stepSize=0.1,
+ tol=1e-8,
+ solver="adamW",
+ thresholds=[1.0, 1.0],
+ seed=42,
+ )
+ estimator = (
+ _classifier("FMClassifier")() if use_setters else
_classifier("FMClassifier")(**options)
+ )
+ if use_setters:
+ for name, value in options.items():
+ assert getattr(estimator, "set" + name[0].upper() +
name[1:])(value) is estimator
+ first = estimator.fit(train)
+ second = estimator.fit(train.withColumn("target", F.lit(1.0) -
F.col("target")))
+ held = session.createDataFrame(
+ [(Vectors.sparse(2, {0: x, 1: y}),) for x in [-1.0, 1.0] for y in
[-1.0, 1.0]], ["input"]
+ )
+ lazy = first.transform(held)
+ del first, estimator
+ gc.collect()
+ result = lazy.select("pred", "prob", "scores").collect()
+ assert [r[0] for r in result] == [1.0, 0.0, 0.0, 1.0]
+ for row in result:
+ assert len(row[1]) == len(row[2]) == 2
+ assert sum(row[1]) == pytest.approx(1.0, abs=1e-8)
+ assert all(math.isfinite(float(x)) for x in row[2])
+ assert _classes(second.transform(held), "pred") == [0.0, 1.0, 1.0, 0.0]
+
+
+def test_fm_classifier_gradient_descent_and_thresholds(session):
+ train = session.createDataFrame(
+ [(Vectors.dense([x]), float(x > 0)) for x in [-3.0, -2.0, -1.0, 1.0,
2.0, 3.0]],
+ ["features", "label"],
+ )
+ model = _classifier("FMClassifier")(
+ solver="gd", stepSize=0.1, maxIter=200, seed=17, thresholds=[1.0, 4.0]
+ ).fit(train)
+ for row in model.transform(train).select("prediction",
"probability").collect():
+ expected = 0.0 if row[1][0] >= row[1][1] / 4.0 else 1.0
+ assert row[0] == expected
+
+
[email protected]("weights", ["dense", "sparse"])
+def test_multilayer_perceptron_multiclass_and_initial_weights(session,
weights):
+ train = _triangles(session, ("input", "target"))
+ initial = (
+ Vectors.dense([0.01 * i for i in range(9)])
+ if weights == "dense"
+ else Vectors.sparse(9, {0: 0.1, 8: -0.1})
+ )
+ estimator = _classifier("MultilayerPerceptronClassifier")(
+ featuresCol="input",
+ labelCol="target",
+ predictionCol="pred",
+ probabilityCol="prob",
+ rawPredictionCol="scores",
+ layers=[2, 3],
+ initialWeights=initial,
+ seed=2**33,
+ maxIter=100,
+ tol=1e-8,
+ blockSize=3,
+ stepSize=0.1,
+ solver="l-bfgs",
+ )
+ model = estimator.fit(train)
+ lazy = model.transform(train)
+ del model
+ gc.collect()
+ result = lazy.select("target", "pred", "prob", "scores").collect()
+ assert [r[1] for r in result] == [r[0] for r in result]
+ for row in result:
+ assert len(row[2]) == len(row[3]) == 3
+ assert sum(row[2]) == pytest.approx(1.0, abs=1e-8)
+
+
+def
test_multilayer_perceptron_hidden_layers_setters_and_gradient_descent(session):
+ train = session.createDataFrame(
+ [(Vectors.dense([x, y]), float(x != y)) for x in [0.0, 1.0] for y in
[0.0, 1.0]],
+ ["features", "label"],
+ )
+ estimator = (
+ _classifier("MultilayerPerceptronClassifier")()
+ .setLayers([2, 3, 2])
+ .setMaxIter(300)
+ .setSeed(42)
+ .setBlockSize(4)
+ .setTol(1e-9)
+ )
+ assert _classes(estimator.fit(train).transform(train)) == [0.0, 1.0, 1.0,
0.0]
+ simple = _triangles(session)
+ gd = (
+ _classifier("MultilayerPerceptronClassifier")(
+ layers=[2, 3], solver="gd", stepSize=0.1, maxIter=100, seed=42
+ )
+ .setThresholds([1.0, 1.0, 1.0])
+ .fit(simple)
+ )
+ assert _classes(gd.transform(simple)) == [0.0] * 3 + [1.0] * 3 + [2.0] * 3
+
+
[email protected]("parallelism", [1, 3])
+def
test_one_vs_rest_custom_columns_parallel_fit_and_lazy_independent_models(session,
parallelism):
+ base = _classifier("LinearSVC")(maxIter=100, tol=1e-8,
rawPredictionCol="scores")
+ estimator = _classifier("OneVsRest")(
+ classifier=base,
+ featuresCol="input",
+ labelCol="target",
+ predictionCol="pred",
+ rawPredictionCol="scores",
+ parallelism=parallelism,
+ )
+ train = _triangles(session, ("input", "target"))
+ first = estimator.fit(train)
+ second = estimator.fit(train.withColumn("target", (F.col("target") + 1.0)
% 3.0))
+ lazy = first.transform(train)
+ del first, estimator, base
+ gc.collect()
+ result = lazy.select("target", "pred", "scores").collect()
+ assert [r[1] for r in result] == [r[0] for r in result]
+ for row in result:
+ assert len(row[2]) == 3
+ assert row[1] == float(max(range(3), key=lambda i: row[2][i]))
+ assert _classes(second.transform(train), "pred") == [1.0] * 3 + [2.0] * 3
+ [0.0] * 3
+
+
[email protected](
+ "name",
+ [
+ "LogisticRegression",
+ "LinearSVC",
+ "DecisionTreeClassifier",
+ "RandomForestClassifier",
+ "GBTClassifier",
+ "NaiveBayes",
+ "FMClassifier",
+ "MultilayerPerceptronClassifier",
+ ],
+)
+def test_one_vs_rest_accepts_each_native_binary_classifier(session, name):
+ options = {
+ "LogisticRegression": dict(maxIter=30),
+ "LinearSVC": dict(maxIter=50),
+ "RandomForestClassifier": dict(numTrees=10, seed=42),
+ "GBTClassifier": dict(maxIter=5, seed=42),
+ "FMClassifier": dict(maxIter=150, stepSize=0.1, seed=42),
+ "MultilayerPerceptronClassifier": dict(layers=[3, 2], maxIter=100,
seed=42),
+ }.get(name, {})
+ rows = []
+ for label in range(3):
+ for scale in [1.0, 1.5, 2.0]:
+ rows.append((Vectors.sparse(3, {label: scale}), float(label)))
+ train = session.createDataFrame(rows, ["features", "label"])
+ classifier = _classifier(name)(**options)
+ estimator =
_classifier("OneVsRest")().setClassifier(classifier).setParallelism(2)
+ result = estimator.fit(train).transform(train)
+ assert _classes(result) == [0.0] * 3 + [1.0] * 3 + [2.0] * 3
+ assert "probability" not in result.columns
+
+
+def test_one_vs_rest_weights_and_mutated_base_classifier(session):
+ train = _triangles(session).withColumn("weight", F.lit(1.0))
+ bad = train.withColumn("label", (F.col("label") + 1.0) %
3.0).withColumn("weight", F.lit(0.0))
+ base = _classifier("LinearSVC")(maxIter=1)
+ estimator = _classifier("OneVsRest")(classifier=base, weightCol="weight")
+ base.setMaxIter(100)
+ result = estimator.fit(train.union(bad)).transform(train)
+ assert _classes(result) == [0.0] * 3 + [1.0] * 3 + [2.0] * 3
+ base.setMaxIter(-1)
+ with pytest.raises(Exception):
+ estimator.fit(train)
+
+
+def test_one_vs_rest_ignores_unsupported_weights_with_warning(session):
+ train = _triangles(session).withColumn("weight", F.lit(-1.0))
+ base = _classifier("MultilayerPerceptronClassifier")(layers=[2, 2],
maxIter=50, seed=42)
+ with pytest.warns(UserWarning, match="weightCol is ignored"):
+ model = _classifier("OneVsRest")(classifier=base,
weightCol="weight").fit(train)
+ assert _classes(model.transform(train)) == [0.0] * 3 + [1.0] * 3 + [2.0] *
3
+
+
[email protected](
+ "name,options",
+ [
+ ("FMClassifier", dict(factorSize=0)),
+ ("FMClassifier", dict(solver="unknown")),
+ ("FMClassifier", dict(miniBatchFraction=0.0)),
+ ("FMClassifier", dict(maxIter=-1)),
+ ("MultilayerPerceptronClassifier", dict(layers=[2])),
+ ("MultilayerPerceptronClassifier", dict(layers=[2, 3],
solver="unknown")),
+ ("MultilayerPerceptronClassifier", dict(layers=[2, 3],
initialWeights=[0.0])),
+ ("OneVsRest", dict()),
+ ("OneVsRest", dict(parallelism=0)),
+ ],
+)
+def test_remaining_classifiers_reject_invalid_configuration(session, name,
options):
+ if name == "OneVsRest" and options:
+ options = dict(options, classifier=_classifier("LinearSVC")())
+ train = _triangles(session)
+ if name == "FMClassifier":
+ train = train.filter(F.col("label") < 2.0)
+ with pytest.raises(Exception):
+ _classifier(name)(**options).fit(train)
+
+
[email protected]("name", ["FMClassifier",
"MultilayerPerceptronClassifier", "OneVsRest"])
+def test_remaining_classifiers_reject_nonvector_and_empty_data(session, name):
+ options = {
+ "MultilayerPerceptronClassifier": dict(layers=[2, 3]),
+ "OneVsRest": dict(classifier=_classifier("LinearSVC")()),
+ }.get(name, {})
+ train = _triangles(session)
+ with pytest.raises(Exception):
+ _classifier(name)(**options).fit(train.withColumn("features",
F.lit(1.0)))
+ empty = train.limit(0)
+ if name == "MultilayerPerceptronClassifier":
+ assert
_classifier(name)(**options).fit(empty).transform(empty).count() == 0
+ else:
+ with pytest.raises(Exception):
+ _classifier(name)(**options).fit(empty)
+
+
+def test_one_vs_rest_first_tie_and_nan_scores_follow_pyspark(session):
+ train = _triangles(session)
+ base = _classifier("LinearSVC")(maxIter=0, fitIntercept=False)
+ model = _classifier("OneVsRest")(classifier=base).fit(train)
+ points = session.createDataFrame(
+ [(Vectors.dense([0.0, 0.0]),), (Vectors.dense([float("nan"), 0.0]),)],
+ ["features"],
+ )
+ assert _classes(model.transform(points)) == [0.0, -1.0]
+
+
[email protected](
+ "parameter", ["featuresCol", "labelCol", "predictionCol",
"rawPredictionCol", "parallelism"]
+)
+def test_one_vs_rest_rejects_null_required_parameters(session, parameter):
+ estimator =
_classifier("OneVsRest")(classifier=_classifier("LinearSVC")(), **{parameter:
None})
+ frame = _triangles(session)
+ with pytest.raises(Exception):
+ estimator.fit(frame).transform(frame).collect()
diff --git a/scripts/capture_remaining_classifiers_golden.py
b/scripts/capture_remaining_classifiers_golden.py
new file mode 100644
index 00000000..f935ce7f
--- /dev/null
+++ b/scripts/capture_remaining_classifiers_golden.py
@@ -0,0 +1,140 @@
+#!/usr/bin/env python3
+"""Capture classification parameter goldens using official PySpark 4.3.0.
+
+OneVsRest's classifier is client-side orchestration state, not a literal
parameter.
+"""
+
+import argparse
+import base64
+import json
+from pathlib import Path
+
+from pyspark.ml import classification
+from pyspark.ml.connect.serialize import serialize_ml_params
+from pyspark.ml.linalg import Vectors
+from pyspark.sql import SparkSession
+
+VALUES = {
+ "FMClassifier": {
+ "featuresCol": "input",
+ "labelCol": "target",
+ "predictionCol": "pred",
+ "probabilityCol": "prob",
+ "rawPredictionCol": "scores",
+ "factorSize": 2,
+ "fitIntercept": False,
+ "fitLinear": False,
+ "regParam": 0.1,
+ "miniBatchFraction": 0.5,
+ "initStd": 0.2,
+ "maxIter": 50,
+ "stepSize": 0.3,
+ "tol": 1e-08,
+ "solver": "gd",
+ "thresholds": [1.0, 2.0],
+ "seed": 8589934592,
+ },
+ "MultilayerPerceptronClassifier": {
+ "featuresCol": "input",
+ "labelCol": "target",
+ "predictionCol": "pred",
+ "maxIter": 50,
+ "tol": 1e-08,
+ "seed": 8589934592,
+ "layers": [2, 3, 2],
+ "blockSize": 4,
+ "stepSize": 0.1,
+ "solver": "gd",
+ "initialWeights": {
+ "dense": [
+ 0.0,
+ 0.01,
+ 0.02,
+ 0.03,
+ 0.04,
+ 0.05,
+ 0.06,
+ 0.07,
+ 0.08,
+ 0.09,
+ 0.1,
+ 0.11,
+ 0.12,
+ 0.13,
+ 0.14,
+ 0.15,
+ 0.16,
+ ]
+ },
+ "probabilityCol": "prob",
+ "rawPredictionCol": "scores",
+ "thresholds": [1.0, 2.0],
+ },
+ "OneVsRest": {
+ "featuresCol": "input",
+ "labelCol": "target",
+ "predictionCol": "pred",
+ "rawPredictionCol": "scores",
+ "weightCol": "weight",
+ "parallelism": 3,
+ },
+}
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--remote", default="sc://localhost:15002")
+ parser.add_argument("--out", type=Path,
default=Path("tests/golden/remaining_classifiers.json"))
+ args = parser.parse_args()
+ spark = SparkSession.builder.remote(args.remote).getOrCreate()
+ cases = []
+ try:
+ for name, values in VALUES.items():
+ variants = [{}, values]
+ if name == "MultilayerPerceptronClassifier":
+ variants.append(
+ dict(
+ values,
+ initialWeights={"size": 17, "indices": [0, 16],
"values": [0.1, -0.2]},
+ )
+ )
+ for variant in variants:
+ options = dict(variant)
+ if "initialWeights" in options:
+ vector = options["initialWeights"]
+ options["initialWeights"] = (
+ Vectors.dense(vector["dense"])
+ if "dense" in vector
+ else Vectors.sparse(vector["size"], vector["indices"],
vector["values"])
+ )
+ thresholds = (
+ options.pop("thresholds", None)
+ if name == "MultilayerPerceptronClassifier"
+ else None
+ )
+ estimator = getattr(classification, name)(**options)
+ if thresholds is not None:
+ estimator.setThresholds(thresholds)
+ params = serialize_ml_params(estimator, spark.client)
+ cases.append(
+ {
+ "class": name,
+ "values": variant,
+ "params_b64": base64.b64encode(
+ params.SerializeToString(deterministic=True)
+ ).decode(),
+ }
+ )
+ args.out.write_text(
+ json.dumps(
+ {"source": "apache/spark v4.3.0 pyspark.ml.classification",
"cases": cases},
+ indent=2,
+ )
+ + "\n"
+ )
+ finally:
+ spark.stop()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/golden/remaining_classifiers.json
b/tests/golden/remaining_classifiers.json
new file mode 100644
index 00000000..577e7f3a
--- /dev/null
+++ b/tests/golden/remaining_classifiers.json
@@ -0,0 +1,142 @@
+{
+ "source": "apache/spark v4.3.0 pyspark.ml.classification",
+ "cases": [
+ {
+ "class": "FMClassifier",
+ "values": {},
+ "params_b64": ""
+ },
+ {
+ "class": "FMClassifier",
+ "values": {
+ "featuresCol": "input",
+ "labelCol": "target",
+ "predictionCol": "pred",
+ "probabilityCol": "prob",
+ "rawPredictionCol": "scores",
+ "factorSize": 2,
+ "fitIntercept": false,
+ "fitLinear": false,
+ "regParam": 0.1,
+ "miniBatchFraction": 0.5,
+ "initStd": 0.2,
+ "maxIter": 50,
+ "stepSize": 0.3,
+ "tol": 1e-08,
+ "solver": "gd",
+ "thresholds": [
+ 1.0,
+ 2.0
+ ],
+ "seed": 8589934592
+ },
+ "params_b64":
"ChAKCmZhY3RvclNpemUSAjACChYKC2ZlYXR1cmVzQ29sEgdqBWlucHV0ChIKDGZpdEludGVyY2VwdBICGAAKDwoJZml0TGluZWFyEgIYAAoUCgdpbml0U3RkEglZmpmZmZmZyT8KFAoIbGFiZWxDb2wSCGoGdGFyZ2V0Cg0KB21heEl0ZXISAjAyCh4KEW1pbmlCYXRjaEZyYWN0aW9uEglZAAAAAAAA4D8KFwoNcHJlZGljdGlvbkNvbBIGagRwcmVkChgKDnByb2JhYmlsaXR5Q29sEgZqBHByb2IKHAoQcmF3UHJlZGljdGlvbkNvbBIIagZzY29yZXMKFQoIcmVnUGFyYW0SCVmamZmZmZm5PwoOCgRzZWVkEgY4gICAgCAKDgoGc29sdmVyEgRqAmdkChUKCHN0ZXBTaXplEglZMzMzMzMz0z8KKwoKdGhyZXNob2xkcxIdsgEaCgJKABI
[...]
+ },
+ {
+ "class": "MultilayerPerceptronClassifier",
+ "values": {},
+ "params_b64": ""
+ },
+ {
+ "class": "MultilayerPerceptronClassifier",
+ "values": {
+ "featuresCol": "input",
+ "labelCol": "target",
+ "predictionCol": "pred",
+ "maxIter": 50,
+ "tol": 1e-08,
+ "seed": 8589934592,
+ "layers": [
+ 2,
+ 3,
+ 2
+ ],
+ "blockSize": 4,
+ "stepSize": 0.1,
+ "solver": "gd",
+ "initialWeights": {
+ "dense": [
+ 0.0,
+ 0.01,
+ 0.02,
+ 0.03,
+ 0.04,
+ 0.05,
+ 0.06,
+ 0.07,
+ 0.08,
+ 0.09,
+ 0.1,
+ 0.11,
+ 0.12,
+ 0.13,
+ 0.14,
+ 0.15,
+ 0.16
+ ]
+ },
+ "probabilityCol": "prob",
+ "rawPredictionCol": "scores",
+ "thresholds": [
+ 1.0,
+ 2.0
+ ]
+ },
+ "params_b64":
"Cg8KCWJsb2NrU2l6ZRICMAQKFgoLZmVhdHVyZXNDb2wSB2oFaW5wdXQK7AEKDmluaXRpYWxXZWlnaHRzEtkBwgHVAQouugErCgN1ZHQSJG9yZy5hcGFjaGUuc3BhcmsubWwubGluYWxnLlZlY3RvclVEVBICIAESBAoCCgASBAoCCgASkgHKAY4BKosBCogBAAAAAAAAAAB7FK5H4XqEP3sUrkfhepQ/uB6F61G4nj97FK5H4XqkP5qZmZmZmak/uB6F61G4rj/sUbgeheuxP3sUrkfherQ/CtejcD0Ktz+amZmZmZm5Pylcj8L1KLw/uB6F61G4vj+kcD0K16PAP+xRuB6F68E/MzMzMzMzwz97FK5H4XrEPwoUCghsYWJlbENvbBIIagZ0YXJnZXQKHQoGbGF5ZXJzEhOyARAKAjIAEgIwAhICMAMSAjACCg0KB21heEl0ZXISAjAyChcKDXB
[...]
+ },
+ {
+ "class": "MultilayerPerceptronClassifier",
+ "values": {
+ "featuresCol": "input",
+ "labelCol": "target",
+ "predictionCol": "pred",
+ "maxIter": 50,
+ "tol": 1e-08,
+ "seed": 8589934592,
+ "layers": [
+ 2,
+ 3,
+ 2
+ ],
+ "blockSize": 4,
+ "stepSize": 0.1,
+ "solver": "gd",
+ "initialWeights": {
+ "size": 17,
+ "indices": [
+ 0,
+ 16
+ ],
+ "values": [
+ 0.1,
+ -0.2
+ ]
+ },
+ "probabilityCol": "prob",
+ "rawPredictionCol": "scores",
+ "thresholds": [
+ 1.0,
+ 2.0
+ ]
+ },
+ "params_b64":
"Cg8KCWJsb2NrU2l6ZRICMAQKFgoLZmVhdHVyZXNDb2wSB2oFaW5wdXQKcQoOaW5pdGlhbFdlaWdodHMSX8IBXAouugErCgN1ZHQSJG9yZy5hcGFjaGUuc3BhcmsubWwubGluYWxnLlZlY3RvclVEVBICIAASAjAREgnKAQYSBAoCABASF8oBFCoSChCamZmZmZm5P5qZmZmZmcm/ChQKCGxhYmVsQ29sEghqBnRhcmdldAodCgZsYXllcnMSE7IBEAoCMgASAjACEgIwAxICMAIKDQoHbWF4SXRlchICMDIKFwoNcHJlZGljdGlvbkNvbBIGagRwcmVkChgKDnByb2JhYmlsaXR5Q29sEgZqBHByb2IKHAoQcmF3UHJlZGljdGlvbkNvbBIIagZzY29yZXMKDgoEc2VlZBIGOICAgIAgCg4KBnNvbHZlchIEagJnZAoVCghzdGVwU2l6ZRIJWZq
[...]
+ },
+ {
+ "class": "OneVsRest",
+ "values": {},
+ "params_b64": ""
+ },
+ {
+ "class": "OneVsRest",
+ "values": {
+ "featuresCol": "input",
+ "labelCol": "target",
+ "predictionCol": "pred",
+ "rawPredictionCol": "scores",
+ "weightCol": "weight",
+ "parallelism": 3
+ },
+ "params_b64":
"ChYKC2ZlYXR1cmVzQ29sEgdqBWlucHV0ChQKCGxhYmVsQ29sEghqBnRhcmdldAoRCgtwYXJhbGxlbGlzbRICMAMKFwoNcHJlZGljdGlvbkNvbBIGagRwcmVkChwKEHJhd1ByZWRpY3Rpb25Db2wSCGoGc2NvcmVzChUKCXdlaWdodENvbBIIagZ3ZWlnaHQ="
+ }
+ ]
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]