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 5b8644a2 [SPARK-61616][CONNECT] Support native AFTSurvivalRegression,
IsotonicRegression and FMRegressor
5b8644a2 is described below
commit 5b8644a204d8b4b9434009c00dabc889a26aae1b
Author: Ruifeng Zheng <[email protected]>
AuthorDate: Fri Nov 13 14:51:09 2026 +0900
[SPARK-61616][CONNECT] Support native AFTSurvivalRegression,
IsotonicRegression and FMRegressor
### What changes were proposed in this pull request?
Add the three remaining native regression estimators,
AFTSurvivalRegression, IsotonicRegression and FMRegressor, in the Rust API and
Rust-backed Python client. All eight PySpark 4.3.0 regression estimators now
support native fitting and DataFrame transforms.
- AFT supports censoring, an optional intercept and quantile output, with
all 11 constructor parameters and named setters.
- Isotonic supports scalar features or a selected vector component,
instance weights and increasing/decreasing regression, with all six constructor
parameters and named setters.
- FM supports interaction, linear and intercept terms, both `adamW` and
`gd`, and all 14 constructor parameters and named setters.
The implementations use the existing Spark Connect fit command and
cached-model ownership path. Add official parameter/numerical fixtures, Rust
and Python tests, CI coverage and compatibility documentation. Exclude
asynchronous model deletions from the existing label-validation test's request
count.
### Why are the changes needed?
These are the remaining missing native regression estimators. Users can now
fit them through either the Rust API or the Rust-backed Python API.
### Does this PR introduce _any_ user-facing change?
Yes. The estimators are available under `spark_connect::ml`,
`pyspark.ml.connect.regression` and the `pyspark.ml.connect` re-exports. Python
constructors preserve official PySpark's parameter order, defaults and type
conversions.
This covers construction, parameter setters, fitting and DataFrame
transforms. Python returns the common `MLModel`; specialized model inspection,
single-instance prediction and persistence remain outside these native wrappers.
### How was this patch tested?
- 673 Rust unit tests, four live regression tests, and a golden test
covering six official parameter fixtures passed.
- All 36 regression behavior cases passed with both official PySpark 4.3.0
and the native Python client; two additional shared model lifetime/session
tests passed with the native client.
- 2,118 Python offline tests passed (8 skipped), including parameter
conversion, constructor signatures and wire-format checks.
- All Rust integration tests compiled, including the WASM configuration.
Rust formatting and Python lint/format checks passed. Core Clippy passed;
workspace Clippy reports pre-existing errors, with no new warning or error
sites introduced.
- Public SQL API comparison found no gaps across 12 classes, excluding the
documented transport internals. All three new constructor signatures and named
setter sets match official PySpark.
- Official Spark 4.3.0 Connect suite through the Rust transport: 2,638
passed, 589 skipped across 87 files, with zero unexpected failures, using
local[4] and Spark's default shuffle setting. The three artifact/local-cluster
test files require a separate cluster environment and were excluded.
### Was this patch authored or co-authored using generative AI tooling?
Generated-by: Codex (GPT-6)
This pull request and its description were written by Isaac.
Closes #616 from zhengruifeng/add-remaining-regressors.
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 | 3 +
crates/pyspark-rs/src/ml.rs | 405 ++++++++++++-
crates/spark-connect/src/ml.rs | 666 +++++++++++++++++++++
.../tests/e2e_remaining_regressors.rs | 218 +++++++
.../tests/remaining_regressors_golden.rs | 74 +++
docs/compatibility.md | 38 ++
python/pyspark/ml/connect/__init__.py | 6 +
python/pyspark/ml/connect/regression.py | 6 +
python/tests/test_ml_e2e.py | 10 +-
python/tests/test_ml_offline.py | 42 +-
python/tests/test_remaining_regressors_e2e.py | 169 ++++++
scripts/capture_remaining_regressors_golden.py | 135 +++++
tests/golden/remaining_regressors.json | 382 ++++++++++++
14 files changed, 2146 insertions(+), 12 deletions(-)
diff --git a/.github/workflows/build_python_connect.yml
b/.github/workflows/build_python_connect.yml
index df841a25..76cd0dd9 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
tests/test_remaining_classifiers_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 tests/test_remaining_regressors_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_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 e2e_coverage --test e2e_linear_svc --test
e2e_linear_regression --test e2e_generalized_linear_regression --test
e2e_remaining_classifiers --test e2e_remaining_regressors --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 00c9c703..02d96a9c 100644
--- a/crates/pyspark-rs/src/lib.rs
+++ b/crates/pyspark-rs/src/lib.rs
@@ -247,6 +247,9 @@ fn _pyspark(_py: Python<'_>, m: &Bound<'_, PyModule>) ->
PyResult<()> {
m.add_class::<ml::PyOneVsRest>()?;
m.add_class::<ml::PyLinearRegression>()?;
+ m.add_class::<ml::PyAFTSurvivalRegression>()?;
+ m.add_class::<ml::PyIsotonicRegression>()?;
+ m.add_class::<ml::PyFMRegressor>()?;
m.add_class::<ml::PyGeneralizedLinearRegression>()?;
m.add_class::<ml::PyDecisionTreeClassifier>()?;
m.add_class::<ml::PyNaiveBayes>()?;
diff --git a/crates/pyspark-rs/src/ml.rs b/crates/pyspark-rs/src/ml.rs
index 615f4685..ae67e4ae 100644
--- a/crates/pyspark-rs/src/ml.rs
+++ b/crates/pyspark-rs/src/ml.rs
@@ -16,13 +16,14 @@ use pyo3::pyclass::boolean_struct::False;
use pyo3::types::{PyDict, PyList, PyTuple, PyType};
use pyo3::PyClass;
use spark_connect::ml::{
- BinaryClassificationEvaluator, BisectingKMeans, Classifier, CrossValidator,
- DecisionTreeClassifier, DecisionTreeRegressor, Estimator, Evaluator,
FMClassifier,
- GBTClassifier, GBTRegressor, GaussianMixture, GeneralizedLinearRegression,
KMeans,
- LinearRegression, LinearSVC, LogisticRegression, MlOperator, MlVector,
Model,
- MulticlassClassificationEvaluator, MultilayerPerceptronClassifier,
NaiveBayes, OneVsRest,
- Params, Pipeline, RandomForestClassifier, RandomForestRegressor,
RegressionEvaluator,
- StringIndexer, Transformer, VectorAssembler,
+ AFTSurvivalRegression, BinaryClassificationEvaluator, BisectingKMeans,
Classifier,
+ CrossValidator, DecisionTreeClassifier, DecisionTreeRegressor, Estimator,
Evaluator,
+ FMClassifier, FMRegressor, GBTClassifier, GBTRegressor, GaussianMixture,
+ GeneralizedLinearRegression, IsotonicRegression, KMeans, LinearRegression,
LinearSVC,
+ LogisticRegression, MlOperator, MlVector, Model,
MulticlassClassificationEvaluator,
+ MultilayerPerceptronClassifier, NaiveBayes, OneVsRest, Params, Pipeline,
+ RandomForestClassifier, RandomForestRegressor, RegressionEvaluator,
StringIndexer, Transformer,
+ VectorAssembler,
};
use spark_connect::DataFrame;
@@ -2297,6 +2298,393 @@ impl PyGeneralizedLinearRegression {
}
}
+/// Weibull accelerated failure time regression using Spark's JVM
implementation.
+#[pyclass(
+ name = "AFTSurvivalRegression",
+ module = "pyspark.ml.connect.regression"
+)]
+pub struct PyAFTSurvivalRegression {
+ inner: AFTSurvivalRegression,
+ unsendable: Vec<&'static str>,
+}
+
+const AFTSURVIVAL_REGRESSION_PARAMS: &[(&str, Kind)] = &[
+ ("featuresCol", Kind::Str),
+ ("labelCol", Kind::Str),
+ ("predictionCol", Kind::Str),
+ ("fitIntercept", Kind::Bool),
+ ("maxIter", Kind::Int),
+ ("tol", Kind::Float),
+ ("censorCol", Kind::Str),
+ ("quantileProbabilities", Kind::FloatList),
+ ("quantilesCol", Kind::Str),
+ ("aggregationDepth", Kind::Int),
+ ("maxBlockSizeInMB", Kind::Float),
+];
+
+#[pymethods]
+impl PyAFTSurvivalRegression {
+ #[new]
+ #[pyo3(signature = (*args, **kwargs), text_signature = "(*,
featuresCol='features', labelCol='label', predictionCol='prediction',
fitIntercept=True, maxIter=100, tol=1e-06, censorCol='censor',
quantileProbabilities=[0.01, 0.05, 0.1, 0.25, 0.5, 0.75, 0.9, 0.95, 0.99],
quantilesCol=None, aggregationDepth=2, maxBlockSizeInMB=0.0)")]
+ fn new(args: &Bound<'_, PyTuple>, kwargs: Option<&Bound<'_, PyDict>>) ->
PyResult<Self> {
+ let mut this = Self {
+ inner: AFTSurvivalRegression::new(),
+ unsendable: Vec::new(),
+ };
+ init_params(
+ &mut this,
+ "AFTSurvivalRegression",
+ &[],
+ AFTSURVIVAL_REGRESSION_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 = "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 = "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 = "setCensorCol")]
+ fn set_censor_col<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "censorCol", Kind::Str, value)
+ }
+
+ #[pyo3(name = "setQuantileProbabilities")]
+ fn set_quantile_probabilities<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "quantileProbabilities", Kind::FloatList, value)
+ }
+
+ #[pyo3(name = "setQuantilesCol")]
+ fn set_quantiles_col<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "quantilesCol", Kind::Str, value)
+ }
+
+ #[pyo3(name = "setAggregationDepth")]
+ fn set_aggregation_depth<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "aggregationDepth", Kind::Int, value)
+ }
+
+ #[pyo3(name = "setMaxBlockSizeInMB")]
+ fn set_max_block_size_in_mb<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "maxBlockSizeInMB", Kind::Float, value)
+ }
+
+ fn fit(slf: &Bound<'_, Self>, dataset: &Bound<'_, PyAny>) ->
PyResult<PyMLModel> {
+ fit_native(slf, dataset, None)
+ }
+}
+
+/// Univariate isotonic or antitonic regression using Spark's JVM
implementation.
+#[pyclass(name = "IsotonicRegression", module =
"pyspark.ml.connect.regression")]
+pub struct PyIsotonicRegression {
+ inner: IsotonicRegression,
+ unsendable: Vec<&'static str>,
+}
+
+const ISOTONIC_REGRESSION_PARAMS: &[(&str, Kind)] = &[
+ ("featuresCol", Kind::Str),
+ ("labelCol", Kind::Str),
+ ("predictionCol", Kind::Str),
+ ("weightCol", Kind::Str),
+ ("isotonic", Kind::Bool),
+ ("featureIndex", Kind::Int),
+];
+
+#[pymethods]
+impl PyIsotonicRegression {
+ #[new]
+ #[pyo3(signature = (*args, **kwargs), text_signature = "(*,
featuresCol='features', labelCol='label', predictionCol='prediction',
weightCol=None, isotonic=True, featureIndex=0)")]
+ fn new(args: &Bound<'_, PyTuple>, kwargs: Option<&Bound<'_, PyDict>>) ->
PyResult<Self> {
+ let mut this = Self {
+ inner: IsotonicRegression::new(),
+ unsendable: Vec::new(),
+ };
+ init_params(
+ &mut this,
+ "IsotonicRegression",
+ &[],
+ ISOTONIC_REGRESSION_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 = "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 = "setIsotonic")]
+ fn set_isotonic<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "isotonic", Kind::Bool, value)
+ }
+
+ #[pyo3(name = "setFeatureIndex")]
+ fn set_feature_index<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "featureIndex", Kind::Int, value)
+ }
+
+ fn fit(slf: &Bound<'_, Self>, dataset: &Bound<'_, PyAny>) ->
PyResult<PyMLModel> {
+ fit_native(slf, dataset, None)
+ }
+}
+
+/// Factorization machines regression using Spark's JVM implementation.
+#[pyclass(name = "FMRegressor", module = "pyspark.ml.connect.regression")]
+pub struct PyFMRegressor {
+ inner: FMRegressor,
+ unsendable: Vec<&'static str>,
+}
+
+const FMREGRESSOR_PARAMS: &[(&str, Kind)] = &[
+ ("featuresCol", Kind::Str),
+ ("labelCol", Kind::Str),
+ ("predictionCol", 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),
+ ("seed", Kind::Int),
+];
+
+#[pymethods]
+impl PyFMRegressor {
+ #[new]
+ #[pyo3(signature = (*args, **kwargs), text_signature = "(*,
featuresCol='features', labelCol='label', predictionCol='prediction',
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', seed=None)")]
+ fn new(args: &Bound<'_, PyTuple>, kwargs: Option<&Bound<'_, PyDict>>) ->
PyResult<Self> {
+ let mut this = Self {
+ inner: FMRegressor::new(),
+ unsendable: Vec::new(),
+ };
+ init_params(
+ &mut this,
+ "FMRegressor",
+ &[],
+ FMREGRESSOR_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 = "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 = "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)
+ }
+}
+
/// Decision tree classifier fitted and cached by Spark Connect.
#[pyclass(
name = "DecisionTreeClassifier",
@@ -4413,6 +4801,9 @@ native!(
PyMultilayerPerceptronClassifier => MultilayerPerceptronClassifier,
PyOneVsRest => OneVsRest,
PyLinearRegression => LinearRegression,
+ PyAFTSurvivalRegression => AFTSurvivalRegression,
+ PyIsotonicRegression => IsotonicRegression,
+ PyFMRegressor => FMRegressor,
PyGeneralizedLinearRegression => GeneralizedLinearRegression,
PyDecisionTreeClassifier => DecisionTreeClassifier,
PyNaiveBayes => NaiveBayes,
diff --git a/crates/spark-connect/src/ml.rs b/crates/spark-connect/src/ml.rs
index bc4b5fe5..d6117e39 100644
--- a/crates/spark-connect/src/ml.rs
+++ b/crates/spark-connect/src/ml.rs
@@ -3385,6 +3385,672 @@ impl Model for GeneralizedLinearRegressionModel {
}
}
+/// Weibull accelerated failure time regression using Spark's JVM
implementation.
+///
+/// Unset parameters use Spark's defaults.
+#[derive(Debug, Clone)]
+pub struct AFTSurvivalRegression {
+ operator: MlOperator,
+ params: Params,
+}
+
+impl AFTSurvivalRegression {
+ pub fn new() -> Self {
+ Self {
+ operator: MlOperator::new(
+ "org.apache.spark.ml.regression.AFTSurvivalRegression",
+ 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`.
+ 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`.
+ 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`.
+ pub fn prediction_col(&self) -> &str {
+ self.params.string_or("predictionCol", "prediction")
+ }
+
+ /// Set `fitIntercept`.
+ pub fn set_fit_intercept(mut self, value: bool) -> Self {
+ self.params = self.params.set_param_bool("fitIntercept", value);
+ self
+ }
+
+ /// Get `fitIntercept`.
+ pub fn fit_intercept(&self) -> bool {
+ self.params.bool_or("fitIntercept", true)
+ }
+
+ /// Set `maxIter`.
+ pub fn set_max_iter(mut self, value: i32) -> Self {
+ self.params = self.params.set_param_int32("maxIter", value);
+ self
+ }
+
+ /// Get `maxIter`.
+ 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`.
+ pub fn tol(&self) -> f64 {
+ self.params.double_or("tol", 1e-06)
+ }
+
+ /// Set `censorCol`.
+ pub fn set_censor_col(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("censorCol", value);
+ self
+ }
+
+ /// Get `censorCol`.
+ pub fn censor_col(&self) -> &str {
+ self.params.string_or("censorCol", "censor")
+ }
+
+ /// Set `quantileProbabilities`.
+ pub fn set_quantile_probabilities(mut self, value: impl IntoIterator<Item
= f64>) -> Self {
+ self.params = self
+ .params
+ .set_param_double_array("quantileProbabilities", value);
+ self
+ }
+
+ /// Get `quantileProbabilities`.
+ pub fn quantile_probabilities(&self) -> Vec<f64> {
+ self.params
+ .double_array_opt("quantileProbabilities")
+ .unwrap_or_else(|| vec![0.01, 0.05, 0.1, 0.25, 0.5, 0.75, 0.9,
0.95, 0.99])
+ }
+
+ /// Set `quantilesCol`.
+ pub fn set_quantiles_col(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("quantilesCol", value);
+ self
+ }
+
+ /// Get `quantilesCol`.
+ pub fn quantiles_col(&self) -> Option<&str> {
+ self.params.string_opt("quantilesCol")
+ }
+
+ /// Set `aggregationDepth`.
+ pub fn set_aggregation_depth(mut self, value: i32) -> Self {
+ self.params = self.params.set_param_int32("aggregationDepth", value);
+ self
+ }
+
+ /// Get `aggregationDepth`.
+ pub fn aggregation_depth(&self) -> i32 {
+ self.params.int_or("aggregationDepth", 2)
+ }
+
+ /// Set `maxBlockSizeInMB`.
+ pub fn set_max_block_size_in_mb(mut self, value: f64) -> Self {
+ self.params = self.params.set_param_double("maxBlockSizeInMB", value);
+ self
+ }
+
+ /// Get `maxBlockSizeInMB`.
+ pub fn max_block_size_in_mb(&self) -> f64 {
+ self.params.double_or("maxBlockSizeInMB", 0.0)
+ }
+
+ fn model_from_info(
+ &self,
+ info: proto::ml_command_result::MlOperatorInfo,
+ session: &SparkSession,
+ ) -> spark_connect_core::error::Result<AFTSurvivalRegressionModel> {
+ let cached = CachedModel::from_info(&info, session,
"AFTSurvivalRegression")?;
+ Ok(AFTSurvivalRegressionModel {
+ operator: MlOperator::with_uid(
+ "org.apache.spark.ml.regression.AFTSurvivalRegressionModel",
+ info.uid.as_deref().unwrap_or(&self.operator.uid),
+ OperatorType::Model,
+ ),
+ params: self.params.clone(),
+ cached,
+ })
+ }
+}
+
+impl Default for AFTSurvivalRegression {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl Estimator for AFTSurvivalRegression {
+ 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 fitted regression 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 AFTSurvivalRegressionModel {
+ operator: MlOperator,
+ params: Params,
+ cached: CachedModel,
+}
+
+impl Transformer for AFTSurvivalRegressionModel {
+ 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 AFTSurvivalRegressionModel {
+ fn clone_box(&self) -> Box<dyn Model> {
+ Box::new(self.clone())
+ }
+}
+
+/// Univariate isotonic or antitonic regression using Spark's JVM
implementation.
+///
+/// Unset parameters use Spark's defaults.
+#[derive(Debug, Clone)]
+pub struct IsotonicRegression {
+ operator: MlOperator,
+ params: Params,
+}
+
+impl IsotonicRegression {
+ pub fn new() -> Self {
+ Self {
+ operator: MlOperator::new(
+ "org.apache.spark.ml.regression.IsotonicRegression",
+ 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`.
+ 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`.
+ 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`.
+ pub fn prediction_col(&self) -> &str {
+ self.params.string_or("predictionCol", "prediction")
+ }
+
+ /// Set `weightCol`.
+ pub fn set_weight_col(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("weightCol", value);
+ self
+ }
+
+ /// Get `weightCol`.
+ pub fn weight_col(&self) -> Option<&str> {
+ self.params.string_opt("weightCol")
+ }
+
+ /// Set `isotonic`.
+ pub fn set_isotonic(mut self, value: bool) -> Self {
+ self.params = self.params.set_param_bool("isotonic", value);
+ self
+ }
+
+ /// Get `isotonic`.
+ pub fn isotonic(&self) -> bool {
+ self.params.bool_or("isotonic", true)
+ }
+
+ /// Set `featureIndex`.
+ pub fn set_feature_index(mut self, value: i32) -> Self {
+ self.params = self.params.set_param_int32("featureIndex", value);
+ self
+ }
+
+ /// Get `featureIndex`.
+ pub fn feature_index(&self) -> i32 {
+ self.params.int_or("featureIndex", 0)
+ }
+
+ fn model_from_info(
+ &self,
+ info: proto::ml_command_result::MlOperatorInfo,
+ session: &SparkSession,
+ ) -> spark_connect_core::error::Result<IsotonicRegressionModel> {
+ let cached = CachedModel::from_info(&info, session,
"IsotonicRegression")?;
+ Ok(IsotonicRegressionModel {
+ operator: MlOperator::with_uid(
+ "org.apache.spark.ml.regression.IsotonicRegressionModel",
+ info.uid.as_deref().unwrap_or(&self.operator.uid),
+ OperatorType::Model,
+ ),
+ params: self.params.clone(),
+ cached,
+ })
+ }
+}
+
+impl Default for IsotonicRegression {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl Estimator for IsotonicRegression {
+ 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 fitted regression 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 IsotonicRegressionModel {
+ operator: MlOperator,
+ params: Params,
+ cached: CachedModel,
+}
+
+impl Transformer for IsotonicRegressionModel {
+ 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 IsotonicRegressionModel {
+ fn clone_box(&self) -> Box<dyn Model> {
+ Box::new(self.clone())
+ }
+}
+
+/// Factorization machines regression using Spark's JVM implementation.
+///
+/// Unset parameters use Spark's defaults.
+#[derive(Debug, Clone)]
+pub struct FMRegressor {
+ operator: MlOperator,
+ params: Params,
+}
+
+impl FMRegressor {
+ pub fn new() -> Self {
+ Self {
+ operator: MlOperator::new(
+ "org.apache.spark.ml.regression.FMRegressor",
+ 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`.
+ 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`.
+ 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`.
+ pub fn prediction_col(&self) -> &str {
+ self.params.string_or("predictionCol", "prediction")
+ }
+
+ /// Set `factorSize`.
+ pub fn set_factor_size(mut self, value: i32) -> Self {
+ self.params = self.params.set_param_int32("factorSize", value);
+ self
+ }
+
+ /// Get `factorSize`.
+ 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`.
+ 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`.
+ 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`.
+ 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`.
+ 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`.
+ 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`.
+ 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`.
+ 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`.
+ 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`.
+ pub fn solver(&self) -> &str {
+ self.params.string_or("solver", "adamW")
+ }
+
+ /// Set `seed`.
+ pub fn set_seed(mut self, value: i64) -> Self {
+ self.params = self.params.set_param_int_narrow("seed", value);
+ self
+ }
+
+ /// Get `seed`.
+ 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<FMRegressionModel> {
+ let cached = CachedModel::from_info(&info, session, "FMRegressor")?;
+ Ok(FMRegressionModel {
+ operator: MlOperator::with_uid(
+ "org.apache.spark.ml.regression.FMRegressionModel",
+ info.uid.as_deref().unwrap_or(&self.operator.uid),
+ OperatorType::Model,
+ ),
+ params: self.params.clone(),
+ cached,
+ })
+ }
+}
+
+impl Default for FMRegressor {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl Estimator for FMRegressor {
+ 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 fitted regression 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 FMRegressionModel {
+ operator: MlOperator,
+ params: Params,
+ cached: CachedModel,
+}
+
+impl Transformer for FMRegressionModel {
+ 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 FMRegressionModel {
+ fn clone_box(&self) -> Box<dyn Model> {
+ Box::new(self.clone())
+ }
+}
+
/// Decision tree classification using Spark's JVM implementation and ML
vector features.
///
/// Supports binary and multiclass labels. Unset parameters use Spark's
defaults. A single
diff --git a/crates/spark-connect/tests/e2e_remaining_regressors.rs
b/crates/spark-connect/tests/e2e_remaining_regressors.rs
new file mode 100644
index 00000000..ad842cbc
--- /dev/null
+++ b/crates/spark-connect/tests/e2e_remaining_regressors.rs
@@ -0,0 +1,218 @@
+//! Live native regression tests. Set SPARK_REMOTE to run against Spark
Connect.
+mod common;
+
+use common::live_session;
+use spark_connect::column::{col, lit, lit_double, lit_string};
+use spark_connect::expression::Expression;
+use spark_connect::ml::{AFTSurvivalRegression, Estimator, FMRegressor,
IsotonicRegression};
+use spark_connect::{Column, DataFrame};
+
+fn vectorize(df: DataFrame) -> DataFrame {
+ df.with_column(
+ "input",
+ Column::new(Expression::function(
+ "array_to_vector",
+ vec![col("xs").expression().clone()],
+ )),
+ )
+}
+
+fn predictions(df: DataFrame) -> Vec<f64> {
+ df.order_by(vec![col("id").asc().expression().clone()])
+ .select([col("pred")])
+ .collect()
+ .unwrap()
+ .into_iter()
+ .map(|r| r.get(0).unwrap().as_f64().unwrap())
+ .collect()
+}
+
+fn close(actual: &[f64], expected: &[f64], tolerance: f64) {
+ assert_eq!(actual.len(), expected.len());
+ for (a, e) in actual.iter().zip(expected) {
+ assert!(
+ (a - e).abs() <= tolerance * e.abs().max(1.0),
+ "expected {e}, got {a}"
+ );
+ }
+}
+
+#[test]
+fn aft_matches_official_censoring_quantiles_and_intercept() {
+ let Some(s) = live_session() else {
+ return;
+ };
+ let fixture: serde_json::Value = serde_json::from_str(include_str!(
+ "../../../tests/golden/remaining_regressors.json"
+ ))
+ .unwrap();
+ for case in fixture["aft"].as_array().unwrap() {
+ let rows = fixture["aft_rows"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .enumerate()
+ .map(|(id, row)| {
+ let censor = if case["censored"].as_bool().unwrap() {
+ row[1].as_f64().unwrap()
+ } else {
+ 1.0
+ };
+ format!(
+ "({id}, {}D, {censor}D, {}D, {}D)",
+ row[0].as_f64().unwrap(),
+ row[2][0].as_f64().unwrap(),
+ row[2][1].as_f64().unwrap()
+ )
+ })
+ .collect::<Vec<_>>()
+ .join(",");
+ let train = vectorize(s.sql(&format!("SELECT id, duration, observed,
array(x,y) AS xs FROM VALUES {rows} AS t(id,duration,observed,x,y)")).unwrap());
+ let mut estimator = AFTSurvivalRegression::new()
+ .set_feature_col("input")
+ .set_label_col("duration")
+ .set_prediction_col("pred")
+ .set_censor_col("observed")
+
.set_fit_intercept(case["options"]["fitIntercept"].as_bool().unwrap())
+ .set_max_iter(100)
+ .set_tol(1e-8)
+ .set_quantile_probabilities([0.2, 0.5, 0.8])
+ .set_quantiles_col("quantiles")
+ .set_aggregation_depth(2)
+ .set_max_block_size_in_mb(1.0);
+ let mut model = estimator.fit(&train).unwrap();
+ let quantiles = Expression::function(
+ "vector_to_array",
+ vec![
+ col("quantiles").expression().clone(),
+ lit_string("float64").expression().clone(),
+ ],
+ );
+ let mut cols = vec![col("pred")];
+ for i in 0..3 {
+ cols.push(Column::new(Expression::function(
+ "get",
+ vec![quantiles.clone(), lit(i).expression().clone()],
+ )));
+ }
+ let lazy = model
+ .transform(&train)
+ .unwrap()
+ .order_by(vec![col("id").asc().expression().clone()])
+ .select(cols);
+ drop(model);
+ let actual = lazy.collect().unwrap();
+ assert_eq!(actual.len(),
case["predictions"].as_array().unwrap().len());
+ for (i, row) in actual.iter().enumerate() {
+ let expected = [
+ case["predictions"][i].as_f64().unwrap(),
+ case["quantiles"][i][0].as_f64().unwrap(),
+ case["quantiles"][i][1].as_f64().unwrap(),
+ case["quantiles"][i][2].as_f64().unwrap(),
+ ];
+ let got = (0..4)
+ .map(|j| row.get(j).unwrap().as_f64().unwrap())
+ .collect::<Vec<_>>();
+ close(&got, &expected, 1e-6);
+ }
+ }
+}
+
+#[test]
+fn
isotonic_interpolates_weighted_scalar_and_vector_features_in_both_directions() {
+ let Some(s) = live_session() else {
+ return;
+ };
+ for isotonic in [true, false] {
+ for vector in [true, false] {
+ let sign = if isotonic { 1.0 } else { -1.0 };
+ let train = s.sql("SELECT x AS input, array(99.0D,x) AS xs, y AS
target, w AS weight FROM VALUES
(0.0D,0.0D,1.0D),(1.0D,3.0D,1.0D),(2.0D,1.0D,3.0D),(3.0D,4.0D,1.0D) AS
t(x,y,w)").unwrap().with_column("target", col("target") * lit_double(sign));
+ let held = s.sql("SELECT id, x AS input, array(99.0D,x) AS xs FROM
VALUES (0,-1.0D),(1,0.5D),(2,1.5D),(3,2.5D),(4,4.0D) AS t(id,x)").unwrap();
+ let (train, held) = if vector {
+ (vectorize(train), vectorize(held))
+ } else {
+ (train, held)
+ };
+ let mut estimator = IsotonicRegression::new()
+ .set_feature_col("input")
+ .set_label_col("target")
+ .set_prediction_col("pred")
+ .set_weight_col("weight")
+ .set_isotonic(isotonic)
+ .set_feature_index(if vector { 1 } else { 0 });
+ let mut model = estimator.fit(&train).unwrap();
+ let lazy = model.transform(&held).unwrap();
+ drop(model);
+ close(
+ &predictions(lazy),
+ &[0.0, 0.75 * sign, 1.5 * sign, 2.75 * sign, 4.0 * sign],
+ 1e-9,
+ );
+ }
+ }
+}
+
+#[test]
+fn
fm_regressor_learns_interactions_with_both_solvers_and_owns_each_fitted_model()
{
+ let Some(s) = live_session() else {
+ return;
+ };
+ let train = vectorize(s.sql("SELECT array(x,y) AS xs, x*y AS target FROM
VALUES (-1.0D),(0.0D),(1.0D) AS a(x) CROSS JOIN VALUES (-1.0D),(0.0D),(1.0D) AS
b(y)").unwrap());
+ let held = vectorize(s.sql("SELECT id,array(x,y) AS xs FROM VALUES
(0,0.5D,-2.0D),(1,-0.5D,-1.0D),(2,0.0D,1.5D) AS t(id,x,y)").unwrap());
+ for solver in ["adamW", "gd"] {
+ let mut estimator = FMRegressor::new()
+ .set_feature_col("input")
+ .set_label_col("target")
+ .set_prediction_col("pred")
+ .set_factor_size(2)
+ .set_fit_intercept(false)
+ .set_fit_linear(false)
+ .set_reg_param(0.0)
+ .set_mini_batch_fraction(1.0)
+ .set_init_std(0.1)
+ .set_max_iter(300)
+ .set_step_size(if solver == "gd" { 1.0 } else { 0.1 })
+ .set_tol(1e-8)
+ .set_solver(solver)
+ .set_seed(42);
+ let mut first = estimator.fit(&train).unwrap();
+ let mut second = estimator
+ .fit(&train.with_column("target", lit(0) - col("target")))
+ .unwrap();
+ let lazy = first.transform(&held).unwrap();
+ let other = second.transform(&held).unwrap();
+ drop(first);
+ drop(second);
+ close(&predictions(lazy), &[-1.0, 0.5, 0.0], 0.025);
+ close(&predictions(other), &[1.0, -0.5, 0.0], 0.025);
+ }
+}
+
+#[test]
+fn new_regressors_reject_invalid_parameters() {
+ let Some(s) = live_session() else {
+ return;
+ };
+ let train = vectorize(
+ s.sql("SELECT array(1.0D) AS xs, 1.0D AS label, 1.0D AS censor")
+ .unwrap(),
+ );
+ let estimators: Vec<Box<dyn Estimator>> = vec![
+ Box::new(AFTSurvivalRegression::new().set_quantile_probabilities([0.0,
1.0])),
+ Box::new(AFTSurvivalRegression::new().set_aggregation_depth(1)),
+ Box::new(AFTSurvivalRegression::new().set_max_block_size_in_mb(-1.0)),
+ Box::new(IsotonicRegression::new().set_feature_index(-1)),
+ Box::new(FMRegressor::new().set_factor_size(0)),
+ Box::new(FMRegressor::new().set_solver("invalid")),
+ Box::new(FMRegressor::new().set_mini_batch_fraction(0.0)),
+ Box::new(FMRegressor::new().set_reg_param(-1.0)),
+ ];
+ let train = train.with_column_renamed("input", "features");
+ for mut estimator in estimators {
+ assert!(
+ estimator.fit(&train).is_err(),
+ "{}",
+ estimator.operator().name
+ );
+ }
+}
diff --git a/crates/spark-connect/tests/remaining_regressors_golden.rs
b/crates/spark-connect/tests/remaining_regressors_golden.rs
new file mode 100644
index 00000000..720417a8
--- /dev/null
+++ b/crates/spark-connect/tests/remaining_regressors_golden.rs
@@ -0,0 +1,74 @@
+//! Parameter bytes captured from official PySpark, including integer widths
and double arrays.
+use base64::engine::general_purpose::STANDARD;
+use base64::Engine;
+use prost::Message;
+use spark_connect::ml::{AFTSurvivalRegression, Estimator, FMRegressor,
IsotonicRegression};
+
+#[test]
+fn remaining_regressors_match_official_parameters() {
+ let fixture: serde_json::Value = serde_json::from_str(include_str!(
+ "../../../tests/golden/remaining_regressors.json"
+ ))
+ .unwrap();
+ let estimators: Vec<Box<dyn Estimator>> = vec![
+ Box::new(AFTSurvivalRegression::new()),
+ Box::new(
+ AFTSurvivalRegression::new()
+ .set_feature_col("input")
+ .set_label_col("duration")
+ .set_prediction_col("pred")
+ .set_fit_intercept(false)
+ .set_max_iter(50)
+ .set_tol(1e-08)
+ .set_censor_col("observed")
+ .set_quantile_probabilities([0.2, 0.5, 0.8])
+ .set_quantiles_col("quantiles")
+ .set_aggregation_depth(3)
+ .set_max_block_size_in_mb(1.0),
+ ),
+ Box::new(IsotonicRegression::new()),
+ Box::new(
+ IsotonicRegression::new()
+ .set_feature_col("input")
+ .set_label_col("target")
+ .set_prediction_col("pred")
+ .set_weight_col("weight")
+ .set_isotonic(false)
+ .set_feature_index(1),
+ ),
+ Box::new(FMRegressor::new()),
+ Box::new(
+ FMRegressor::new()
+ .set_feature_col("input")
+ .set_label_col("target")
+ .set_prediction_col("pred")
+ .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_seed(8589934592),
+ ),
+ ];
+ let cases = fixture["cases"].as_array().unwrap();
+ assert_eq!(estimators.len(), cases.len());
+ for (estimator, case) in estimators.into_iter().zip(cases) {
+ 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"]);
+ assert_eq!(
+ estimator.operator().name,
+ format!(
+ "org.apache.spark.ml.regression.{}",
+ case["class"].as_str().unwrap()
+ )
+ );
+ }
+}
diff --git a/docs/compatibility.md b/docs/compatibility.md
index b1d8f63f..4b8a7771 100644
--- a/docs/compatibility.md
+++ b/docs/compatibility.md
@@ -744,3 +744,41 @@ 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.
+
+
+## Native AFTSurvivalRegression, IsotonicRegression and FMRegressor
+
+All eight regression estimators in PySpark 4.3.0 now have native Rust
fit/transform
+implementations. The three additions are available under `spark_connect::ml`
and
+`pyspark.ml.connect.regression`, and are re-exported from `pyspark.ml.connect`.
+They fit Spark's JVM estimators and retain the returned server-cached models
for
+as long as a model clone or transformed DataFrame needs them.
+
+- **AFTSurvivalRegression** fits a Weibull accelerated failure time model. It
+ accepts positive survival times and a censor column (1 for observed events, 0
+ for censored observations), and can produce a vector of requested quantiles.
+ All 11 constructor parameters have Rust and Python setters, including
+ `quantileProbabilities`, `quantilesCol`, and the aggregation/block-size
settings.
+- **IsotonicRegression** fits increasing or decreasing univariate regression.
+ It supports scalar features or a selected vector component (`featureIndex`),
+ instance weights, interpolation between fitted boundaries, and clamping
beyond
+ the training range. All six constructor parameters have setters.
+- **FMRegressor** fits factorization machines with pairwise interactions and
+ optional intercept and linear terms, using either `adamW` or `gd`. All 14
+ constructor parameters have setters, including factor size, initialization,
+ mini-batch fraction, regularization and seed.
+
+Unset parameters use Spark's defaults. The Python wrappers preserve PySpark's
+keyword-only constructor signatures and type conversion; numeric arrays are
+converted to ML vectors by the existing native fit/transform adapter.
+
+This support covers construction, configuration, fitting and DataFrame
+transforms. Python returns the common `MLModel`. Specialized model inspection
+(e.g. AFT coefficients/scale, isotonic boundaries/predictions, FM factors),
+single-instance prediction and model persistence are not exposed by these
+native wrappers.
+
+Parameter goldens come from official PySpark 4.3.0. Native Rust and Python
tests
+exercise censoring and quantiles, weighted isotonic interpolation, both FM
+solvers, validation errors and cached-model lifetimes. The Python behavior
tests
+also run unchanged against the official client.
diff --git a/python/pyspark/ml/connect/__init__.py
b/python/pyspark/ml/connect/__init__.py
index 0de15bf4..4a610ba9 100644
--- a/python/pyspark/ml/connect/__init__.py
+++ b/python/pyspark/ml/connect/__init__.py
@@ -24,6 +24,9 @@ from pyspark.ml.connect.classification import (
from pyspark.ml.connect.regression import (
GBTRegressor,
DecisionTreeRegressor,
+ AFTSurvivalRegression,
+ IsotonicRegression,
+ FMRegressor,
GeneralizedLinearRegression,
LinearRegression,
RandomForestRegressor,
@@ -77,6 +80,9 @@ __all__ = [
"GBTClassifier",
"GBTRegressor",
"RandomForestClassifier",
+ "AFTSurvivalRegression",
+ "IsotonicRegression",
+ "FMRegressor",
"GeneralizedLinearRegression",
"LinearRegression",
"DecisionTreeRegressor",
diff --git a/python/pyspark/ml/connect/regression.py
b/python/pyspark/ml/connect/regression.py
index a3741281..c9065855 100644
--- a/python/pyspark/ml/connect/regression.py
+++ b/python/pyspark/ml/connect/regression.py
@@ -1,9 +1,12 @@
"""Native regression estimators backed by Spark Connect's JVM ML API."""
from pyspark._pyspark import (
+ AFTSurvivalRegression,
DecisionTreeRegressor,
+ FMRegressor,
GBTRegressor,
GeneralizedLinearRegression,
+ IsotonicRegression,
LinearRegression,
RandomForestRegressor,
)
@@ -11,6 +14,9 @@ from pyspark._pyspark import (
__all__ = [
"GBTRegressor",
"DecisionTreeRegressor",
+ "AFTSurvivalRegression",
+ "IsotonicRegression",
+ "FMRegressor",
"GeneralizedLinearRegression",
"LinearRegression",
"RandomForestRegressor",
diff --git a/python/tests/test_ml_e2e.py b/python/tests/test_ml_e2e.py
index 2f2156cd..795d855b 100644
--- a/python/tests/test_ml_e2e.py
+++ b/python/tests/test_ml_e2e.py
@@ -247,14 +247,17 @@ def _native_estimators():
# Every native pyspark.ml.connect estimator, with the class of the model
that the server
# caches for its fit, and data that it fits.
from pyspark.ml.connect import (
+ AFTSurvivalRegression,
BisectingKMeans,
DecisionTreeClassifier,
DecisionTreeRegressor,
FMClassifier,
+ FMRegressor,
GaussianMixture,
GBTClassifier,
GBTRegressor,
GeneralizedLinearRegression,
+ IsotonicRegression,
KMeans,
LinearRegression,
LinearSVC,
@@ -268,6 +271,9 @@ def _native_estimators():
ml = "org.apache.spark.ml."
return [
+ (AFTSurvivalRegression(labelCol="duration", maxIter=2), ml +
"regression.AFTSurvivalRegressionModel"),
+ (IsotonicRegression(), ml + "regression.IsotonicRegressionModel"),
+ (FMRegressor(maxIter=2, seed=42), ml + "regression.FMRegressionModel"),
(GaussianMixture(k=2, seed=1, maxIter=2), ml +
"clustering.GaussianMixtureModel"),
(BisectingKMeans(k=2, seed=1), ml + "clustering.BisectingKMeansModel"),
(NaiveBayes(), ml + "classification.NaiveBayesModel"),
@@ -291,8 +297,8 @@ def _native_estimators():
def _native_training(session):
from pyspark.ml.linalg import Vectors
- rows = [(float(i % 2), Vectors.dense([float(i), float(i % 3)]), "ab"[i %
2]) for i in range(8)]
- return session.createDataFrame(rows, ["label", "features", "s"])
+ rows = [(float(i % 2), Vectors.dense([float(i), float(i % 3)]), "ab"[i %
2], float(i + 1), 1.0) for i in range(8)]
+ return session.createDataFrame(rows, ["label", "features", "s",
"duration", "censor"])
def
test_native_models_are_released_once_their_last_owner_is_gone_as_pyspark(session):
diff --git a/python/tests/test_ml_offline.py b/python/tests/test_ml_offline.py
index 08bbf62e..bd3f47b6 100644
--- a/python/tests/test_ml_offline.py
+++ b/python/tests/test_ml_offline.py
@@ -444,13 +444,14 @@ def
test_ml_connect_logistic_regression_checks_its_labels_before_its_fit_as_pysp
((0.5, 1.0), True, not_index),
]:
sent = len(service.execute_requests)
+ sent_requests = _requests_but_deletes(service)
service.query_payload = _labels_result(classes, double)
with pytest.raises(ValueError) as error:
connect.LogisticRegression().fit(df)
assert str(error.value) == message, classes
service.query_payload = None
# Only the label query is sent: no fit, whose command would be the
only one of the ML.
- assert len(service.execute_requests) == sent + 1, classes
+ assert _requests_but_deletes(service) == sent_requests + 1, classes
assert _commands_but_deletes(service, sent) == [], classes
sent = len(service.execute_requests)
@@ -883,6 +884,10 @@ def
test_ml_pipeline_and_cross_validator_fit_is_not_implemented(ml_mock):
# param in PySpark. Their constructors take them all but thresholds, which
PySpark's
# RandomForestClassifier takes by its setter only.
_NATIVE_PARAMS = {
+ 'AFTSurvivalRegression': {'featuresCol': 'str', 'labelCol': 'str',
'predictionCol': 'str', 'fitIntercept': 'bool', 'maxIter': 'int', 'tol':
'float', 'censorCol': 'str', 'quantileProbabilities': 'float_list',
'quantilesCol': 'str', 'aggregationDepth': 'int', 'maxBlockSizeInMB': 'float'},
+ 'IsotonicRegression': {'featuresCol': 'str', 'labelCol': 'str',
'predictionCol': 'str', 'weightCol': 'str', 'isotonic': 'bool', 'featureIndex':
'int'},
+ 'FMRegressor': {'featuresCol': 'str', 'labelCol': 'str', 'predictionCol':
'str', 'factorSize': 'int', 'fitIntercept': 'bool', 'fitLinear': 'bool',
'regParam': 'float', 'miniBatchFraction': 'float', 'initStd': 'float',
'maxIter': 'int', 'stepSize': 'float', 'tol': 'float', 'solver': 'str', 'seed':
'int'},
+
"StringIndexer": dict(inputCol="str", outputCol="str"),
"VectorAssembler": dict(inputCols="str_list", outputCol="str"),
"LogisticRegression": dict(
@@ -3646,3 +3651,38 @@ def
test_one_vs_rest_defers_base_param_validation_until_fit():
assert estimator.setClassifier(None) is estimator
with pytest.raises(ValueError, match="classifier"):
estimator.fit(None)
+
+
[email protected]("name", ["AFTSurvivalRegression",
"IsotonicRegression", "FMRegressor"])
[email protected]("use_setters", [False, True])
+def test_remaining_regressor_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 import connect
+ from pyspark.ml.connect import regression
+
+ cls = getattr(regression, name)
+ assert cls is getattr(native, name) is getattr(connect, name)
+ fixture = json.loads((Path(__file__).resolve().parents[2] /
"tests/golden/remaining_regressors.json").read_text())
+ defaults = fixture["defaults"][name]
+ 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
+ spark, service = ml_mock
+ models = []
+ for case in fixture["cases"]:
+ if case["class"] != name:
+ continue
+ estimator = cls() if use_setters else cls(**case["values"])
+ if use_setters:
+ for key, value in case["values"].items():
+ assert getattr(estimator, "set" + key[0].upper() +
key[1:])(value) is estimator
+ operator, params = _native_request(spark, service, estimator, models)
+ assert operator.name == "org.apache.spark.ml.regression." + name
+ assert params ==
pb2.MlParams.FromString(base64.b64decode(case["params_b64"]))
diff --git a/python/tests/test_remaining_regressors_e2e.py
b/python/tests/test_remaining_regressors_e2e.py
new file mode 100644
index 00000000..638d60ec
--- /dev/null
+++ b/python/tests/test_remaining_regressors_e2e.py
@@ -0,0 +1,169 @@
+#
+# 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.
+#
+"""Regression behavior tests, runnable unchanged with native or official
PySpark."""
+
+import gc
+import json
+import os
+from pathlib import Path
+
+import pytest
+from pyspark.errors import PySparkException
+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 _regressor(name):
+ try:
+ from pyspark.ml.connect import regression as native
+ except ImportError:
+ native = None
+ if native is not None and hasattr(native, "AFTSurvivalRegression"):
+ return getattr(native, name)
+ from pyspark.ml import regression as official
+
+ return getattr(official, name)
+
+
+def _estimator(name, options, setters):
+ cls = _regressor(name)
+ if not setters:
+ return cls(**options)
+ estimator = cls()
+ for key, value in options.items():
+ assert getattr(estimator, "set" + key[0].upper() + key[1:])(value) is
estimator
+ return estimator
+
+
+def _fixture():
+ return json.loads((Path(__file__).resolve().parents[2] /
"tests/golden/remaining_regressors.json").read_text())
+
+
[email protected]("case_index", range(4))
[email protected]("setters", [False, True], ids=["constructor",
"setters"])
+def test_aft_matches_official_censoring_quantiles_and_intercept(session,
case_index, setters):
+ fixture = _fixture()
+ case = fixture["aft"][case_index]
+ rows = [(i, y, c if case["censored"] else 1.0, Vectors.dense(x)) for i,
(y, c, x) in enumerate(fixture["aft_rows"])]
+ train = session.createDataFrame(rows, ["id", "duration", "observed",
"input"])
+ estimator = _estimator("AFTSurvivalRegression", case["options"], setters)
+ model = estimator.fit(train)
+ lazy = model.transform(train).orderBy("id").select("pred", "quantiles")
+ # A lazy transform must own its cached model after the Python handle is
gone.
+ del model
+ gc.collect()
+ result = lazy.collect()
+ assert [r.pred for r in result] == pytest.approx(case["predictions"],
rel=1e-6)
+ for row, expected in zip(result, case["quantiles"]):
+ assert list(row.quantiles) == pytest.approx(expected, rel=1e-6)
+ assert 0 < row.quantiles[0] < row.quantiles[1] < row.quantiles[2]
+ # Scaling every survival time scales predictions, including censored
observations.
+ if case["options"]["fitIntercept"]:
+ scaled = estimator.fit(train.withColumn("duration", F.col("duration")
* 2.0))
+ predictions =
scaled.transform(train).orderBy("id").select("pred").collect()
+ assert [r.pred for r in predictions] == pytest.approx([x * 2.0 for x
in case["predictions"]], rel=2e-5)
+
+
[email protected]("features", ["scalar", "dense", "sparse"])
[email protected]("isotonic", [True, False])
[email protected]("setters", [False, True], ids=["constructor",
"setters"])
+def test_isotonic_weights_feature_index_and_interpolation(session, features,
isotonic, setters):
+ def feature(x):
+ if features == "scalar":
+ return float(x)
+ if features == "dense":
+ return Vectors.dense([99.0, x])
+ return Vectors.sparse(2, [0, 1], [99.0, float(x)])
+
+ sign = 1.0 if isotonic else -1.0
+ rows = [(feature(x), sign * y, w) for x, y, w in [(0, 0.0, 1.0), (1, 3.0,
1.0), (2, 1.0, 3.0), (3, 4.0, 1.0)]]
+ train = session.createDataFrame(rows, ["input", "target", "weight"])
+ options = dict(featuresCol="input", labelCol="target",
predictionCol="pred", weightCol="weight", isotonic=isotonic, featureIndex=0 if
features == "scalar" else 1)
+ estimator = _estimator("IsotonicRegression", options, setters)
+ held = session.createDataFrame([(i, feature(x)) for i, x in
enumerate([-1.0, 0.5, 1.5, 2.5, 4.0])], ["id", "input"])
+ model = estimator.fit(train)
+ lazy = model.transform(held).orderBy("id")
+ del model
+ gc.collect()
+ assert [r.pred for r in lazy.collect()] == pytest.approx([sign*x for x in
[0.0, 0.75, 1.5, 2.75, 4.0]])
+ # Without weightCol, the pooled block is 2.0 instead of the weighted 1.5.
+ options.pop("weightCol")
+ unweighted =
_regressor("IsotonicRegression")(**options).fit(train).transform(held).orderBy("id")
+ assert [r.pred for r in unweighted.collect()] == pytest.approx([sign*x for
x in [0.0, 1.0, 2.0, 3.0, 4.0]])
+
+
[email protected]("solver", ["adamW", "gd"])
[email protected]("setters", [False, True], ids=["constructor",
"setters"])
+def test_fm_regressor_learns_interactions_with_both_solvers(session, solver,
setters):
+ rows = [(Vectors.dense([x, y]), x*y) for x in [-1.0, 0.0, 1.0] for y in
[-1.0, 0.0, 1.0]]
+ train = session.createDataFrame(rows, ["input", "target"])
+ options = dict(featuresCol="input", labelCol="target",
predictionCol="pred", factorSize=2, fitIntercept=False, fitLinear=False,
regParam=0.0, miniBatchFraction=1.0, initStd=0.1, maxIter=300, stepSize=1.0 if
solver == "gd" else 0.1, tol=1e-8, solver=solver, seed=42)
+ estimator = _estimator("FMRegressor", options, setters)
+ held = session.createDataFrame([(0, Vectors.dense([0.5, -2.0])), (1,
Vectors.sparse(2, [0, 1], [-0.5, -1.0])), (2, Vectors.dense([0.0, 1.5]))],
["id", "input"])
+ first = estimator.fit(train)
+ second = estimator.fit(train.withColumn("target", -F.col("target")))
+ lazy = first.transform(held).orderBy("id")
+ other = second.transform(held).orderBy("id")
+ del first, second
+ gc.collect()
+ assert [r.pred for r in lazy.collect()] == pytest.approx([-1.0, 0.5, 0.0],
abs=0.025)
+ assert [r.pred for r in other.collect()] == pytest.approx([1.0, -0.5,
0.0], abs=0.025)
+
+
+def test_fm_regressor_fits_intercept_and_linear_terms(session):
+ train = session.createDataFrame([(Vectors.dense([x]), 2*x+1) for x in
[-1.0, -0.5, 0.0, 0.5, 1.0]], ["features", "label"])
+ model = _regressor("FMRegressor")(factorSize=2, maxIter=300, stepSize=0.1,
tol=1e-8, seed=42).fit(train)
+ values = [r.prediction for r in model.transform(train).collect()]
+ assert values == pytest.approx([-1.0, 0.0, 1.0, 2.0, 3.0], abs=0.025)
+
+
[email protected]("name,options", [
+ ("AFTSurvivalRegression", {"quantileProbabilities": [0.0, 1.0]}),
+ ("AFTSurvivalRegression", {"aggregationDepth": 1}),
+ ("AFTSurvivalRegression", {"maxBlockSizeInMB": -1.0}),
+ ("IsotonicRegression", {"featureIndex": -1}),
+ ("FMRegressor", {"factorSize": 0}),
+ ("FMRegressor", {"solver": "invalid"}),
+ ("FMRegressor", {"miniBatchFraction": 0.0}),
+ ("FMRegressor", {"regParam": -1.0}),
+])
+def test_regressors_reject_invalid_parameters(session, name, options):
+ train = session.createDataFrame([(Vectors.dense([0.0]), 1.0, 1.0),
(Vectors.dense([1.0]), 2.0, 0.0)], ["features", "label", "censor"])
+ estimator = _regressor(name)(**options)
+ with pytest.raises((ValueError, RuntimeError, PySparkException)):
+ estimator.fit(train)
+
+
[email protected]("column,value", [("label", 0.0), ("label", -1.0),
("censor", 2.0)])
+def test_aft_rejects_nonpositive_survival_times_and_invalid_censor(session,
column, value):
+ train = session.createDataFrame([(Vectors.dense([0.0]), 1.0, 1.0),
(Vectors.dense([1.0]), 2.0, 0.0)], ["features", "label", "censor"])
+ estimator = _regressor("AFTSurvivalRegression")()
+ with pytest.raises((ValueError, RuntimeError, PySparkException)):
+ estimator.fit(train.withColumn(column, F.lit(value)))
diff --git a/scripts/capture_remaining_regressors_golden.py
b/scripts/capture_remaining_regressors_golden.py
new file mode 100644
index 00000000..1b22eefb
--- /dev/null
+++ b/scripts/capture_remaining_regressors_golden.py
@@ -0,0 +1,135 @@
+#!/usr/bin/env python3
+"""Capture parameter and AFT prediction goldens using official PySpark
4.3.0."""
+
+import argparse
+import base64
+import inspect
+import json
+from pathlib import Path
+
+from pyspark.ml import regression
+from pyspark.ml.connect.serialize import serialize_ml_params
+from pyspark.ml.linalg import Vectors
+from pyspark.sql import SparkSession
+
+VALUES = {
+ "AFTSurvivalRegression": {
+ "featuresCol": "input",
+ "labelCol": "duration",
+ "predictionCol": "pred",
+ "fitIntercept": False,
+ "maxIter": 50,
+ "tol": 1e-08,
+ "censorCol": "observed",
+ "quantileProbabilities": [0.2, 0.5, 0.8],
+ "quantilesCol": "quantiles",
+ "aggregationDepth": 3,
+ "maxBlockSizeInMB": 1.0,
+ },
+ "IsotonicRegression": {
+ "featuresCol": "input",
+ "labelCol": "target",
+ "predictionCol": "pred",
+ "weightCol": "weight",
+ "isotonic": False,
+ "featureIndex": 1,
+ },
+ "FMRegressor": {
+ "featuresCol": "input",
+ "labelCol": "target",
+ "predictionCol": "pred",
+ "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",
+ "seed": 8589934592,
+ },
+}
+
+AFT_ROWS = [
+ (1.218, 1.0, [1.560, -0.605]),
+ (2.949, 0.0, [0.346, 2.158]),
+ (3.627, 0.0, [1.380, 0.231]),
+ (0.273, 1.0, [0.520, 1.151]),
+ (4.199, 0.0, [0.795, -0.226]),
+]
+
+
+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_regressors.json"))
+ args = parser.parse_args()
+ spark = SparkSession.builder.remote(args.remote).getOrCreate()
+ cases, defaults, aft = [], {}, []
+ try:
+ for name, values in VALUES.items():
+ cls = getattr(regression, name)
+ defaults[name] = {n: p.default for n, p in
inspect.signature(cls).parameters.items()}
+ for variant in [{}, values]:
+ estimator = cls(**variant)
+ params = serialize_ml_params(estimator, spark.client)
+ cases.append(
+ {
+ "class": name,
+ "values": variant,
+ "params_b64": base64.b64encode(
+ params.SerializeToString(deterministic=True)
+ ).decode(),
+ }
+ )
+ for fit_intercept in [False, True]:
+ for censored in [False, True]:
+ rows = [
+ (i, y, c if censored else 1.0, Vectors.dense(x))
+ for i, (y, c, x) in enumerate(AFT_ROWS)
+ ]
+ train = spark.createDataFrame(rows, ["id", "duration",
"observed", "input"])
+ options = dict(
+ featuresCol="input",
+ labelCol="duration",
+ predictionCol="pred",
+ censorCol="observed",
+ fitIntercept=fit_intercept,
+ maxIter=100,
+ tol=1e-8,
+ quantileProbabilities=[0.2, 0.5, 0.8],
+ quantilesCol="quantiles",
+ aggregationDepth=2,
+ maxBlockSizeInMB=1.0,
+ )
+ model = regression.AFTSurvivalRegression(**options).fit(train)
+ results = model.transform(train).orderBy("id").select("pred",
"quantiles").collect()
+ aft.append(
+ {
+ "options": options,
+ "censored": censored,
+ "predictions": [r.pred for r in results],
+ "quantiles": [list(r.quantiles) for r in results],
+ }
+ )
+ args.out.write_text(
+ json.dumps(
+ {
+ "source": "apache/spark v4.3.0 pyspark.ml.regression",
+ "defaults": defaults,
+ "cases": cases,
+ "aft_rows": AFT_ROWS,
+ "aft": aft,
+ },
+ indent=2,
+ )
+ + "\n"
+ )
+ finally:
+ spark.stop()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/golden/remaining_regressors.json
b/tests/golden/remaining_regressors.json
new file mode 100644
index 00000000..7f93a7a0
--- /dev/null
+++ b/tests/golden/remaining_regressors.json
@@ -0,0 +1,382 @@
+{
+ "source": "apache/spark v4.3.0 pyspark.ml.regression",
+ "defaults": {
+ "AFTSurvivalRegression": {
+ "featuresCol": "features",
+ "labelCol": "label",
+ "predictionCol": "prediction",
+ "fitIntercept": true,
+ "maxIter": 100,
+ "tol": 1e-06,
+ "censorCol": "censor",
+ "quantileProbabilities": [
+ 0.01,
+ 0.05,
+ 0.1,
+ 0.25,
+ 0.5,
+ 0.75,
+ 0.9,
+ 0.95,
+ 0.99
+ ],
+ "quantilesCol": null,
+ "aggregationDepth": 2,
+ "maxBlockSizeInMB": 0.0
+ },
+ "IsotonicRegression": {
+ "featuresCol": "features",
+ "labelCol": "label",
+ "predictionCol": "prediction",
+ "weightCol": null,
+ "isotonic": true,
+ "featureIndex": 0
+ },
+ "FMRegressor": {
+ "featuresCol": "features",
+ "labelCol": "label",
+ "predictionCol": "prediction",
+ "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",
+ "seed": null
+ }
+ },
+ "cases": [
+ {
+ "class": "AFTSurvivalRegression",
+ "values": {},
+ "params_b64": ""
+ },
+ {
+ "class": "AFTSurvivalRegression",
+ "values": {
+ "featuresCol": "input",
+ "labelCol": "duration",
+ "predictionCol": "pred",
+ "fitIntercept": false,
+ "maxIter": 50,
+ "tol": 1e-08,
+ "censorCol": "observed",
+ "quantileProbabilities": [
+ 0.2,
+ 0.5,
+ 0.8
+ ],
+ "quantilesCol": "quantiles",
+ "aggregationDepth": 3,
+ "maxBlockSizeInMB": 1.0
+ },
+ "params_b64":
"ChYKEGFnZ3JlZ2F0aW9uRGVwdGgSAjADChcKCWNlbnNvckNvbBIKaghvYnNlcnZlZAoWCgtmZWF0dXJlc0NvbBIHagVpbnB1dAoSCgxmaXRJbnRlcmNlcHQSAhgAChYKCGxhYmVsQ29sEgpqCGR1cmF0aW9uCh0KEG1heEJsb2NrU2l6ZUluTUISCVkAAAAAAADwPwoNCgdtYXhJdGVyEgIwMgoXCg1wcmVkaWN0aW9uQ29sEgZqBHByZWQKQQoVcXVhbnRpbGVQcm9iYWJpbGl0aWVzEiiyASUKAkoAEglZmpmZmZmZyT8SCVkAAAAAAADgPxIJWZqZmZmZmek/ChsKDHF1YW50aWxlc0NvbBILaglxdWFudGlsZXMKEAoDdG9sEglZOoww4o55RT4="
+ },
+ {
+ "class": "IsotonicRegression",
+ "values": {},
+ "params_b64": ""
+ },
+ {
+ "class": "IsotonicRegression",
+ "values": {
+ "featuresCol": "input",
+ "labelCol": "target",
+ "predictionCol": "pred",
+ "weightCol": "weight",
+ "isotonic": false,
+ "featureIndex": 1
+ },
+ "params_b64":
"ChIKDGZlYXR1cmVJbmRleBICMAEKFgoLZmVhdHVyZXNDb2wSB2oFaW5wdXQKDgoIaXNvdG9uaWMSAhgAChQKCGxhYmVsQ29sEghqBnRhcmdldAoXCg1wcmVkaWN0aW9uQ29sEgZqBHByZWQKFQoJd2VpZ2h0Q29sEghqBndlaWdodA=="
+ },
+ {
+ "class": "FMRegressor",
+ "values": {},
+ "params_b64": ""
+ },
+ {
+ "class": "FMRegressor",
+ "values": {
+ "featuresCol": "input",
+ "labelCol": "target",
+ "predictionCol": "pred",
+ "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",
+ "seed": 8589934592
+ },
+ "params_b64":
"ChAKCmZhY3RvclNpemUSAjACChYKC2ZlYXR1cmVzQ29sEgdqBWlucHV0ChIKDGZpdEludGVyY2VwdBICGAAKDwoJZml0TGluZWFyEgIYAAoUCgdpbml0U3RkEglZmpmZmZmZyT8KFAoIbGFiZWxDb2wSCGoGdGFyZ2V0Cg0KB21heEl0ZXISAjAyCh4KEW1pbmlCYXRjaEZyYWN0aW9uEglZAAAAAAAA4D8KFwoNcHJlZGljdGlvbkNvbBIGagRwcmVkChUKCHJlZ1BhcmFtEglZmpmZmZmZuT8KDgoEc2VlZBIGOICAgIAgCg4KBnNvbHZlchIEagJnZAoVCghzdGVwU2l6ZRIJWTMzMzMzM9M/ChAKA3RvbBIJWTqMMOKOeUU+"
+ }
+ ],
+ "aft_rows": [
+ [
+ 1.218,
+ 1.0,
+ [
+ 1.56,
+ -0.605
+ ]
+ ],
+ [
+ 2.949,
+ 0.0,
+ [
+ 0.346,
+ 2.158
+ ]
+ ],
+ [
+ 3.627,
+ 0.0,
+ [
+ 1.38,
+ 0.231
+ ]
+ ],
+ [
+ 0.273,
+ 1.0,
+ [
+ 0.52,
+ 1.151
+ ]
+ ],
+ [
+ 4.199,
+ 0.0,
+ [
+ 0.795,
+ -0.226
+ ]
+ ]
+ ],
+ "aft": [
+ {
+ "options": {
+ "featuresCol": "input",
+ "labelCol": "duration",
+ "predictionCol": "pred",
+ "censorCol": "observed",
+ "fitIntercept": false,
+ "maxIter": 100,
+ "tol": 1e-08,
+ "quantileProbabilities": [
+ 0.2,
+ 0.5,
+ 0.8
+ ],
+ "quantilesCol": "quantiles",
+ "aggregationDepth": 2,
+ "maxBlockSizeInMB": 1.0
+ },
+ "censored": false,
+ "predictions": [
+ 3.347853946502114,
+ 2.172586958336815,
+ 3.451043366483275,
+ 2.0188076707510088,
+ 1.8851713140385438
+ ],
+ "quantiles": [
+ [
+ 0.9938656434747983,
+ 2.4882036184517085,
+ 4.921604152607021
+ ],
+ [
+ 0.644968260221865,
+ 1.6147176123924858,
+ 3.1938708100519504
+ ],
+ [
+ 1.0244991241845887,
+ 2.5648964169685975,
+ 5.07330057843677
+ ],
+ [
+ 0.5993163431872977,
+ 1.5004252370594129,
+ 2.967803367307618
+ ],
+ [
+ 0.5596441872993653,
+ 1.4011035606535247,
+ 2.7713475903695226
+ ]
+ ]
+ },
+ {
+ "options": {
+ "featuresCol": "input",
+ "labelCol": "duration",
+ "predictionCol": "pred",
+ "censorCol": "observed",
+ "fitIntercept": false,
+ "maxIter": 100,
+ "tol": 1e-08,
+ "quantileProbabilities": [
+ 0.2,
+ 0.5,
+ 0.8
+ ],
+ "quantilesCol": "quantiles",
+ "aggregationDepth": 2,
+ "maxBlockSizeInMB": 1.0
+ },
+ "censored": true,
+ "predictions": [
+ 10.04888424188614,
+ 19.22775352978342,
+ 17.43265547950875,
+ 9.131650929569455,
+ 3.5385170918695095
+ ],
+ "quantiles": [
+ [
+ 0.7511731751298859,
+ 5.331942944971888,
+ 22.881421179088026
+ ],
+ [
+ 1.4373110807047482,
+ 10.202255525389965,
+ 43.78180863192949
+ ],
+ [
+ 1.303124093409809,
+ 9.24977561276453,
+ 39.69435040697685
+ ],
+ [
+ 0.6826082436446662,
+ 4.845258496153699,
+ 20.7928707257823
+ ],
+ [
+ 0.26451087057721795,
+ 1.8775389177052328,
+ 8.057242772384734
+ ]
+ ]
+ },
+ {
+ "options": {
+ "featuresCol": "input",
+ "labelCol": "duration",
+ "predictionCol": "pred",
+ "censorCol": "observed",
+ "fitIntercept": true,
+ "maxIter": 100,
+ "tol": 1e-08,
+ "quantileProbabilities": [
+ 0.2,
+ 0.5,
+ 0.8
+ ],
+ "quantilesCol": "quantiles",
+ "aggregationDepth": 2,
+ "maxBlockSizeInMB": 1.0
+ },
+ "censored": false,
+ "predictions": [
+ 2.7226847429456003,
+ 2.463945478573775,
+ 2.5491520298232717,
+ 2.6891906278253086,
+ 3.0095915123987047
+ ],
+ "quantiles": [
+ [
+ 1.010262887644848,
+ 2.1369214421194207,
+ 3.729080775642416
+ ],
+ [
+ 0.914256665459687,
+ 1.933847809233013,
+ 3.3747027599089536
+ ],
+ [
+ 0.945872891588918,
+ 2.0007228695373174,
+ 3.4914045238743
+ ],
+ [
+ 0.9978347644299927,
+ 2.110633311269599,
+ 3.683206106856082
+ ],
+ [
+ 1.1167207734296583,
+ 2.3621025722969304,
+ 4.122037955551445
+ ]
+ ]
+ },
+ {
+ "options": {
+ "featuresCol": "input",
+ "labelCol": "duration",
+ "predictionCol": "pred",
+ "censorCol": "observed",
+ "fitIntercept": true,
+ "maxIter": 100,
+ "tol": 1e-08,
+ "quantileProbabilities": [
+ 0.2,
+ 0.5,
+ 0.8
+ ],
+ "quantilesCol": "quantiles",
+ "aggregationDepth": 2,
+ "maxBlockSizeInMB": 1.0
+ },
+ "censored": true,
+ "predictions": [
+ 5.718980229637453,
+ 18.07651649667316,
+ 7.381861947425865,
+ 13.577610764536105,
+ 9.013098221697321
+ ],
+ "quantiles": [
+ [
+ 0.561598316570269,
+ 3.2436818681150075,
+ 11.942413250247904
+ ],
+ [
+ 1.7750964029176055,
+ 10.25260910941418,
+ 37.747504180807354
+ ],
+ [
+ 0.7248916898408828,
+ 4.186832405488372,
+ 15.414854116050694
+ ],
+ [
+ 1.3333082196881851,
+ 7.700927102530106,
+ 28.352858759818407
+ ],
+ [
+ 0.8850775112241616,
+ 5.112034331881677,
+ 18.821212752366424
+ ]
+ ]
+ }
+ ]
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]