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 39060791 [SPARK-61536][CONNECT] Support native GBTRegressor training
and prediction
39060791 is described below
commit 39060791c0f0ee6fd3721f13ba73483bad53bbee
Author: Ruifeng Zheng <[email protected]>
AuthorDate: Thu Nov 12 21:24:20 2026 +0900
[SPARK-61536][CONNECT] Support native GBTRegressor training and prediction
### What changes were proposed in this pull request?
Add native `GBTRegressor` / `GBTRegressionModel` fit and DataFrame
prediction to the Rust client, and expose `GBTRegressor` through the
Rust-backed Python Connect API. Support all 22 constructor parameters, Rust
setters/getters, and PySpark's 21 named Python setters. Reuse the cached-model
ownership and session checks of the existing native estimators.
### Why are the changes needed?
Continue native tree-ensemble support after GBTClassifier, allowing Rust
and Rust-backed Python clients to train gradient-boosted regression trees with
squared or absolute loss.
### Does this PR introduce _any_ user-facing change?
Yes. Users can fit GBTRegressor and produce predictions and optional
per-tree leaf vectors. Tests cover continuous nonlinear targets, instance
weights, sampling, learning rate, both losses, validation early stopping,
parameter errors, and lazy prediction/model lifetime.
The Python constructor matches upstream's `validationTol=0.1` signature and
preserves upstream's behavior: omitting it sends no value, so the server uses
`0.01`; explicitly passing `0.1` sends `0.1`. Model inspection, per-iteration
evaluation, single-vector prediction and persistence remain outside this native
API's scope.
### How was this patch tested?
- All 628 Rust library tests pass; every integration test compiles with
default features and with `wasm-udf`.
- Six live Rust GBTRegressor tests and the official-PySpark golden
parameter comparison pass, including six signed/integer-width seed cases.
- All eight new behavior cases pass with official PySpark. The same cases
and two shared model ownership/session tests pass with the native Python
extension (10 passed).
- Native Python offline suites: 2,044 passed, 8 skipped, 14 subtests passed.
- Constructor parameter order/defaults and 21 named setters match official
PySpark; the 12-class SQL API introspection diff has zero missing public
members.
- Official Spark 4.3 Connect transport suite: 2,638 passed, 589 skipped
across 87 files; zero unexpected failures.
- Rust formatting, Ruff lint/format checks, Ruff exclusion checks and
whitespace checks pass. Clippy passes for the core library and new test
targets. Workspace and Python-wrapper Clippy still report errors at unchanged
source sites; no error's primary source was introduced by this patch.
### 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 #567 from zhengruifeng/add-gbt-regressor.
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 | 1 +
crates/pyspark-rs/src/ml.rs | 230 +++++++-
crates/spark-connect/src/ml.rs | 594 +++++++++++++++++++++
crates/spark-connect/tests/e2e_gbt_regressor.rs | 299 +++++++++++
crates/spark-connect/tests/gbt_regressor_golden.rs | 46 ++
docs/compatibility.md | 24 +
python/pyspark/ml/connect/__init__.py | 2 +
python/pyspark/ml/connect/regression.py | 9 +-
python/tests/test_gbt_regressor_e2e.py | 243 +++++++++
python/tests/test_ml_e2e.py | 2 +
python/tests/test_ml_offline.py | 101 ++++
scripts/capture_gbt_regressor_golden.py | 75 +++
tests/golden/gbt_regressor.json | 31 ++
14 files changed, 1655 insertions(+), 6 deletions(-)
diff --git a/.github/workflows/build_python_connect.yml
b/.github/workflows/build_python_connect.yml
index dba4467c..436c4ac1 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 -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 -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_kmeans --test e2e_decision_tree_regressor
--test e2e_decision_tree_classifier --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_kmeans --test e2e_decision_tree_regressor
--test e2e_decision_tree_classifier --test e2e_gbt_regressor --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 4565f265..45d8122d 100644
--- a/crates/pyspark-rs/src/lib.rs
+++ b/crates/pyspark-rs/src/lib.rs
@@ -248,6 +248,7 @@ fn _pyspark(_py: Python<'_>, m: &Bound<'_, PyModule>) ->
PyResult<()> {
m.add_class::<ml::PyLinearRegression>()?;
m.add_class::<ml::PyDecisionTreeClassifier>()?;
m.add_class::<ml::PyGBTClassifier>()?;
+ m.add_class::<ml::PyGBTRegressor>()?;
m.add_class::<ml::PyRandomForestClassifier>()?;
m.add_class::<ml::PyDecisionTreeRegressor>()?;
m.add_class::<ml::PyRandomForestRegressor>()?;
diff --git a/crates/pyspark-rs/src/ml.rs b/crates/pyspark-rs/src/ml.rs
index 07f90d7f..3dc221a1 100644
--- a/crates/pyspark-rs/src/ml.rs
+++ b/crates/pyspark-rs/src/ml.rs
@@ -16,8 +16,8 @@ use pyo3::types::{PyDict, PyTuple, PyType};
use pyo3::PyClass;
use spark_connect::ml::{
BinaryClassificationEvaluator, CrossValidator, DecisionTreeClassifier,
DecisionTreeRegressor,
- Estimator, Evaluator, GBTClassifier, KMeans, LinearRegression, LinearSVC,
LogisticRegression,
- MaxAbsScaler, Model, MulticlassClassificationEvaluator, Params, Pipeline,
+ Estimator, Evaluator, GBTClassifier, GBTRegressor, KMeans,
LinearRegression, LinearSVC,
+ LogisticRegression, MaxAbsScaler, Model,
MulticlassClassificationEvaluator, Params, Pipeline,
RandomForestClassifier, RandomForestRegressor, RegressionEvaluator,
StandardScaler,
StringIndexer, Transformer, VectorAssembler,
};
@@ -1684,6 +1684,231 @@ impl PyRandomForestClassifier {
}
}
+/// Gradient-boosted regressor fitted and cached by Spark Connect.
+#[pyclass(name = "GBTRegressor", module = "pyspark.ml.connect.regression")]
+pub struct PyGBTRegressor {
+ inner: GBTRegressor,
+ unsendable: Vec<&'static str>,
+}
+
+const GBT_REGRESSOR_PARAMS: &[(&str, Kind)] = &[
+ ("featuresCol", Kind::Str),
+ ("labelCol", Kind::Str),
+ ("predictionCol", Kind::Str),
+ ("maxDepth", Kind::Int),
+ ("maxBins", Kind::Int),
+ ("minInstancesPerNode", Kind::Int),
+ ("minInfoGain", Kind::Float),
+ ("maxMemoryInMB", Kind::Int),
+ ("cacheNodeIds", Kind::Bool),
+ ("subsamplingRate", Kind::Float),
+ ("checkpointInterval", Kind::Int),
+ ("lossType", Kind::Str),
+ ("maxIter", Kind::Int),
+ ("stepSize", Kind::Float),
+ ("seed", Kind::Int),
+ ("impurity", Kind::Str),
+ ("featureSubsetStrategy", Kind::Str),
+ ("validationTol", Kind::Float),
+ ("validationIndicatorCol", Kind::Str),
+ ("leafCol", Kind::Str),
+ ("minWeightFractionPerNode", Kind::Float),
+ ("weightCol", Kind::Str),
+];
+
+#[pymethods]
+impl PyGBTRegressor {
+ #[new]
+ #[pyo3(signature = (*args, **kwargs), text_signature = "(*,
featuresCol='features', labelCol='label', predictionCol='prediction',
maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0,
maxMemoryInMB=256, cacheNodeIds=False, subsamplingRate=1.0,
checkpointInterval=10, lossType='squared', maxIter=20, stepSize=0.1, seed=None,
impurity='variance', featureSubsetStrategy='all', validationTol=0.1,
validationIndicatorCol=None, leafCol='', minWeightFractionPerNode=0.0,
weightCol=None)")]
+ fn new(args: &Bound<'_, PyTuple>, kwargs: Option<&Bound<'_, PyDict>>) ->
PyResult<Self> {
+ let mut this = Self {
+ inner: GBTRegressor::new(),
+ unsendable: Vec::new(),
+ };
+ init_params(
+ &mut this,
+ "GBTRegressor",
+ &[],
+ GBT_REGRESSOR_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 = "setMaxDepth")]
+ fn set_max_depth<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "maxDepth", Kind::Int, value)
+ }
+
+ #[pyo3(name = "setMaxBins")]
+ fn set_max_bins<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "maxBins", Kind::Int, value)
+ }
+
+ #[pyo3(name = "setMinInstancesPerNode")]
+ fn set_min_instances_per_node<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "minInstancesPerNode", Kind::Int, value)
+ }
+
+ #[pyo3(name = "setMinInfoGain")]
+ fn set_min_info_gain<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "minInfoGain", Kind::Float, value)
+ }
+
+ #[pyo3(name = "setMaxMemoryInMB")]
+ fn set_max_memory_in_mb<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "maxMemoryInMB", Kind::Int, value)
+ }
+
+ #[pyo3(name = "setCacheNodeIds")]
+ fn set_cache_node_ids<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "cacheNodeIds", Kind::Bool, value)
+ }
+
+ #[pyo3(name = "setCheckpointInterval")]
+ fn set_checkpoint_interval<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "checkpointInterval", Kind::Int, value)
+ }
+
+ #[pyo3(name = "setImpurity")]
+ fn set_impurity<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "impurity", Kind::Str, value)
+ }
+
+ #[pyo3(name = "setFeatureSubsetStrategy")]
+ fn set_feature_subset_strategy<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "featureSubsetStrategy", 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)
+ }
+
+ #[pyo3(name = "setSubsamplingRate")]
+ fn set_subsampling_rate<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "subsamplingRate", Kind::Float, value)
+ }
+
+ #[pyo3(name = "setLeafCol")]
+ fn set_leaf_col<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "leafCol", Kind::Str, value)
+ }
+
+ #[pyo3(name = "setMinWeightFractionPerNode")]
+ fn set_min_weight_fraction_per_node<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "minWeightFractionPerNode", Kind::Float, 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 = "setLossType")]
+ fn set_loss_type<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "lossType", 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 = "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 = "setValidationIndicatorCol")]
+ fn set_validation_indicator_col<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "validationIndicatorCol", Kind::Str, value)
+ }
+
+ fn fit(slf: &Bound<'_, Self>, df: &PyDataFrame) -> PyResult<PyMLModel> {
+ fit_native(slf, df)
+ }
+}
+
/// Decision tree regressor fitted and cached by Spark Connect.
#[pyclass(
name = "DecisionTreeRegressor",
@@ -2542,6 +2767,7 @@ native!(
PyLinearRegression => LinearRegression,
PyDecisionTreeClassifier => DecisionTreeClassifier,
PyGBTClassifier => GBTClassifier,
+ PyGBTRegressor => GBTRegressor,
PyRandomForestClassifier => RandomForestClassifier,
PyDecisionTreeRegressor => DecisionTreeRegressor,
PyRandomForestRegressor => RandomForestRegressor,
diff --git a/crates/spark-connect/src/ml.rs b/crates/spark-connect/src/ml.rs
index 1dd906e9..ebdc46c1 100644
--- a/crates/spark-connect/src/ml.rs
+++ b/crates/spark-connect/src/ml.rs
@@ -2952,6 +2952,360 @@ impl Model for RandomForestClassificationModel {
}
}
+/// Gradient-boosted regression using Spark's JVM implementation and ML
vectors.
+///
+/// Labels are continuous numeric values. Unset parameters use Spark's
defaults. A seed controls row sampling
+/// for split candidates and subsampling, and feature sampling when a subset
is requested.
+#[derive(Debug, Clone)]
+pub struct GBTRegressor {
+ operator: MlOperator,
+ params: Params,
+}
+
+impl GBTRegressor {
+ pub fn new() -> Self {
+ Self {
+ operator: MlOperator::new(
+ "org.apache.spark.ml.regression.GBTRegressor",
+ OperatorType::Estimator,
+ ),
+ params: Params::new(),
+ }
+ }
+
+ /// Feature vector column.
+ pub fn set_feature_col(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("featuresCol", value);
+ self
+ }
+
+ /// Continuous numeric regression label column.
+ pub fn set_label_col(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("labelCol", value);
+ self
+ }
+
+ /// Regression prediction output column.
+ pub fn set_prediction_col(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("predictionCol", value);
+ self
+ }
+
+ /// Maximum tree depth, from 0 to 30.
+ pub fn set_max_depth(mut self, value: i32) -> Self {
+ self.params = self.params.set_param_int32("maxDepth", value);
+ self
+ }
+
+ /// Maximum number of bins for discretizing continuous features.
+ pub fn set_max_bins(mut self, value: i32) -> Self {
+ self.params = self.params.set_param_int32("maxBins", value);
+ self
+ }
+
+ /// Minimum number of training instances in each child node.
+ pub fn set_min_instances_per_node(mut self, value: i32) -> Self {
+ self.params = self.params.set_param_int32("minInstancesPerNode",
value);
+ self
+ }
+
+ /// Minimum information gain for a split.
+ pub fn set_min_info_gain(mut self, value: f64) -> Self {
+ self.params = self.params.set_param_double("minInfoGain", value);
+ self
+ }
+
+ /// Maximum memory in MB for histogram aggregation.
+ pub fn set_max_memory_in_mb(mut self, value: i32) -> Self {
+ self.params = self.params.set_param_int32("maxMemoryInMB", value);
+ self
+ }
+
+ /// Whether to cache node IDs for training instances.
+ pub fn set_cache_node_ids(mut self, value: bool) -> Self {
+ self.params = self.params.set_param_bool("cacheNodeIds", value);
+ self
+ }
+
+ /// Node ID cache checkpoint interval; -1 disables checkpointing.
+ pub fn set_checkpoint_interval(mut self, value: i32) -> Self {
+ self.params = self.params.set_param_int32("checkpointInterval", value);
+ self
+ }
+
+ /// Impurity setting; Spark uses variance for the regression trees in GBT.
+ pub fn set_impurity(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("impurity", value);
+ self
+ }
+
+ /// Feature subset strategy: auto, all, onethird, sqrt, log2, or a numeric
count/fraction.
+ pub fn set_feature_subset_strategy(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("featureSubsetStrategy",
value);
+ self
+ }
+
+ /// Random seed for split-candidate row sampling, subsampling and feature
sampling.
+ pub fn set_seed(mut self, value: i64) -> Self {
+ self.params = self.params.set_param_int_narrow("seed", value);
+ self
+ }
+
+ /// Fraction of training data used to train each tree, in (0, 1].
+ pub fn set_subsampling_rate(mut self, value: f64) -> Self {
+ self.params = self.params.set_param_double("subsamplingRate", value);
+ self
+ }
+
+ /// Optional output vector of leaf indices, one per tree; empty disables
it.
+ pub fn set_leaf_col(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("leafCol", value);
+ self
+ }
+
+ /// Minimum fraction of total weight in each child node, in [0, 0.5).
+ pub fn set_min_weight_fraction_per_node(mut self, value: f64) -> Self {
+ self.params = self
+ .params
+ .set_param_double("minWeightFractionPerNode", value);
+ self
+ }
+
+ /// Optional instance weight column.
+ pub fn set_weight_col(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("weightCol", value);
+ self
+ }
+
+ /// The feature vector column (default: "features").
+ pub fn feature_col(&self) -> &str {
+ self.params.string_or("featuresCol", "features")
+ }
+
+ /// The label column (default: "label").
+ pub fn label_col(&self) -> &str {
+ self.params.string_or("labelCol", "label")
+ }
+
+ /// The regression prediction output column (default: "prediction").
+ pub fn prediction_col(&self) -> &str {
+ self.params.string_or("predictionCol", "prediction")
+ }
+
+ /// The maximum tree depth (default: 5).
+ pub fn max_depth(&self) -> i32 {
+ self.params.int_or("maxDepth", 5)
+ }
+
+ /// The maximum number of bins for continuous features (default: 32).
+ pub fn max_bins(&self) -> i32 {
+ self.params.int_or("maxBins", 32)
+ }
+
+ /// The minimum number of training instances in each child node (default:
1).
+ pub fn min_instances_per_node(&self) -> i32 {
+ self.params.int_or("minInstancesPerNode", 1)
+ }
+
+ /// The minimum information gain for a split (default: 0).
+ pub fn min_info_gain(&self) -> f64 {
+ self.params.double_or("minInfoGain", 0.0)
+ }
+
+ /// The maximum memory in MB for histogram aggregation (default: 256).
+ pub fn max_memory_in_mb(&self) -> i32 {
+ self.params.int_or("maxMemoryInMB", 256)
+ }
+
+ /// Whether to cache node IDs for training instances (default: false).
+ pub fn cache_node_ids(&self) -> bool {
+ self.params.bool_or("cacheNodeIds", false)
+ }
+
+ /// The node ID cache checkpoint interval (default: 10).
+ pub fn checkpoint_interval(&self) -> i32 {
+ self.params.int_or("checkpointInterval", 10)
+ }
+
+ /// The impurity measure (default: "variance").
+ pub fn impurity(&self) -> &str {
+ self.params.string_or("impurity", "variance")
+ }
+
+ /// The feature subset strategy (default: "all").
+ pub fn feature_subset_strategy(&self) -> &str {
+ self.params.string_or("featureSubsetStrategy", "all")
+ }
+
+ /// The random seed, if one is set; else Spark's default seed applies.
+ pub fn seed(&self) -> Option<i64> {
+ self.params.long_opt("seed")
+ }
+
+ /// The fraction of training data used to train each tree (default: 1).
+ pub fn subsampling_rate(&self) -> f64 {
+ self.params.double_or("subsamplingRate", 1.0)
+ }
+
+ /// The leaf index output column (default: empty, no column).
+ pub fn leaf_col(&self) -> &str {
+ self.params.string_or("leafCol", "")
+ }
+
+ /// The minimum fraction of total weight in each child node (default: 0).
+ pub fn min_weight_fraction_per_node(&self) -> f64 {
+ self.params.double_or("minWeightFractionPerNode", 0.0)
+ }
+
+ /// The instance weight column, if one is set.
+ pub fn weight_col(&self) -> Option<&str> {
+ self.params.string_opt("weightCol")
+ }
+
+ /// Loss function: squared or absolute.
+ pub fn set_loss_type(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("lossType", value);
+ self
+ }
+
+ /// The lossType value; default: "squared".
+ pub fn loss_type(&self) -> &str {
+ self.params.string_or("lossType", "squared")
+ }
+
+ /// Maximum number of boosting iterations (trees).
+ pub fn set_max_iter(mut self, value: i32) -> Self {
+ self.params = self.params.set_param_int32("maxIter", value);
+ self
+ }
+
+ /// The maxIter value; default: 20.
+ pub fn max_iter(&self) -> i32 {
+ self.params.int_or("maxIter", 20)
+ }
+
+ /// Learning rate for the contribution of each tree after the first, in
(0, 1].
+ pub fn set_step_size(mut self, value: f64) -> Self {
+ self.params = self.params.set_param_double("stepSize", value);
+ self
+ }
+
+ /// The stepSize value; default: 0.1.
+ pub fn step_size(&self) -> f64 {
+ self.params.double_or("stepSize", 0.1)
+ }
+
+ /// Relative improvement tolerance for validation-set early stopping.
+ pub fn set_validation_tol(mut self, value: f64) -> Self {
+ self.params = self.params.set_param_double("validationTol", value);
+ self
+ }
+
+ /// The validationTol value; default: 0.01.
+ pub fn validation_tol(&self) -> f64 {
+ self.params.double_or("validationTol", 0.01)
+ }
+
+ /// Optional boolean column: false rows train; true rows validate early
stopping.
+ pub fn set_validation_indicator_col(mut self, value: &str) -> Self {
+ self.params = self
+ .params
+ .set_param_string("validationIndicatorCol", value);
+ self
+ }
+
+ /// The validationIndicatorCol value; unset unless explicitly configured.
+ pub fn validation_indicator_col(&self) -> Option<&str> {
+ self.params.string_opt("validationIndicatorCol")
+ }
+
+ fn model_from_info(
+ &self,
+ info: proto::ml_command_result::MlOperatorInfo,
+ session: &SparkSession,
+ ) -> spark_connect_core::error::Result<GBTRegressionModel> {
+ let cached = CachedModel::from_info(&info, session, "GBTRegressor")?;
+ Ok(GBTRegressionModel {
+ operator: MlOperator::with_uid(
+ "org.apache.spark.ml.regression.GBTRegressionModel",
+ info.uid.as_deref().unwrap_or(&self.operator.uid),
+ OperatorType::Model,
+ ),
+ params: self.params.clone(),
+ cached,
+ })
+ }
+}
+
+impl Default for GBTRegressor {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl Estimator for GBTRegressor {
+ 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 gradient-boosted regression model fitted by Spark Connect.
+///
+/// Obtain it through [`Estimator::fit`]. The model, its clones and transformed
+/// DataFrames retain the cached server model until the last owner is dropped.
+#[derive(Debug, Clone)]
+pub struct GBTRegressionModel {
+ operator: MlOperator,
+ params: Params,
+ cached: CachedModel,
+}
+
+impl Transformer for GBTRegressionModel {
+ 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 GBTRegressionModel {
+ fn clone_box(&self) -> Box<dyn Model> {
+ Box::new(self.clone())
+ }
+}
+
/// Decision tree regression using Spark's JVM implementation and ML vector
features.
///
/// Supports continuous numeric labels. Unset parameters use Spark's defaults.
A single tree
@@ -5486,6 +5840,244 @@ mod tests {
assert!(built.operator_mut().uid.starts_with("GBTClassifier_"));
}
+ #[test]
+ fn gbt_regressor_getters_follow_defaults_builders_and_mutable_params() {
+ let mut tree = GBTRegressor::default();
+ assert_eq!(tree.feature_col(), "features");
+ assert_eq!(tree.label_col(), "label");
+ assert_eq!(tree.prediction_col(), "prediction");
+ assert_eq!(tree.max_depth(), 5);
+ assert_eq!(tree.max_bins(), 32);
+ assert_eq!(tree.min_instances_per_node(), 1);
+ assert_eq!(tree.min_info_gain(), 0.0);
+ assert_eq!(tree.max_memory_in_mb(), 256);
+ assert_eq!(tree.cache_node_ids(), false);
+ assert_eq!(tree.checkpoint_interval(), 10);
+ assert_eq!(tree.impurity(), "variance");
+ assert_eq!(tree.feature_subset_strategy(), "all");
+ assert_eq!(tree.seed(), None);
+ assert_eq!(tree.subsampling_rate(), 1.0);
+ assert_eq!(tree.leaf_col(), "");
+ assert_eq!(tree.min_weight_fraction_per_node(), 0.0);
+ assert_eq!(tree.weight_col(), None);
+ assert_eq!(tree.loss_type(), "squared");
+ assert_eq!(tree.max_iter(), 20);
+ assert_eq!(tree.step_size(), 0.1);
+ assert_eq!(tree.validation_tol(), 0.01);
+ assert_eq!(tree.validation_indicator_col(), None);
+ let mut built = GBTRegressor::new()
+ .set_feature_col("input")
+ .set_label_col("target")
+ .set_prediction_col("value")
+ .set_max_depth(3)
+ .set_max_bins(16)
+ .set_min_instances_per_node(2)
+ .set_min_info_gain(0.01)
+ .set_max_memory_in_mb(64)
+ .set_cache_node_ids(true)
+ .set_checkpoint_interval(-1)
+ .set_impurity("variance")
+ .set_feature_subset_strategy("sqrt")
+ .set_seed(1_i64 << 33)
+ .set_subsampling_rate(0.75)
+ .set_leaf_col("leaves")
+ .set_min_weight_fraction_per_node(0.1)
+ .set_weight_col("weight")
+ .set_loss_type("absolute")
+ .set_max_iter(4)
+ .set_step_size(0.2)
+ .set_validation_tol(0.05)
+ .set_validation_indicator_col("validation");
+ *tree.params_mut() = tree
+ .params()
+ .clone()
+ .set_param_string("featuresCol", "input");
+ assert_eq!(tree.feature_col(), "input");
+ assert_eq!(built.feature_col(), tree.feature_col());
+ *tree.params_mut() =
tree.params().clone().set_param_string("labelCol", "target");
+ assert_eq!(tree.label_col(), "target");
+ assert_eq!(built.label_col(), tree.label_col());
+ *tree.params_mut() = tree
+ .params()
+ .clone()
+ .set_param_string("predictionCol", "value");
+ assert_eq!(tree.prediction_col(), "value");
+ assert_eq!(built.prediction_col(), tree.prediction_col());
+ *tree.params_mut() = tree.params().clone().set_param_int32("maxDepth",
3);
+ assert_eq!(tree.max_depth(), 3);
+ assert_eq!(built.max_depth(), tree.max_depth());
+ *tree.params_mut() = tree.params().clone().set_param_int32("maxBins",
16);
+ assert_eq!(tree.max_bins(), 16);
+ assert_eq!(built.max_bins(), tree.max_bins());
+ *tree.params_mut() = tree
+ .params()
+ .clone()
+ .set_param_int32("minInstancesPerNode", 2);
+ assert_eq!(tree.min_instances_per_node(), 2);
+ assert_eq!(
+ built.min_instances_per_node(),
+ tree.min_instances_per_node()
+ );
+ *tree.params_mut() =
tree.params().clone().set_param_double("minInfoGain", 0.01);
+ assert_eq!(tree.min_info_gain(), 0.01);
+ assert_eq!(built.min_info_gain(), tree.min_info_gain());
+ *tree.params_mut() =
tree.params().clone().set_param_int32("maxMemoryInMB", 64);
+ assert_eq!(tree.max_memory_in_mb(), 64);
+ assert_eq!(built.max_memory_in_mb(), tree.max_memory_in_mb());
+ *tree.params_mut() =
tree.params().clone().set_param_bool("cacheNodeIds", true);
+ assert_eq!(tree.cache_node_ids(), true);
+ assert_eq!(built.cache_node_ids(), tree.cache_node_ids());
+ *tree.params_mut() = tree
+ .params()
+ .clone()
+ .set_param_int32("checkpointInterval", -1);
+ assert_eq!(tree.checkpoint_interval(), -1);
+ assert_eq!(built.checkpoint_interval(), tree.checkpoint_interval());
+ *tree.params_mut() = tree
+ .params()
+ .clone()
+ .set_param_string("impurity", "variance");
+ assert_eq!(tree.impurity(), "variance");
+ assert_eq!(built.impurity(), tree.impurity());
+ *tree.params_mut() = tree
+ .params()
+ .clone()
+ .set_param_string("featureSubsetStrategy", "sqrt");
+ assert_eq!(tree.feature_subset_strategy(), "sqrt");
+ assert_eq!(
+ built.feature_subset_strategy(),
+ tree.feature_subset_strategy()
+ );
+ *tree.params_mut() = tree
+ .params()
+ .clone()
+ .set_param_int_narrow("seed", 1_i64 << 33);
+ assert_eq!(tree.seed(), Some(1_i64 << 33));
+ assert_eq!(built.seed(), tree.seed());
+ *tree.params_mut() = tree
+ .params()
+ .clone()
+ .set_param_double("subsamplingRate", 0.75);
+ assert_eq!(tree.subsampling_rate(), 0.75);
+ assert_eq!(built.subsampling_rate(), tree.subsampling_rate());
+ *tree.params_mut() = tree.params().clone().set_param_string("leafCol",
"leaves");
+ assert_eq!(tree.leaf_col(), "leaves");
+ assert_eq!(built.leaf_col(), tree.leaf_col());
+ *tree.params_mut() = tree
+ .params()
+ .clone()
+ .set_param_double("minWeightFractionPerNode", 0.1);
+ assert_eq!(tree.min_weight_fraction_per_node(), 0.1);
+ assert_eq!(
+ built.min_weight_fraction_per_node(),
+ tree.min_weight_fraction_per_node()
+ );
+ *tree.params_mut() = tree
+ .params()
+ .clone()
+ .set_param_string("weightCol", "weight");
+ assert_eq!(tree.weight_col(), Some("weight"));
+ assert_eq!(built.weight_col(), tree.weight_col());
+ *tree.params_mut() = tree
+ .params()
+ .clone()
+ .set_param_string("lossType", "absolute");
+ assert_eq!(tree.loss_type(), "absolute");
+ assert_eq!(built.loss_type(), tree.loss_type());
+ *tree.params_mut() = tree.params().clone().set_param_int32("maxIter",
4);
+ assert_eq!(tree.max_iter(), 4);
+ assert_eq!(built.max_iter(), tree.max_iter());
+ *tree.params_mut() =
tree.params().clone().set_param_double("stepSize", 0.2);
+ assert_eq!(tree.step_size(), 0.2);
+ assert_eq!(built.step_size(), tree.step_size());
+ *tree.params_mut() = tree
+ .params()
+ .clone()
+ .set_param_double("validationTol", 0.05);
+ assert_eq!(tree.validation_tol(), 0.05);
+ assert_eq!(built.validation_tol(), tree.validation_tol());
+ *tree.params_mut() = tree
+ .params()
+ .clone()
+ .set_param_string("validationIndicatorCol", "validation");
+ assert_eq!(tree.validation_indicator_col(), Some("validation"));
+ assert_eq!(
+ built.validation_indicator_col(),
+ tree.validation_indicator_col()
+ );
+ assert_eq!(tree.params().to_proto(), built.params().to_proto());
+ assert!(built.operator_mut().uid.starts_with("GBTRegressor_"));
+ }
+
+ #[test]
+ fn gbt_regressor_validates_fitted_references_and_model_metadata() {
+ let session = offline_session();
+ let estimator = GBTRegressor::default().set_prediction_col("class");
+ assert_eq!(
+ estimator.operator().name,
+ "org.apache.spark.ml.regression.GBTRegressor"
+ );
+ assert_eq!(estimator.operator().op_type, OperatorType::Estimator);
+ 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 info = |uid| proto::ml_command_result::MlOperatorInfo {
+ r#type:
Some(proto::ml_command_result::ml_operator_info::Type::ObjRef(
+ proto::ObjectRef {
+ id: "trained-gbt-regressor".into(),
+ },
+ )),
+ uid,
+ ..Default::default()
+ };
+ let mut model = estimator
+ .model_from_info(info(Some("returned-uid".into())), &session)
+ .unwrap();
+ assert_eq!(model.operator().uid, "returned-uid");
+ assert_eq!(
+ model.operator().name,
+ "org.apache.spark.ml.regression.GBTRegressionModel"
+ );
+ assert_eq!(model.operator().op_type, OperatorType::Model);
+ let fallback = estimator.model_from_info(info(None),
&session).unwrap();
+ assert_eq!(fallback.operator().uid, estimator.operator().uid);
+ 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-gbt-regressor".into()
+ }
+ ))
+ );
+ assert_eq!(*t.input.unwrap(), df.relation().unwrap());
+ assert_eq!(t.params.unwrap(), estimator.params().to_proto());
+ assert!(model
+ .transform(&session.new_session().range(2).unwrap())
+ .is_err());
+ assert!(model.clone_box().transform(&df).is_ok());
+ }
#[test]
fn gbt_classifier_validates_fitted_references_and_model_metadata() {
let session = offline_session();
@@ -5934,6 +6526,8 @@ mod tests {
assert_eq!(sent(tree_regressor.params()), Some(expected.clone()));
let gbt = GBTClassifier::new().set_seed(seed);
assert_eq!(sent(gbt.params()), Some(expected.clone()));
+ let gbtr = GBTRegressor::new().set_seed(seed);
+ assert_eq!(sent(gbtr.params()), Some(expected.clone()));
let cv = CrossValidator::new().set_seed(seed);
assert_eq!(sent(cv.params()), Some(expected));
}
diff --git a/crates/spark-connect/tests/e2e_gbt_regressor.rs
b/crates/spark-connect/tests/e2e_gbt_regressor.rs
new file mode 100644
index 00000000..3a5d6324
--- /dev/null
+++ b/crates/spark-connect/tests/e2e_gbt_regressor.rs
@@ -0,0 +1,299 @@
+//! Native gradient-boosted regression tests. Set SPARK_REMOTE to run against
a live Connect server.
+mod common;
+
+use common::live_session;
+use spark_connect::column::{col, lit_double, lit_string};
+use spark_connect::expression::Expression;
+use spark_connect::ml::{Estimator, GBTRegressor};
+use spark_connect::{Column, DataFrame, SparkSession};
+
+fn vectors(s: &SparkSession, sql: &str, name: &str) -> DataFrame {
+ s.sql(sql).unwrap().with_column(
+ name,
+ Column::new(Expression::function(
+ "array_to_vector",
+ vec![col("xs").expression().clone()],
+ )),
+ )
+}
+
+fn vector_array(name: &str) -> Column {
+ Column::new(Expression::function(
+ "vector_to_array",
+ vec![
+ col(name).expression().clone(),
+ lit_string("float64").expression().clone(),
+ ],
+ ))
+}
+
+fn predictions(df: DataFrame, name: &str) -> Vec<f64> {
+ df.order_by(vec![col("id").asc().expression().clone()])
+ .select([col(name)])
+ .collect()
+ .unwrap()
+ .into_iter()
+ .map(|row| row.get(0).unwrap().as_f64().unwrap())
+ .collect()
+}
+
+fn deterministic() -> GBTRegressor {
+ GBTRegressor::new()
+ .set_seed(42)
+ .set_max_iter(3)
+ .set_feature_subset_strategy("all")
+}
+
+#[test]
+fn gbt_regressor_learns_nonlinear_labels_and_keeps_cached_models_alive() {
+ let Some(s) = live_session() else {
+ return;
+ };
+ let training = vectors(
+ &s,
+ "SELECT array(CAST(x AS DOUBLE)) AS xs, CAST(y AS DOUBLE) AS target,
1.0D AS weight
+ FROM VALUES
(-3,-4.0),(-2,-4.0),(-1,5.5),(0,5.5),(1,5.5),(2,-4.0),(3,-4.0) AS t(x,y)",
+ "input",
+ );
+ let held_out = vectors(
+ &s,
+ "SELECT id, array(CAST(x AS DOUBLE)) AS xs
+ FROM VALUES (0,-2.5),(1,-0.5),(2,0.5),(3,2.5) AS t(id,x)",
+ "input",
+ );
+ let mut estimator = deterministic()
+ .set_feature_col("input")
+ .set_label_col("target")
+ .set_prediction_col("value")
+ .set_leaf_col("leaves")
+ .set_max_depth(3)
+ .set_max_bins(16)
+ .set_min_instances_per_node(1)
+ .set_min_info_gain(0.0)
+ .set_max_memory_in_mb(64)
+ .set_cache_node_ids(true)
+ .set_checkpoint_interval(-1)
+ .set_impurity("variance")
+ .set_subsampling_rate(1.0)
+ .set_min_weight_fraction_per_node(0.0)
+ .set_weight_col("weight");
+ let mut first = estimator.fit(&training).unwrap();
+ let mut second = estimator
+ .fit(&training.with_column("target", col("target") + lit_double(10.0)))
+ .unwrap();
+ let object_id = |model: &dyn spark_connect::ml::Model| {
+ let spark_connect_proto::ml_relation::MlType::Transform(t) =
+ model.build_ml_relation(&held_out).unwrap().ml_type.unwrap()
+ else {
+ panic!("transform")
+ };
+ let
Some(spark_connect_proto::ml_relation::transform::Operator::ObjRef(r)) =
t.operator
+ else {
+ panic!("cached model")
+ };
+ r.id
+ };
+ assert_ne!(object_id(first.as_ref()), object_id(second.as_ref()));
+ let mut cloned = first.clone_box();
+ let delayed = first
+ .transform(&held_out)
+ .unwrap()
+ .select([col("id"), col("value")]);
+ drop(first);
+ let output = cloned.transform(&held_out).unwrap();
+ assert_eq!(
+ predictions(output.clone(), "value"),
+ vec![-4.0, 5.5, 5.5, -4.0]
+ );
+ let leaves = output.select([vector_array("leaves")]).collect().unwrap();
+ for row in leaves {
+ let spark_connect::row::Value::List(values) = row.get(0).unwrap() else
{
+ panic!("leaf vector")
+ };
+ assert_eq!(values.len(), 3);
+ assert!(values.iter().all(|v| v.as_f64().unwrap() >= 0.0));
+ }
+ let mut repeated = estimator.fit(&training).unwrap();
+ assert_eq!(
+ predictions(repeated.transform(&held_out).unwrap(), "value"),
+ vec![-4.0, 5.5, 5.5, -4.0]
+ );
+ drop(cloned);
+ assert_eq!(predictions(delayed, "value"), vec![-4.0, 5.5, 5.5, -4.0]);
+ assert_eq!(
+ predictions(second.transform(&held_out).unwrap(), "value"),
+ vec![6.0, 15.5, 15.5, 6.0]
+ );
+ assert!(second
+ .transform(&s.new_session().range(1).unwrap())
+ .is_err());
+ s.stop().unwrap();
+}
+
+#[test]
+fn gbt_regressor_weights_change_the_predicted_mean() {
+ let Some(s) = live_session() else {
+ return;
+ };
+ let data = vectors(
+ &s,
+ "SELECT 0 AS id, array(0.0D) AS xs, CAST(y AS DOUBLE) AS label, CAST(w
AS DOUBLE) AS weight
+ FROM VALUES (-2,1),(-2,1),(-2,1),(10,9) AS t(y,w)",
+ "features",
+ );
+ let mut plain = deterministic().set_max_depth(0).fit(&data).unwrap();
+ let mut weighted = deterministic()
+ .set_max_depth(0)
+ .set_weight_col("weight")
+ .fit(&data)
+ .unwrap();
+ assert_eq!(
+ predictions(plain.transform(&data).unwrap(), "prediction"),
+ vec![1.0; 4]
+ );
+ assert_eq!(
+ predictions(weighted.transform(&data).unwrap(), "prediction"),
+ vec![7.0; 4]
+ );
+ s.stop().unwrap();
+}
+
+#[test]
+fn gbt_regressor_sampling_is_reproducible() {
+ let Some(s) = live_session() else {
+ return;
+ };
+ let data = vectors(
+ &s,
+ "SELECT id, array(CAST(id AS DOUBLE), CAST(id % 3 AS DOUBLE)) AS xs,
+ CAST(CASE WHEN id < 20 THEN -3 ELSE 8 END AS DOUBLE) AS label FROM
range(40)",
+ "features",
+ );
+ let mut estimator = GBTRegressor::new()
+ .set_seed(1_i64 << 33)
+ .set_max_iter(5)
+ .set_max_depth(3)
+ .set_subsampling_rate(0.8)
+ .set_feature_subset_strategy("sqrt");
+ let mut first = estimator.fit(&data).unwrap();
+ let mut second = estimator.fit(&data).unwrap();
+ let actual = predictions(first.transform(&data).unwrap(), "prediction");
+ assert_eq!(
+ actual,
+ predictions(second.transform(&data).unwrap(), "prediction")
+ );
+ assert!(actual.iter().all(|x| x.is_finite()));
+ assert!(actual[0] < actual[39]);
+ s.stop().unwrap();
+}
+
+#[test]
+fn gbt_regressor_rejects_invalid_parameters_and_data() {
+ let Some(s) = live_session() else {
+ return;
+ };
+ let data = vectors(
+ &s,
+ "SELECT array(CAST(x AS DOUBLE)) AS xs, CAST(y AS DOUBLE) AS label,
1.0D AS weight
+ FROM VALUES (-1,-2.5),(1,3.5) AS t(x,y)",
+ "features",
+ );
+ for mut estimator in [
+ deterministic().set_max_iter(0),
+ deterministic().set_max_depth(31),
+ deterministic().set_step_size(0.0),
+ deterministic().set_validation_tol(-0.1),
+ deterministic().set_max_bins(1),
+ deterministic().set_min_instances_per_node(0),
+ deterministic().set_min_info_gain(-1.0),
+ deterministic().set_max_memory_in_mb(-1),
+ deterministic().set_checkpoint_interval(0),
+ deterministic().set_loss_type("logistic"),
+ deterministic().set_feature_subset_strategy("invalid"),
+ deterministic().set_subsampling_rate(0.0),
+ deterministic().set_min_weight_fraction_per_node(0.5),
+ ] {
+ assert!(
+ estimator.fit(&data).is_err(),
+ "invalid parameters: {:?}",
+ estimator.params()
+ );
+ }
+ assert!(deterministic().fit(&data.drop(vec!["label"])).is_err());
+ assert!(deterministic()
+ .fit(&data.with_column("label", lit_double(f64::NAN)))
+ .is_err());
+ assert!(deterministic()
+ .set_weight_col("weight")
+ .fit(&data.with_column("weight", lit_double(-1.0)))
+ .is_err());
+ assert!(deterministic()
+ .fit(&data.with_column("features", lit_double(1.0)))
+ .is_err());
+ s.stop().unwrap();
+}
+
+#[test]
+fn gbt_regressor_absolute_loss_handles_an_outlier_differently() {
+ let Some(s) = live_session() else {
+ return;
+ };
+ let data = vectors(
+ &s,
+ "SELECT id, array(0.0D) AS xs, CAST(y AS DOUBLE) AS label
+ FROM VALUES (0,0),(1,0),(2,0),(3,10) AS t(id,y)",
+ "features",
+ );
+ let base = GBTRegressor::new()
+ .set_seed(42)
+ .set_max_depth(0)
+ .set_max_iter(3)
+ .set_step_size(0.5);
+ let mut squared =
base.clone().set_loss_type("squared").fit(&data).unwrap();
+ let mut absolute = base.set_loss_type("absolute").fit(&data).unwrap();
+ assert_eq!(
+ predictions(squared.transform(&data).unwrap(), "prediction"),
+ vec![2.5; 4]
+ );
+ assert_eq!(
+ predictions(absolute.transform(&data).unwrap(), "prediction"),
+ vec![2.0; 4]
+ );
+ s.stop().unwrap();
+}
+
+#[test]
+fn gbt_regressor_validation_rows_stop_boosting_early() {
+ let Some(s) = live_session() else {
+ return;
+ };
+ let data = vectors(
+ &s,
+ "SELECT id, array(CAST(x AS DOUBLE)) AS xs, CAST(y AS DOUBLE) AS
label, validation
+ FROM VALUES
(0,-3,-2,false),(1,-2,-2,false),(2,2,3,false),(3,3,3,false),
+ (4,-3,3,true),(5,-2,3,true),(6,2,-2,true),(7,3,-2,true) AS
t(id,x,y,validation)",
+ "features",
+ );
+ let mut model = GBTRegressor::new()
+ .set_seed(42)
+ .set_max_depth(1)
+ .set_max_iter(6)
+ .set_step_size(0.2)
+ .set_leaf_col("leaves")
+ .set_validation_tol(0.01)
+ .set_validation_indicator_col("validation")
+ .fit(&data)
+ .unwrap();
+ let output = model.transform(&data).unwrap();
+ assert_eq!(
+ predictions(output.clone(), "prediction"),
+ vec![-2.0, -2.0, 3.0, 3.0, -2.0, -2.0, 3.0, 3.0]
+ );
+ for row in output.select([vector_array("leaves")]).collect().unwrap() {
+ let spark_connect::row::Value::List(leaves) = row.get(0).unwrap() else
{
+ panic!("leaves")
+ };
+ assert_eq!(leaves.len(), 1);
+ }
+ s.stop().unwrap();
+}
diff --git a/crates/spark-connect/tests/gbt_regressor_golden.rs
b/crates/spark-connect/tests/gbt_regressor_golden.rs
new file mode 100644
index 00000000..50d14b95
--- /dev/null
+++ b/crates/spark-connect/tests/gbt_regressor_golden.rs
@@ -0,0 +1,46 @@
+//! Match every GBTRegressor parameter and seed boundary to official PySpark.
+use base64::{engine::general_purpose::STANDARD, Engine};
+use prost::Message;
+use spark_connect::ml::{Estimator, GBTRegressor};
+
+#[test]
+fn gbt_regressor_parameters_match_official_pyspark() {
+ let fixture: serde_json::Value =
+
serde_json::from_str(include_str!("../../../tests/golden/gbt_regressor.json")).unwrap();
+ for case in fixture["cases"].as_array().unwrap() {
+ let seed = case["seed"].as_i64().unwrap();
+ let bytes = STANDARD
+ .decode(case["params_b64"].as_str().unwrap())
+ .unwrap();
+ let expected =
spark_connect_proto::MlParams::decode(bytes.as_slice()).unwrap();
+ let estimator = GBTRegressor::new()
+ .set_feature_col("input")
+ .set_label_col("target")
+ .set_prediction_col("value")
+ .set_max_depth(3)
+ .set_max_bins(16)
+ .set_min_instances_per_node(2)
+ .set_min_info_gain(0.01)
+ .set_max_memory_in_mb(64)
+ .set_cache_node_ids(true)
+ .set_checkpoint_interval(-1)
+ .set_impurity("variance")
+ .set_feature_subset_strategy("all")
+ .set_loss_type("absolute")
+ .set_max_iter(4)
+ .set_step_size(0.2)
+ .set_validation_tol(0.05)
+ .set_validation_indicator_col("validation")
+ .set_seed(seed)
+ .set_subsampling_rate(0.75)
+ .set_leaf_col("leaves")
+ .set_min_weight_fraction_per_node(0.1)
+ .set_weight_col("weight");
+ assert_eq!(estimator.params().to_proto(), expected, "seed {seed}");
+ }
+ assert!(GBTRegressor::default()
+ .params()
+ .to_proto()
+ .params
+ .is_empty());
+}
diff --git a/docs/compatibility.md b/docs/compatibility.md
index b9b28267..09738c70 100644
--- a/docs/compatibility.md
+++ b/docs/compatibility.md
@@ -223,6 +223,30 @@ transformed DataFrames retain the cached server model
until their last owner dro
Tree inspection, feature importances, single-vector prediction and persistence
are
not exposed by this native addition.
+## Native GBTRegressor
+
+`spark_connect::ml::GBTRegressor` fits Spark's JVM gradient-boosted regressor
+through Connect with ML vector features and continuous numeric labels. Rust
+setters/getters cover all 22 PySpark constructor parameters. It supports
squared
+and absolute loss, instance weights, row/feature sampling, learning rate,
+iteration limits and validation-set early stopping.
+
+The Python binding is available as `pyspark.ml.connect.regression.GBTRegressor`
+and `pyspark.ml.connect.GBTRegressor`. Its keyword-only signature and 21 named
+setters match PySpark. `validationTol` has no Python setter. The reference's
+signature advertises `validationTol=0.1`, but omitting it leaves the parameter
+unset and uses Spark's `0.01` default. This binding preserves that behavior;
+`GBTRegressor(validationTol=0.1)` explicitly sends `0.1`. The Rust getter
returns
+`0.01` when unset.
+
+`maxIter` limits boosting iterations, and `stepSize` scales each tree after the
+first. With `validationIndicatorCol`, false rows train and true rows validate;
+early stopping can fit fewer trees. DataFrame transforms expose predictions and
+an optional vector of leaf IDs, one per fitted tree. Models, clones and lazy
+transformed DataFrames retain the cached model in its fitting session until the
+last owner is dropped. Tree inspection, per-iteration evaluation, single-vector
+prediction and persistence are outside this native addition.
+
## Native GBTClassifier
`spark_connect::ml::GBTClassifier` fits Spark's JVM gradient-boosted binary
diff --git a/python/pyspark/ml/connect/__init__.py
b/python/pyspark/ml/connect/__init__.py
index 6e814f86..36e37ea6 100644
--- a/python/pyspark/ml/connect/__init__.py
+++ b/python/pyspark/ml/connect/__init__.py
@@ -19,6 +19,7 @@ from pyspark.ml.connect.classification import (
RandomForestClassifier,
)
from pyspark.ml.connect.regression import (
+ GBTRegressor,
DecisionTreeRegressor,
LinearRegression,
RandomForestRegressor,
@@ -58,6 +59,7 @@ __all__ = [
"LinearSVC",
"DecisionTreeClassifier",
"GBTClassifier",
+ "GBTRegressor",
"RandomForestClassifier",
"LinearRegression",
"DecisionTreeRegressor",
diff --git a/python/pyspark/ml/connect/regression.py
b/python/pyspark/ml/connect/regression.py
index c05b998d..918851dc 100644
--- a/python/pyspark/ml/connect/regression.py
+++ b/python/pyspark/ml/connect/regression.py
@@ -1,4 +1,9 @@
"""Native regression estimators backed by Spark Connect's JVM ML API."""
-from pyspark._pyspark import DecisionTreeRegressor, LinearRegression,
RandomForestRegressor
+from pyspark._pyspark import (
+ DecisionTreeRegressor,
+ GBTRegressor,
+ LinearRegression,
+ RandomForestRegressor,
+)
-__all__ = ["DecisionTreeRegressor", "LinearRegression",
"RandomForestRegressor"]
+__all__ = ["GBTRegressor", "DecisionTreeRegressor", "LinearRegression",
"RandomForestRegressor"]
diff --git a/python/tests/test_gbt_regressor_e2e.py
b/python/tests/test_gbt_regressor_e2e.py
new file mode 100644
index 00000000..7e8d18fd
--- /dev/null
+++ b/python/tests/test_gbt_regressor_e2e.py
@@ -0,0 +1,243 @@
+#
+# 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 GBTRegressor behaviors; these same cases run with official
PySpark."""
+
+import gc
+import math
+import os
+
+import pytest
+from pyspark.ml.connect.functions import array_to_vector, vector_to_array
+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-server tests")
+ spark = SparkSession.builder.remote(remote).getOrCreate()
+ try:
+ yield spark
+ finally:
+ spark.stop()
+
+
+def _regressor():
+ try:
+ from pyspark.ml.connect.regression import GBTRegressor
+ except ImportError:
+ from pyspark.ml.regression import GBTRegressor
+ return GBTRegressor
+
+
+def _vectors(session, sql, name="features"):
+ return session.sql(sql).withColumn(name, array_to_vector("xs"))
+
+
+def _predictions(model, frame, name="prediction"):
+ return [r[0] for r in
model.transform(frame).orderBy("id").select(name).collect()]
+
+
[email protected]("use_setters", [False, True], ids=["constructor",
"setters"])
+def
test_gbt_regressor_learns_nonlinear_values_and_retains_lazy_predictions(session,
use_setters):
+ GBTRegressor = _regressor()
+ training = _vectors(
+ session,
+ "SELECT array(CAST(x AS DOUBLE)) AS xs, CAST(y AS DOUBLE) AS target,
1.0D AS weight "
+ "FROM VALUES
(-3,-4.0),(-2,-4.0),(-1,5.5),(0,5.5),(1,5.5),(2,-4.0),(3,-4.0) AS t(x,y)",
+ "input",
+ )
+ held_out = _vectors(
+ session,
+ "SELECT id, array(CAST(x AS DOUBLE)) AS xs "
+ "FROM VALUES (0,-2.5),(1,-0.5),(2,0.5),(3,2.5) AS t(id,x)",
+ "input",
+ )
+ options = dict(
+ featuresCol="input",
+ labelCol="target",
+ predictionCol="value",
+ maxDepth=3,
+ maxBins=16,
+ minInstancesPerNode=1,
+ minInfoGain=0.0,
+ maxMemoryInMB=64,
+ cacheNodeIds=True,
+ subsamplingRate=1.0,
+ checkpointInterval=-1,
+ lossType="squared",
+ maxIter=3,
+ stepSize=0.2,
+ seed=42,
+ impurity="variance",
+ featureSubsetStrategy="all",
+ leafCol="leaves",
+ minWeightFractionPerNode=0.0,
+ weightCol="weight",
+ )
+ if use_setters:
+ estimator = GBTRegressor(validationTol=0.05)
+ for name, value in options.items():
+ assert getattr(estimator, "set" + name[0].upper() +
name[1:])(value) is estimator
+ else:
+ estimator = GBTRegressor(**options, validationTol=0.05)
+ first = estimator.fit(training)
+ second = estimator.fit(training.withColumn("target", F.col("target") +
10.0))
+ expected = [-4.0, 5.5, 5.5, -4.0]
+ assert _predictions(first, held_out, "value") == expected
+ assert _predictions(second, held_out, "value") == [6.0, 15.5, 15.5, 6.0]
+ assert _predictions(estimator.fit(training), held_out, "value") == expected
+ leaves =
first.transform(held_out).select(vector_to_array("leaves").alias("leaf")).collect()
+ assert all(len(r.leaf) == 3 and all(x >= 0 for x in r.leaf) for r in
leaves)
+ delayed = first.transform(held_out).select("id", "value")
+ del first
+ gc.collect()
+ assert [r.value for r in delayed.orderBy("id").collect()] == expected
+
+
+def test_gbt_regressor_instance_weights_change_the_predicted_mean(session):
+ GBTRegressor = _regressor()
+ training = _vectors(
+ session,
+ "SELECT 0 AS id, array(0.0D) AS xs, CAST(y AS DOUBLE) AS label, CAST(w
AS DOUBLE) AS weight "
+ "FROM VALUES (-2,1),(-2,1),(-2,1),(10,9) AS t(y,w)",
+ )
+ plain = GBTRegressor(seed=42, maxDepth=0, maxIter=1).fit(training)
+ weighted = GBTRegressor(seed=42, maxDepth=0, maxIter=1,
weightCol="weight").fit(training)
+ assert _predictions(plain, training) == [1.0] * 4
+ assert _predictions(weighted, training) == [7.0] * 4
+
+
+def test_gbt_regressor_supports_squared_and_absolute_loss(session):
+ GBTRegressor = _regressor()
+ training = _vectors(
+ session,
+ "SELECT id, array(0.0D) AS xs, CAST(y AS DOUBLE) AS label "
+ "FROM VALUES (0,0),(1,0),(2,0),(3,10) AS t(id,y)",
+ )
+ options = dict(seed=42, maxDepth=0, maxIter=3, stepSize=0.5)
+ squared = GBTRegressor(**options, lossType="squared").fit(training)
+ absolute = GBTRegressor(**options, lossType="absolute").fit(training)
+ assert _predictions(squared, training) == pytest.approx([2.5] * 4)
+ assert _predictions(absolute, training) == pytest.approx([2.0] * 4)
+
+
+def
test_gbt_regressor_iterations_and_learning_rate_improve_squared_loss(session):
+ GBTRegressor = _regressor()
+ training = _vectors(
+ session,
+ "SELECT id, array(CAST(x AS DOUBLE)) AS xs, CAST(y AS DOUBLE) AS label
"
+ "FROM VALUES (0,-2,0),(1,-1,0),(2,1,2),(3,2,4) AS t(id,x,y)",
+ )
+
+ def error(iterations, step):
+ model = GBTRegressor(seed=42, maxDepth=1, maxIter=iterations,
stepSize=step).fit(training)
+ return sum(
+ (prediction - label) ** 2
+ for prediction, label in zip(_predictions(model, training), [0.0,
0.0, 2.0, 4.0])
+ )
+
+ assert error(1, 0.1) > error(3, 0.1) > error(3, 0.5)
+
+
+def
test_gbt_regressor_validation_rows_are_held_out_and_stop_boosting_early(session):
+ GBTRegressor = _regressor()
+ training = _vectors(
+ session,
+ "SELECT id, array(CAST(x AS DOUBLE)) AS xs, CAST(y AS DOUBLE) AS
label, validation "
+ "FROM VALUES
(0,-3,-2,false),(1,-2,-2,false),(2,2,3,false),(3,3,3,false),"
+ "(4,-3,3,true),(5,-2,3,true),(6,2,-2,true),(7,3,-2,true) AS
t(id,x,y,validation)",
+ )
+ options = dict(seed=42, maxDepth=1, maxIter=6, stepSize=0.2,
leafCol="leaves")
+ model = GBTRegressor(**options, validationIndicatorCol="validation",
validationTol=0.01).fit(
+ training
+ )
+ reference = GBTRegressor(seed=42, maxDepth=1, maxIter=1).fit(
+ training.filter(~F.col("validation"))
+ )
+ assert _predictions(model, training) == _predictions(reference, training)
+ leaves =
model.transform(training).select(vector_to_array("leaves").alias("leaf")).collect()
+ assert all(len(r.leaf) == 1 for r in leaves)
+ unvalidated =
GBTRegressor(**options).fit(training.filter(~F.col("validation")))
+ assert all(
+ len(r.leaf) == 6
+ for r in unvalidated.transform(training)
+ .select(vector_to_array("leaves").alias("leaf"))
+ .collect()
+ )
+
+
+def
test_gbt_regressor_seeded_subsampling_and_feature_sampling_are_reproducible(session):
+ GBTRegressor = _regressor()
+ training = _vectors(
+ session,
+ "SELECT id, array(CAST(id AS DOUBLE),CAST(id % 3 AS DOUBLE)) AS xs, "
+ "CAST(CASE WHEN id < 20 THEN -3 ELSE 8 END AS DOUBLE) AS label FROM
range(40)",
+ )
+ estimator = GBTRegressor(
+ seed=2**33,
+ maxDepth=2,
+ maxIter=5,
+ stepSize=0.2,
+ subsamplingRate=0.8,
+ featureSubsetStrategy="sqrt",
+ )
+ first = _predictions(estimator.fit(training), training)
+ assert first == pytest.approx(_predictions(estimator.fit(training),
training))
+ assert all(math.isfinite(x) for x in first)
+ assert first[0] < first[-1]
+
+
+def test_gbt_regressor_rejects_invalid_parameters_and_training_data(session):
+ GBTRegressor = _regressor()
+ training = _vectors(
+ session,
+ "SELECT array(CAST(x AS DOUBLE)) AS xs, CAST(y AS DOUBLE) AS label,
1.0D AS weight "
+ "FROM VALUES (-1,-2.5),(1,3.5) AS t(x,y)",
+ )
+ for options in [
+ dict(maxIter=0),
+ dict(stepSize=0.0),
+ dict(stepSize=1.1),
+ dict(validationTol=-0.1),
+ dict(lossType="logistic"),
+ dict(maxDepth=31),
+ dict(maxBins=1),
+ dict(minInstancesPerNode=0),
+ dict(minInfoGain=-1.0),
+ dict(maxMemoryInMB=-1),
+ dict(checkpointInterval=0),
+ dict(featureSubsetStrategy="invalid"),
+ dict(subsamplingRate=0.0),
+ dict(minWeightFractionPerNode=0.5),
+ ]:
+ with pytest.raises(Exception):
+ GBTRegressor(**options).fit(training)
+ for frame in [
+ training.drop("label"),
+ training.drop("features"),
+ training.withColumn("label", F.lit(float("nan"))),
+ training.withColumn("features", F.lit(1.0)),
+ ]:
+ with pytest.raises(Exception):
+ GBTRegressor(maxIter=1).fit(frame)
+ with pytest.raises(Exception):
+ GBTRegressor(weightCol="weight").fit(training.withColumn("weight",
F.lit(-1.0)))
+ with pytest.raises(Exception):
+ GBTRegressor(validationIndicatorCol="missing").fit(training)
diff --git a/python/tests/test_ml_e2e.py b/python/tests/test_ml_e2e.py
index 9ea0f3b7..e0c93f75 100644
--- a/python/tests/test_ml_e2e.py
+++ b/python/tests/test_ml_e2e.py
@@ -245,6 +245,7 @@ def _native_estimators():
DecisionTreeClassifier,
DecisionTreeRegressor,
GBTClassifier,
+ GBTRegressor,
KMeans,
LinearRegression,
LinearSVC,
@@ -258,6 +259,7 @@ def _native_estimators():
ml = "org.apache.spark.ml."
return [
+ (GBTRegressor(maxIter=2), ml + "regression.GBTRegressionModel"),
(GBTClassifier(maxIter=2), ml +
"classification.GBTClassificationModel"),
(DecisionTreeRegressor(), ml +
"regression.DecisionTreeRegressionModel"),
(DecisionTreeClassifier(), ml +
"classification.DecisionTreeClassificationModel"),
diff --git a/python/tests/test_ml_offline.py b/python/tests/test_ml_offline.py
index 89615a2b..fb982286 100644
--- a/python/tests/test_ml_offline.py
+++ b/python/tests/test_ml_offline.py
@@ -362,6 +362,14 @@ _NATIVE_PARAMS = {
seed="int", leafCol="str", minWeightFractionPerNode="float",
weightCol="str", thresholds="float_list",
),
+ "GBTRegressor": dict(
+ featuresCol="str", labelCol="str", predictionCol="str",
+ maxDepth="int", maxBins="int", minInstancesPerNode="int",
+ minInfoGain="float", maxMemoryInMB="int", cacheNodeIds="bool",
+ checkpointInterval="int", impurity="str", featureSubsetStrategy="str",
+ seed="int", subsamplingRate="float", leafCol="str",
minWeightFractionPerNode="float",
+ lossType="str", maxIter="int", stepSize="float",
validationIndicatorCol="str", weightCol="str",
+ ),
"GBTClassifier": dict(
featuresCol="str", labelCol="str", predictionCol="str",
maxDepth="int", maxBins="int", minInstancesPerNode="int",
@@ -2601,6 +2609,99 @@ def
test_decision_tree_regressor_native_parameters_match_official_fixture(ml_moc
assert params ==
pb2.MlParams.FromString(base64.b64decode(case["params_b64"]))
[email protected]("use_setters", [False, True], ids=["constructor",
"setters"])
+def test_gbt_regressor_native_parameters_match_official_fixture(ml_mock,
use_setters):
+ import base64
+ import inspect
+ import json
+ from pathlib import Path
+
+ import pyspark._pyspark as native
+ from pyspark.ml.connect import GBTRegressor as exported
+ from pyspark.ml.connect.regression import GBTRegressor
+
+ assert exported is GBTRegressor is native.GBTRegressor
+ defaults = dict(
+ featuresCol="features",
+ labelCol="label",
+ predictionCol="prediction",
+ maxDepth=5,
+ maxBins=32,
+ minInstancesPerNode=1,
+ minInfoGain=0.0,
+ maxMemoryInMB=256,
+ cacheNodeIds=False,
+ subsamplingRate=1.0,
+ checkpointInterval=10,
+ lossType="squared",
+ maxIter=20,
+ stepSize=0.1,
+ seed=None,
+ impurity="variance",
+ featureSubsetStrategy="all",
+ validationTol=0.1,
+ validationIndicatorCol=None,
+ leafCol="",
+ minWeightFractionPerNode=0.0,
+ weightCol=None,
+ )
+ signature = inspect.signature(GBTRegressor)
+ assert list(signature.parameters) == list(defaults)
+ for name, default in defaults.items():
+ assert signature.parameters[name].kind ==
inspect.Parameter.KEYWORD_ONLY
+ assert signature.parameters[name].default == default
+ assert not hasattr(GBTRegressor(), "setValidationTol")
+ fixture = json.loads(
+ (Path(__file__).resolve().parents[2] /
"tests/golden/gbt_regressor.json").read_text()
+ )
+ assert fixture["omitted_validation_tol"] == 0.01
+ assert fixture["explicit_validation_tol"] == 0.1
+ spark, service = ml_mock
+ models = []
+ assert _native_sent(spark, service, GBTRegressor(), models) == {}
+ assert _native_sent(spark, service, GBTRegressor(validationTol=0.1),
models) == {
+ "validationTol": ("double", fixture["explicit_validation_tol"])
+ }
+ for case in fixture["cases"]:
+ values = dict(
+ featuresCol="input",
+ labelCol="target",
+ predictionCol="value",
+ maxDepth=3,
+ maxBins=16,
+ minInstancesPerNode=2,
+ minInfoGain=0.01,
+ maxMemoryInMB=64,
+ cacheNodeIds=True,
+ subsamplingRate=0.75,
+ checkpointInterval=-1,
+ lossType="absolute",
+ maxIter=4,
+ stepSize=0.2,
+ seed=case["seed"],
+ impurity="variance",
+ featureSubsetStrategy="all",
+ validationIndicatorCol="validation",
+ leafCol="leaves",
+ minWeightFractionPerNode=0.1,
+ weightCol="weight",
+ )
+ if use_setters:
+ estimator = GBTRegressor(validationTol=0.05)
+ for name, value in values.items():
+ assert getattr(estimator, "set" + name[0].upper() +
name[1:])(value) is estimator
+ else:
+ estimator = GBTRegressor(**values, validationTol=0.05)
+ operator, params = _native_request(spark, service, estimator, models)
+ assert operator.name == "org.apache.spark.ml.regression.GBTRegressor"
+ assert params ==
pb2.MlParams.FromString(base64.b64decode(case["params_b64"]))
+ for value in [np.float64(0.05), 1, None]:
+ sent = _native_sent(spark, service, GBTRegressor(validationTol=value),
models)
+ assert sent["validationTol"][0] == ("null" if value is None else
"double")
+ with pytest.raises(TypeError, match="Invalid param value"):
+ GBTRegressor(validationTol="invalid")
+
+
@pytest.mark.parametrize("use_setters", [False, True], ids=["constructor",
"setters"])
def test_gbt_classifier_native_parameters_match_official_fixture(ml_mock,
use_setters):
import base64
diff --git a/scripts/capture_gbt_regressor_golden.py
b/scripts/capture_gbt_regressor_golden.py
new file mode 100644
index 00000000..039079df
--- /dev/null
+++ b/scripts/capture_gbt_regressor_golden.py
@@ -0,0 +1,75 @@
+#!/usr/bin/env python3
+"""Capture GBTRegressor wire parameters using official PySpark 4.3.0."""
+
+import argparse
+import base64
+import json
+from pathlib import Path
+
+from pyspark.ml.connect.serialize import serialize_ml_params
+from pyspark.ml.regression import GBTRegressor
+from pyspark.sql import SparkSession
+
+
+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/gbt_regressor.json"))
+ args = parser.parse_args()
+ spark = SparkSession.builder.remote(args.remote).getOrCreate()
+ # These literal-only parameters need no RPC, including when closing the
client.
+ spark.release_session_on_close = False
+ try:
+ cases = []
+ for seed in [42, -42, 2**31 - 1, 2**31, -(2**31), -(2**31) - 1]:
+ estimator = GBTRegressor(
+ featuresCol="input",
+ labelCol="target",
+ predictionCol="value",
+ maxDepth=3,
+ maxBins=16,
+ minInstancesPerNode=2,
+ minInfoGain=0.01,
+ maxMemoryInMB=64,
+ cacheNodeIds=True,
+ checkpointInterval=-1,
+ impurity="variance",
+ featureSubsetStrategy="all",
+ seed=seed,
+ subsamplingRate=0.75,
+ leafCol="leaves",
+ minWeightFractionPerNode=0.1,
+ weightCol="weight",
+ lossType="absolute",
+ maxIter=4,
+ stepSize=0.2,
+ validationTol=0.05,
+ validationIndicatorCol="validation",
+ )
+ params = serialize_ml_params(estimator, spark.client)
+ cases.append(
+ {
+ "seed": seed,
+ "params_b64": base64.b64encode(
+ params.SerializeToString(deterministic=True)
+ ).decode(),
+ }
+ )
+ args.out.write_text(
+ json.dumps(
+ {
+ "source": "apache/spark v4.3.0
pyspark.ml.regression.GBTRegressor",
+ "cases": cases,
+ "omitted_validation_tol":
GBTRegressor().getValidationTol(),
+ "explicit_validation_tol":
GBTRegressor(validationTol=0.1).getValidationTol(),
+ },
+ indent=2,
+ )
+ + "\n"
+ )
+ finally:
+ spark.stop()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/golden/gbt_regressor.json b/tests/golden/gbt_regressor.json
new file mode 100644
index 00000000..47aba041
--- /dev/null
+++ b/tests/golden/gbt_regressor.json
@@ -0,0 +1,31 @@
+{
+ "source": "apache/spark v4.3.0 pyspark.ml.regression.GBTRegressor",
+ "cases": [
+ {
+ "seed": 42,
+ "params_b64":
"ChIKDGNhY2hlTm9kZUlkcxICGAEKIQoSY2hlY2twb2ludEludGVydmFsEgsw////////////AQoeChVmZWF0dXJlU3Vic2V0U3RyYXRlZ3kSBWoDYWxsChYKC2ZlYXR1cmVzQ29sEgdqBWlucHV0ChYKCGltcHVyaXR5EgpqCHZhcmlhbmNlChQKCGxhYmVsQ29sEghqBnRhcmdldAoTCgdsZWFmQ29sEghqBmxlYXZlcwoWCghsb3NzVHlwZRIKaghhYnNvbHV0ZQoNCgdtYXhCaW5zEgIwEAoOCghtYXhEZXB0aBICMAMKDQoHbWF4SXRlchICMAQKEwoNbWF4TWVtb3J5SW5NQhICMEAKGAoLbWluSW5mb0dhaW4SCVl7FK5H4XqEPwoZChNtaW5JbnN0YW5jZXNQZXJOb2RlEgIwAgolChhtaW5XZWlnaHRGcmFjdGlvblBlck5vZGUSCVm
[...]
+ },
+ {
+ "seed": -42,
+ "params_b64":
"ChIKDGNhY2hlTm9kZUlkcxICGAEKIQoSY2hlY2twb2ludEludGVydmFsEgsw////////////AQoeChVmZWF0dXJlU3Vic2V0U3RyYXRlZ3kSBWoDYWxsChYKC2ZlYXR1cmVzQ29sEgdqBWlucHV0ChYKCGltcHVyaXR5EgpqCHZhcmlhbmNlChQKCGxhYmVsQ29sEghqBnRhcmdldAoTCgdsZWFmQ29sEghqBmxlYXZlcwoWCghsb3NzVHlwZRIKaghhYnNvbHV0ZQoNCgdtYXhCaW5zEgIwEAoOCghtYXhEZXB0aBICMAMKDQoHbWF4SXRlchICMAQKEwoNbWF4TWVtb3J5SW5NQhICMEAKGAoLbWluSW5mb0dhaW4SCVl7FK5H4XqEPwoZChNtaW5JbnN0YW5jZXNQZXJOb2RlEgIwAgolChhtaW5XZWlnaHRGcmFjdGlvblBlck5vZGUSCVm
[...]
+ },
+ {
+ "seed": 2147483647,
+ "params_b64":
"ChIKDGNhY2hlTm9kZUlkcxICGAEKIQoSY2hlY2twb2ludEludGVydmFsEgsw////////////AQoeChVmZWF0dXJlU3Vic2V0U3RyYXRlZ3kSBWoDYWxsChYKC2ZlYXR1cmVzQ29sEgdqBWlucHV0ChYKCGltcHVyaXR5EgpqCHZhcmlhbmNlChQKCGxhYmVsQ29sEghqBnRhcmdldAoTCgdsZWFmQ29sEghqBmxlYXZlcwoWCghsb3NzVHlwZRIKaghhYnNvbHV0ZQoNCgdtYXhCaW5zEgIwEAoOCghtYXhEZXB0aBICMAMKDQoHbWF4SXRlchICMAQKEwoNbWF4TWVtb3J5SW5NQhICMEAKGAoLbWluSW5mb0dhaW4SCVl7FK5H4XqEPwoZChNtaW5JbnN0YW5jZXNQZXJOb2RlEgIwAgolChhtaW5XZWlnaHRGcmFjdGlvblBlck5vZGUSCVm
[...]
+ },
+ {
+ "seed": 2147483648,
+ "params_b64":
"ChIKDGNhY2hlTm9kZUlkcxICGAEKIQoSY2hlY2twb2ludEludGVydmFsEgsw////////////AQoeChVmZWF0dXJlU3Vic2V0U3RyYXRlZ3kSBWoDYWxsChYKC2ZlYXR1cmVzQ29sEgdqBWlucHV0ChYKCGltcHVyaXR5EgpqCHZhcmlhbmNlChQKCGxhYmVsQ29sEghqBnRhcmdldAoTCgdsZWFmQ29sEghqBmxlYXZlcwoWCghsb3NzVHlwZRIKaghhYnNvbHV0ZQoNCgdtYXhCaW5zEgIwEAoOCghtYXhEZXB0aBICMAMKDQoHbWF4SXRlchICMAQKEwoNbWF4TWVtb3J5SW5NQhICMEAKGAoLbWluSW5mb0dhaW4SCVl7FK5H4XqEPwoZChNtaW5JbnN0YW5jZXNQZXJOb2RlEgIwAgolChhtaW5XZWlnaHRGcmFjdGlvblBlck5vZGUSCVm
[...]
+ },
+ {
+ "seed": -2147483648,
+ "params_b64":
"ChIKDGNhY2hlTm9kZUlkcxICGAEKIQoSY2hlY2twb2ludEludGVydmFsEgsw////////////AQoeChVmZWF0dXJlU3Vic2V0U3RyYXRlZ3kSBWoDYWxsChYKC2ZlYXR1cmVzQ29sEgdqBWlucHV0ChYKCGltcHVyaXR5EgpqCHZhcmlhbmNlChQKCGxhYmVsQ29sEghqBnRhcmdldAoTCgdsZWFmQ29sEghqBmxlYXZlcwoWCghsb3NzVHlwZRIKaghhYnNvbHV0ZQoNCgdtYXhCaW5zEgIwEAoOCghtYXhEZXB0aBICMAMKDQoHbWF4SXRlchICMAQKEwoNbWF4TWVtb3J5SW5NQhICMEAKGAoLbWluSW5mb0dhaW4SCVl7FK5H4XqEPwoZChNtaW5JbnN0YW5jZXNQZXJOb2RlEgIwAgolChhtaW5XZWlnaHRGcmFjdGlvblBlck5vZGUSCVm
[...]
+ },
+ {
+ "seed": -2147483649,
+ "params_b64":
"ChIKDGNhY2hlTm9kZUlkcxICGAEKIQoSY2hlY2twb2ludEludGVydmFsEgsw////////////AQoeChVmZWF0dXJlU3Vic2V0U3RyYXRlZ3kSBWoDYWxsChYKC2ZlYXR1cmVzQ29sEgdqBWlucHV0ChYKCGltcHVyaXR5EgpqCHZhcmlhbmNlChQKCGxhYmVsQ29sEghqBnRhcmdldAoTCgdsZWFmQ29sEghqBmxlYXZlcwoWCghsb3NzVHlwZRIKaghhYnNvbHV0ZQoNCgdtYXhCaW5zEgIwEAoOCghtYXhEZXB0aBICMAMKDQoHbWF4SXRlchICMAQKEwoNbWF4TWVtb3J5SW5NQhICMEAKGAoLbWluSW5mb0dhaW4SCVl7FK5H4XqEPwoZChNtaW5JbnN0YW5jZXNQZXJOb2RlEgIwAgolChhtaW5XZWlnaHRGcmFjdGlvblBlck5vZGUSCVm
[...]
+ }
+ ],
+ "omitted_validation_tol": 0.01,
+ "explicit_validation_tol": 0.1
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]