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 43b5c522 [SPARK-61519][CONNECT] Support native GBTClassifier training
and prediction
43b5c522 is described below
commit 43b5c5225d3518a2897d9691e9f4096755e87962
Author: Ruifeng Zheng <[email protected]>
AuthorDate: Thu Nov 12 18:03:47 2026 +0900
[SPARK-61519][CONNECT] Support native GBTClassifier training and prediction
### What changes were proposed in this pull request?
Add native Rust `GBTClassifier` and `GBTClassificationModel`, with
`pyspark.ml.connect.classification.GBTClassifier` and the top-level Connect
export. The estimator fits Spark's JVM implementation through Connect and
transforms DataFrames using the cached server model. Models, clones and lazy
transformed DataFrames retain that cache entry until their last owner is
dropped.
Rust setters/getters cover all 22 PySpark 4.3.0 constructor parameters,
plus probability/raw-prediction column names and class thresholds. The Python
signature and setters match the reference: those three outputs are setter-only,
and `validationTol` is a constructor argument without a Python setter.
Add official wire fixtures, native Rust/Python tests, compatibility
documentation and live CI coverage.
### Why are the changes needed?
The native API has decision trees and random forests but lacks
gradient-boosted classification. This adds binary GBT training, including
validation-set early stopping, through the existing native ML path.
### Does this PR introduce _any_ user-facing change?
Yes. GBTClassifier accepts ML vector features and labels 0 or 1, with
instance weights, row/feature sampling, learning rate and iteration limits. It
produces predictions, probabilities, raw margins and optional per-tree leaf
IDs. With `validationIndicatorCol`, false rows train and true rows validate;
early stopping can fit fewer than `maxIter` trees.
This addition covers fitting and DataFrame transformation. Multiclass
training, model inspection, per-iteration evaluation, single-vector prediction
and persistence are outside its scope.
### How was this patch tested?
- 624 Rust library tests passed. All integration tests compile in release
mode, with and without `wasm-udf`.
- Official PySpark 4.3.0 wire fixtures cover all 25 supported parameters
and six seed boundaries. The golden test and five live Rust tests passed.
- The same seven GBT behavior cases passed with official PySpark and the
rebuilt native Python client, covering nonlinear labels, probabilities/raw
margins, weights, thresholds, iteration count, learning rate, held-out
validation/early stopping and repeatable sampling. Shared model-cache lifetime
and session-isolation tests also passed: nine selected native live tests in
total.
- 2,017 native Python offline tests passed (8 skipped). Native class
identity, all 22 constructor defaults and all 24 Python setters were checked
against the reference. The 12-class public API comparison found no unexpected
gaps.
- Official Spark 4.3.0 Connect tests through the rebuilt Rust transport:
2,638 passed, 589 skipped across 87 files, zero unexpected failures.
- Rust formatting, Ruff 0.14.0 lint/format, vendored-path lint exclusions
and whitespace checks passed. Clippy passes for the Rust library and new
integration targets; workspace Clippy retains existing errors whose source is
unchanged on the base.
### 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 #553 from zhengruifeng/add-gbt-classifier.
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 | 258 +++++++-
crates/spark-connect/src/ml.rs | 652 +++++++++++++++++++++
crates/spark-connect/tests/e2e_gbt_classifier.rs | 289 +++++++++
.../spark-connect/tests/gbt_classifier_golden.rs | 49 ++
docs/compatibility.md | 24 +
python/pyspark/ml/connect/__init__.py | 2 +
python/pyspark/ml/connect/classification.py | 3 +-
python/tests/test_gbt_classifier_e2e.py | 188 ++++++
python/tests/test_ml_e2e.py | 2 +
python/tests/test_ml_offline.py | 83 +++
scripts/capture_gbt_classifier_golden.py | 78 +++
tests/golden/gbt_classifier.json | 29 +
14 files changed, 1655 insertions(+), 7 deletions(-)
diff --git a/.github/workflows/build_python_connect.yml
b/.github/workflows/build_python_connect.yml
index 0a68f0ea..dba4467c 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 -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 -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_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_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 e4b30ff7..3c2a27e8 100644
--- a/crates/pyspark-rs/src/lib.rs
+++ b/crates/pyspark-rs/src/lib.rs
@@ -226,6 +226,7 @@ fn _pyspark(_py: Python<'_>, m: &Bound<'_, PyModule>) ->
PyResult<()> {
m.add_class::<ml::PyLinearSVC>()?;
m.add_class::<ml::PyLinearRegression>()?;
m.add_class::<ml::PyDecisionTreeClassifier>()?;
+ m.add_class::<ml::PyGBTClassifier>()?;
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 de7029ea..b2d5969c 100644
--- a/crates/pyspark-rs/src/ml.rs
+++ b/crates/pyspark-rs/src/ml.rs
@@ -16,10 +16,10 @@ use pyo3::types::{PyDict, PyTuple, PyType};
use pyo3::PyClass;
use spark_connect::ml::{
BinaryClassificationEvaluator, CrossValidator, DecisionTreeClassifier,
DecisionTreeRegressor,
- Estimator, Evaluator, KMeans, LinearRegression, LinearSVC,
LogisticRegression, MaxAbsScaler,
- Model, MulticlassClassificationEvaluator, Params, Pipeline,
RandomForestClassifier,
- RandomForestRegressor, RegressionEvaluator, StandardScaler, StringIndexer,
Transformer,
- VectorAssembler,
+ Estimator, Evaluator, GBTClassifier, KMeans, LinearRegression, LinearSVC,
LogisticRegression,
+ MaxAbsScaler, Model, MulticlassClassificationEvaluator, Params, Pipeline,
+ RandomForestClassifier, RandomForestRegressor, RegressionEvaluator,
StandardScaler,
+ StringIndexer, Transformer, VectorAssembler,
};
use spark_connect::DataFrame;
@@ -1100,6 +1100,255 @@ impl PyDecisionTreeClassifier {
}
}
+/// Gradient-boosted binary classifier fitted and cached by Spark Connect.
+#[pyclass(name = "GBTClassifier", module =
"pyspark.ml.connect.classification")]
+pub struct PyGBTClassifier {
+ inner: GBTClassifier,
+ unsendable: Vec<&'static str>,
+}
+
+const GBT_CLASSIFIER_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),
+ ("checkpointInterval", Kind::Int),
+ ("lossType", Kind::Str),
+ ("maxIter", Kind::Int),
+ ("stepSize", Kind::Float),
+ ("seed", Kind::Int),
+ ("subsamplingRate", Kind::Float),
+ ("impurity", Kind::Str),
+ ("featureSubsetStrategy", Kind::Str),
+ ("validationTol", Kind::Float),
+ ("validationIndicatorCol", Kind::Str),
+ ("leafCol", Kind::Str),
+ ("minWeightFractionPerNode", Kind::Float),
+ ("weightCol", Kind::Str),
+];
+
+#[pymethods]
+impl PyGBTClassifier {
+ #[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, checkpointInterval=10,
lossType='logistic', maxIter=20, stepSize=0.1, seed=None, subsamplingRate=1.0,
impurity='variance', featureSubsetStrategy='all', validationTol=0.01,
validationIndicatorCol=None, leafCol='', minWeightFractionPerNode=0.0,
weightCol=None)")]
+ fn new(args: &Bound<'_, PyTuple>, kwargs: Option<&Bound<'_, PyDict>>) ->
PyResult<Self> {
+ let mut this = Self {
+ inner: GBTClassifier::new(),
+ unsendable: Vec::new(),
+ };
+ init_params(
+ &mut this,
+ "GBTClassifier",
+ &[],
+ GBT_CLASSIFIER_PARAMS,
+ args,
+ kwargs,
+ )?;
+ Ok(this)
+ }
+
+ #[pyo3(name = "setFeaturesCol")]
+ fn set_feature_col<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "featuresCol", Kind::Str, value)
+ }
+
+ #[pyo3(name = "setLabelCol")]
+ fn set_label_col<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "labelCol", Kind::Str, value)
+ }
+
+ #[pyo3(name = "setPredictionCol")]
+ fn set_prediction_col<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "predictionCol", Kind::Str, value)
+ }
+
+ #[pyo3(name = "setProbabilityCol")]
+ fn set_probability_col<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "probabilityCol", Kind::Str, value)
+ }
+
+ #[pyo3(name = "setRawPredictionCol")]
+ fn set_raw_prediction_col<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "rawPredictionCol", Kind::Str, value)
+ }
+
+ #[pyo3(name = "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 = "setThresholds")]
+ fn set_thresholds<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "thresholds", Kind::FloatList, value)
+ }
+
+ #[pyo3(name = "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)
+ }
+}
+
/// Random forest classifier fitted and cached by Spark Connect.
#[pyclass(
name = "RandomForestClassifier",
@@ -2186,6 +2435,7 @@ native!(
PyLinearSVC => LinearSVC,
PyLinearRegression => LinearRegression,
PyDecisionTreeClassifier => DecisionTreeClassifier,
+ PyGBTClassifier => GBTClassifier,
PyRandomForestClassifier => RandomForestClassifier,
PyDecisionTreeRegressor => DecisionTreeRegressor,
PyRandomForestRegressor => RandomForestRegressor,
diff --git a/crates/spark-connect/src/ml.rs b/crates/spark-connect/src/ml.rs
index 29b243a3..1dd906e9 100644
--- a/crates/spark-connect/src/ml.rs
+++ b/crates/spark-connect/src/ml.rs
@@ -2198,6 +2198,394 @@ impl Model for DecisionTreeClassificationModel {
}
}
+/// Gradient-boosted binary classification using Spark's JVM implementation
and ML vectors.
+///
+/// Labels must be 0 or 1. 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 GBTClassifier {
+ operator: MlOperator,
+ params: Params,
+}
+
+impl GBTClassifier {
+ pub fn new() -> Self {
+ Self {
+ operator: MlOperator::new(
+ "org.apache.spark.ml.classification.GBTClassifier",
+ 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
+ }
+
+ /// Numeric binary label column; labels must be 0 or 1.
+ pub fn set_label_col(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("labelCol", value);
+ self
+ }
+
+ /// Predicted class output column.
+ pub fn set_prediction_col(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("predictionCol", value);
+ self
+ }
+
+ /// Class probability output column.
+ pub fn set_probability_col(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("probabilityCol", value);
+ self
+ }
+
+ /// Raw class prediction output column.
+ pub fn set_raw_prediction_col(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("rawPredictionCol", 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
+ }
+
+ /// Per-class thresholds: predictions maximize probability divided by
threshold.
+ /// Provide one nonnegative value per class, with at most one zero.
+ pub fn set_thresholds(mut self, values: impl IntoIterator<Item = f64>) ->
Self {
+ self.params = self.params.set_param_double_array("thresholds", values);
+ 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 predicted class output column (default: "prediction").
+ pub fn prediction_col(&self) -> &str {
+ self.params.string_or("predictionCol", "prediction")
+ }
+
+ /// The class probability output column (default: "probability").
+ pub fn probability_col(&self) -> &str {
+ self.params.string_or("probabilityCol", "probability")
+ }
+
+ /// The raw class prediction output column (default: "rawPrediction").
+ pub fn raw_prediction_col(&self) -> &str {
+ self.params.string_or("rawPredictionCol", "rawPrediction")
+ }
+
+ /// 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")
+ }
+
+ /// The per-class thresholds, if they are set.
+ pub fn thresholds(&self) -> Option<Vec<f64>> {
+ self.params.double_array_opt("thresholds")
+ }
+
+ /// Loss function; Spark supports logistic loss.
+ pub fn set_loss_type(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("lossType", value);
+ self
+ }
+
+ /// The lossType value; default: "logistic".
+ pub fn loss_type(&self) -> &str {
+ self.params.string_or("lossType", "logistic")
+ }
+
+ /// 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<GBTClassificationModel> {
+ let cached = CachedModel::from_info(&info, session, "GBTClassifier")?;
+ Ok(GBTClassificationModel {
+ operator: MlOperator::with_uid(
+ "org.apache.spark.ml.classification.GBTClassificationModel",
+ info.uid.as_deref().unwrap_or(&self.operator.uid),
+ OperatorType::Model,
+ ),
+ params: self.params.clone(),
+ cached,
+ })
+ }
+}
+
+impl Default for GBTClassifier {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl Estimator for GBTClassifier {
+ 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 classification 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 GBTClassificationModel {
+ operator: MlOperator,
+ params: Params,
+ cached: CachedModel,
+}
+
+impl Transformer for GBTClassificationModel {
+ 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 GBTClassificationModel {
+ fn clone_box(&self) -> Box<dyn Model> {
+ Box::new(self.clone())
+ }
+}
+
/// Random forest classification using Spark's JVM implementation and ML
vector features.
///
/// Supports binary and multiclass labels. Unset parameters use Spark's
defaults. Without a
@@ -4906,6 +5294,268 @@ mod tests {
assert!(model.clone_box().transform(&df).is_ok());
}
#[test]
+ fn gbt_classifier_getters_follow_defaults_builders_and_mutable_params() {
+ let mut tree = GBTClassifier::default();
+ assert_eq!(tree.feature_col(), "features");
+ assert_eq!(tree.label_col(), "label");
+ assert_eq!(tree.prediction_col(), "prediction");
+ assert_eq!(tree.probability_col(), "probability");
+ assert_eq!(tree.raw_prediction_col(), "rawPrediction");
+ 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.thresholds(), None);
+ assert_eq!(tree.loss_type(), "logistic");
+ 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 = GBTClassifier::new()
+ .set_feature_col("input")
+ .set_label_col("target")
+ .set_prediction_col("class")
+ .set_probability_col("probs")
+ .set_raw_prediction_col("margin")
+ .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_thresholds([0.25, 0.75])
+ .set_loss_type("logistic")
+ .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", "class");
+ assert_eq!(tree.prediction_col(), "class");
+ assert_eq!(built.prediction_col(), tree.prediction_col());
+ *tree.params_mut() = tree
+ .params()
+ .clone()
+ .set_param_string("probabilityCol", "probs");
+ assert_eq!(tree.probability_col(), "probs");
+ assert_eq!(built.probability_col(), tree.probability_col());
+ *tree.params_mut() = tree
+ .params()
+ .clone()
+ .set_param_string("rawPredictionCol", "margin");
+ assert_eq!(tree.raw_prediction_col(), "margin");
+ assert_eq!(built.raw_prediction_col(), tree.raw_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_double_array("thresholds", [0.25, 0.75]);
+ assert_eq!(tree.thresholds(), Some(vec![0.25, 0.75]));
+ assert_eq!(built.thresholds(), tree.thresholds());
+ *tree.params_mut() = tree
+ .params()
+ .clone()
+ .set_param_string("lossType", "logistic");
+ assert_eq!(tree.loss_type(), "logistic");
+ 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("GBTClassifier_"));
+ }
+
+ #[test]
+ fn gbt_classifier_validates_fitted_references_and_model_metadata() {
+ let session = offline_session();
+ let estimator = GBTClassifier::default().set_prediction_col("class");
+ assert_eq!(
+ estimator.operator().name,
+ "org.apache.spark.ml.classification.GBTClassifier"
+ );
+ 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-classifier".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.classification.GBTClassificationModel"
+ );
+ 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-classifier".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 random_forest_validates_fitted_references_and_model_metadata() {
let session = offline_session();
let estimator =
RandomForestClassifier::default().set_prediction_col("class");
@@ -5282,6 +5932,8 @@ mod tests {
assert_eq!(sent(tree.params()), Some(expected.clone()));
let tree_regressor = DecisionTreeRegressor::new().set_seed(seed);
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 cv = CrossValidator::new().set_seed(seed);
assert_eq!(sent(cv.params()), Some(expected));
}
diff --git a/crates/spark-connect/tests/e2e_gbt_classifier.rs
b/crates/spark-connect/tests/e2e_gbt_classifier.rs
new file mode 100644
index 00000000..038293ec
--- /dev/null
+++ b/crates/spark-connect/tests/e2e_gbt_classifier.rs
@@ -0,0 +1,289 @@
+//! Native gradient-boosted classifier 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, GBTClassifier};
+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() -> GBTClassifier {
+ GBTClassifier::new()
+ .set_seed(42)
+ .set_max_iter(3)
+ .set_feature_subset_strategy("all")
+}
+
+#[test]
+fn gbt_classifier_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,0),(-2,0),(-1,1),(0,1),(1,1),(2,0),(3,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("class")
+ .set_probability_col("probs")
+ .set_raw_prediction_col("votes")
+ .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", lit_double(1.0) - col("target")))
+ .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("class")]);
+ drop(first);
+ let output = cloned.transform(&held_out).unwrap();
+ assert_eq!(
+ predictions(output.clone(), "class"),
+ vec![0.0, 1.0, 1.0, 0.0]
+ );
+ let vectors = output
+ .select([
+ vector_array("probs"),
+ vector_array("votes"),
+ vector_array("leaves"),
+ ])
+ .collect()
+ .unwrap();
+ for row in vectors {
+ for (i, size) in [(0, 2), (1, 2), (2, 3)] {
+ let spark_connect::row::Value::List(values) = row.get(i).unwrap()
else {
+ panic!("vector array")
+ };
+ assert_eq!(values.len(), size);
+ }
+ }
+ let mut repeated = estimator.fit(&training).unwrap();
+ assert_eq!(
+ predictions(repeated.transform(&held_out).unwrap(), "class"),
+ vec![0.0, 1.0, 1.0, 0.0]
+ );
+ drop(cloned);
+ assert_eq!(predictions(delayed, "class"), vec![0.0, 1.0, 1.0, 0.0]);
+ assert_eq!(
+ predictions(second.transform(&held_out).unwrap(), "class"),
+ vec![1.0, 0.0, 0.0, 1.0]
+ );
+ assert!(second
+ .transform(&s.new_session().range(1).unwrap())
+ .is_err());
+ s.stop().unwrap();
+}
+
+#[test]
+fn gbt_classifier_weights_and_class_thresholds_change_predictions() {
+ let Some(s) = live_session() else {
+ return;
+ };
+ // No split: the class probability is the (weighted) label frequency.
+ let training = vectors(
+ &s,
+ "SELECT array(0.0D) AS xs, CAST(y AS DOUBLE) AS label, CAST(w AS
DOUBLE) AS weight
+ FROM VALUES (0,1),(0,1),(0,1),(1,9) AS t(y,w)",
+ "features",
+ );
+ let held_out = vectors(&s, "SELECT 0 AS id, array(0.0D) AS xs",
"features");
+ let mut plain = deterministic().set_max_depth(0).fit(&training).unwrap();
+ let mut weighted = deterministic()
+ .set_max_depth(0)
+ .set_weight_col("weight")
+ .fit(&training)
+ .unwrap();
+ let mut thresholded = deterministic()
+ .set_max_depth(0)
+ .set_thresholds([1.0, 0.1])
+ .fit(&training)
+ .unwrap();
+ assert_eq!(
+ predictions(plain.transform(&held_out).unwrap(), "prediction"),
+ vec![0.0]
+ );
+ assert_eq!(
+ predictions(weighted.transform(&held_out).unwrap(), "prediction"),
+ vec![1.0]
+ );
+ assert_eq!(
+ predictions(thresholded.transform(&held_out).unwrap(), "prediction"),
+ vec![1.0]
+ );
+ s.stop().unwrap();
+}
+
+#[test]
+fn gbt_classifier_subsampling_and_feature_sampling_train_reproducibly() {
+ let Some(s) = live_session() else {
+ return;
+ };
+ let training = vectors(
+ &s,
+ "SELECT id, array(CAST(id AS DOUBLE), CAST(id % 3 AS DOUBLE)) AS xs,
+ CAST(CASE WHEN id < 20 THEN 0 ELSE 1 END AS DOUBLE) AS label FROM
range(40)",
+ "features",
+ );
+ let mut estimator = GBTClassifier::default()
+ .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(&training).unwrap();
+ let mut repeated = estimator.fit(&training).unwrap();
+ let first = predictions(first.transform(&training).unwrap(), "prediction");
+ assert_eq!(
+ first,
+ predictions(repeated.transform(&training).unwrap(), "prediction")
+ );
+ assert!(first[..15].iter().all(|p| *p == 0.0));
+ assert!(first[25..].iter().all(|p| *p == 1.0));
+ s.stop().unwrap();
+}
+
+#[test]
+fn gbt_classifier_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,0),(1,1) AS t(x,y)",
+ "features",
+ );
+ for mut estimator in [
+ deterministic().set_max_iter(0),
+ deterministic().set_max_depth(31),
+ 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("squared"),
+ deterministic().set_step_size(0.0),
+ deterministic().set_validation_tol(-0.1),
+ deterministic().set_feature_subset_strategy("invalid"),
+ deterministic().set_subsampling_rate(0.0),
+ deterministic().set_min_weight_fraction_per_node(0.5),
+ deterministic().set_thresholds([1.0, 1.0, 1.0]),
+ ] {
+ assert!(
+ estimator.fit(&data).is_err(),
+ "invalid params: {:?}",
+ estimator.params()
+ );
+ }
+ assert!(deterministic().fit(&data.drop(vec!["label"])).is_err());
+ assert!(deterministic()
+ .fit(&data.with_column("label", lit_double(2.0)))
+ .is_err());
+ assert!(deterministic()
+ .set_weight_col("weight")
+ .fit(&data.with_column("weight", lit_double(-1.0)))
+ .is_err());
+ s.stop().unwrap();
+}
+
+#[test]
+fn gbt_classifier_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,0,false),(1,-2,0,false),(2,2,1,false),(3,3,1,false),
+ (4,-3,1,true),(5,-2,1,true),(6,2,0,true),(7,3,0,true) AS
t(id,x,y,validation)",
+ "features",
+ );
+ let mut model = GBTClassifier::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![0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.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_classifier_golden.rs
b/crates/spark-connect/tests/gbt_classifier_golden.rs
new file mode 100644
index 00000000..accc502e
--- /dev/null
+++ b/crates/spark-connect/tests/gbt_classifier_golden.rs
@@ -0,0 +1,49 @@
+//! Match every GBTClassifier parameter and seed boundary to official PySpark.
+use base64::{engine::general_purpose::STANDARD, Engine};
+use prost::Message;
+use spark_connect::ml::{Estimator, GBTClassifier};
+
+#[test]
+fn gbt_classifier_parameters_match_official_pyspark() {
+ let fixture: serde_json::Value =
+
serde_json::from_str(include_str!("../../../tests/golden/gbt_classifier.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 = GBTClassifier::new()
+ .set_feature_col("input")
+ .set_label_col("target")
+ .set_prediction_col("class")
+ .set_probability_col("probs")
+ .set_raw_prediction_col("margin")
+ .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("logistic")
+ .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")
+ .set_thresholds([0.25, 0.75]);
+ assert_eq!(estimator.params().to_proto(), expected, "seed {seed}");
+ }
+ assert!(GBTClassifier::default()
+ .params()
+ .to_proto()
+ .params
+ .is_empty());
+}
diff --git a/docs/compatibility.md b/docs/compatibility.md
index 454c0cdb..e9fc17f6 100644
--- a/docs/compatibility.md
+++ b/docs/compatibility.md
@@ -213,6 +213,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 GBTClassifier
+
+`spark_connect::ml::GBTClassifier` fits Spark's JVM gradient-boosted binary
+classifier through Connect with ML vector features and labels 0 or 1. Rust
builder
+setters/getters cover all 22 PySpark constructor parameters, plus
probability/raw
+prediction column names and class thresholds. Unset parameters use Spark's
defaults.
+A seed controls split-candidate row sampling, subsampling and feature sampling.
+
+The Python binding is available as
`pyspark.ml.connect.classification.GBTClassifier`
+and `pyspark.ml.connect.GBTClassifier`. Its keyword-only constructor mirrors
PySpark.
+Probability/raw prediction column names and thresholds are set through
+`setProbabilityCol`, `setRawPredictionCol` and `setThresholds`.
`validationTol` is a
+constructor argument; PySpark does not provide a Python setter for it.
+
+`maxIter` limits boosting iterations, and `stepSize` scales each tree after the
+first. With `validationIndicatorCol`, false rows train the trees and true rows
+validate early stopping; the resulting ensemble can contain fewer than
`maxIter`
+trees. DataFrame transforms expose predictions, probabilities, raw margins and
an
+optional vector of leaf IDs, one per fitted tree. Instance weights are
supported.
+Models, clones and lazy transformed DataFrames retain the cached model in its
+fitting session until the last owner is dropped. Multiclass training, model
+inspection, per-iteration evaluation, single-vector prediction and persistence
+are outside this native addition.
+
## Native DecisionTreeRegressor
`spark_connect::ml::DecisionTreeRegressor` fits Spark's JVM decision tree
diff --git a/python/pyspark/ml/connect/__init__.py
b/python/pyspark/ml/connect/__init__.py
index 4cbb5bcf..6e814f86 100644
--- a/python/pyspark/ml/connect/__init__.py
+++ b/python/pyspark/ml/connect/__init__.py
@@ -12,6 +12,7 @@ from pyspark.ml.connect.feature import (
VectorAssembler,
)
from pyspark.ml.connect.classification import (
+ GBTClassifier,
DecisionTreeClassifier,
LinearSVC,
LogisticRegression,
@@ -56,6 +57,7 @@ __all__ = [
"LogisticRegression",
"LinearSVC",
"DecisionTreeClassifier",
+ "GBTClassifier",
"RandomForestClassifier",
"LinearRegression",
"DecisionTreeRegressor",
diff --git a/python/pyspark/ml/connect/classification.py
b/python/pyspark/ml/connect/classification.py
index 6e1e8ae4..f7ee44f5 100644
--- a/python/pyspark/ml/connect/classification.py
+++ b/python/pyspark/ml/connect/classification.py
@@ -1,9 +1,10 @@
"""Classification estimators (pyspark.ml.connect.classification)."""
from pyspark._pyspark import (
DecisionTreeClassifier,
+ GBTClassifier,
LinearSVC,
LogisticRegression,
RandomForestClassifier,
)
-__all__ = ["DecisionTreeClassifier", "LinearSVC", "LogisticRegression",
"RandomForestClassifier"]
+__all__ = ["GBTClassifier", "DecisionTreeClassifier", "LinearSVC",
"LogisticRegression", "RandomForestClassifier"]
diff --git a/python/tests/test_gbt_classifier_e2e.py
b/python/tests/test_gbt_classifier_e2e.py
new file mode 100644
index 00000000..87d42597
--- /dev/null
+++ b/python/tests/test_gbt_classifier_e2e.py
@@ -0,0 +1,188 @@
+#
+# 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 GBTClassifier 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 _classifier():
+ try:
+ from pyspark.ml.connect.classification import GBTClassifier
+ except ImportError:
+ from pyspark.ml.classification import GBTClassifier
+ return GBTClassifier
+
+
+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_classifier_learns_nonlinear_labels_and_retains_lazy_predictions(session,
use_setters):
+ GBTClassifier = _classifier()
+ training = _vectors(session,
+ "SELECT array(CAST(x AS DOUBLE)) AS xs, CAST(y AS DOUBLE) AS target,
1.0D AS weight "
+ "FROM VALUES (-3,0),(-2,0),(-1,1),(0,1),(1,1),(2,0),(3,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="class", maxDepth=3,
+ maxBins=16, minInstancesPerNode=1, minInfoGain=0.0,
maxMemoryInMB=64,
+ cacheNodeIds=True, checkpointInterval=-1,
lossType="logistic", maxIter=3,
+ stepSize=0.2, seed=42, subsamplingRate=1.0,
impurity="variance",
+ featureSubsetStrategy="all", leafCol="leaves",
minWeightFractionPerNode=0.0,
+ weightCol="weight")
+ if use_setters:
+ estimator = GBTClassifier(validationTol=0.02)
+ for name, value in options.items():
+ assert getattr(estimator, "set" + name[0].upper() +
name[1:])(value) is estimator
+ else:
+ estimator = GBTClassifier(**options, validationTol=0.02)
+ assert estimator.setProbabilityCol("probs") is estimator
+ assert estimator.setRawPredictionCol("margin") is estimator
+ first = estimator.fit(training)
+ second = estimator.fit(training.withColumn("target", 1.0 -
F.col("target")))
+ expected = [0.0,1.0,1.0,0.0]
+ assert _predictions(first, held_out, "class") == expected
+ assert _predictions(second, held_out, "class") == [1.0,0.0,0.0,1.0]
+ assert _predictions(estimator.fit(training), held_out, "class") == expected
+ rows = first.transform(held_out).orderBy("id").select(
+ vector_to_array("probs").alias("p"),
vector_to_array("margin").alias("raw"),
+ vector_to_array("leaves").alias("leaf")).collect()
+ for cls,row in zip(expected,rows):
+ assert len(row.p) == len(row.raw) == 2
+ assert sum(row.p) == pytest.approx(1.0)
+ assert row.raw[0] == pytest.approx(-row.raw[1])
+ assert row.p[1] == pytest.approx(1.0 / (1.0 + math.exp(2.0 *
row.raw[0])))
+ assert row.p[int(cls)] > 0.5
+ assert len(row.leaf) == 3 and all(x >= 0 for x in row.leaf)
+ delayed = first.transform(held_out).select("id", "class")
+ del first
+ gc.collect()
+ assert [r["class"] for r in delayed.orderBy("id").collect()] == expected
+
+
+def
test_gbt_classifier_weights_and_thresholds_change_the_predicted_class(session):
+ GBTClassifier = _classifier()
+ training = _vectors(session,
+ "SELECT array(0.0D) AS xs, CAST(y AS DOUBLE) AS label, CAST(w AS
DOUBLE) AS weight "
+ "FROM VALUES (0,1),(0,1),(0,1),(1,9) AS t(y,w)")
+ test = _vectors(session, "SELECT 0 AS id, array(0.0D) AS xs")
+ options = dict(maxDepth=0, maxIter=1, seed=42)
+ plain = GBTClassifier(**options).fit(training)
+ weighted = GBTClassifier(**options, weightCol="weight").fit(training)
+ thresholded =
GBTClassifier(**options).setThresholds([1.0,0.1]).fit(training)
+ assert _predictions(plain, test) == [0.0]
+ assert _predictions(weighted, test) == [1.0]
+ assert _predictions(thresholded, test) == [1.0]
+ for model, raw, p1 in [(plain,[0.5,-0.5],1.0/(1.0+math.e)),
+ (weighted,[-0.5,0.5],1.0/(1.0+math.exp(-1.0))),
+ (thresholded,[0.5,-0.5],1.0/(1.0+math.e))]:
+ row =
model.transform(test).select(vector_to_array("rawPrediction").alias("raw"),
+
vector_to_array("probability").alias("p")).first()
+ assert row.raw == pytest.approx(raw)
+ assert row.p == pytest.approx([1.0-p1,p1])
+
+
+def
test_gbt_classifier_iterations_and_learning_rate_change_probabilities(session):
+ GBTClassifier = _classifier()
+ training = _vectors(session,
+ "SELECT id, array(CAST(id AS DOUBLE)) AS xs, CAST(id >= 4 AS DOUBLE)
AS label FROM range(8)")
+ def confidence(iterations, step):
+ model = GBTClassifier(seed=42, maxDepth=1, maxIter=iterations,
stepSize=step).fit(training)
+ return
model.transform(training).orderBy("id").select(vector_to_array("probability").alias("p")).first().p[0]
+ initial = confidence(1,0.1)
+ slow = confidence(3,0.1)
+ fast = confidence(3,0.5)
+ assert 0.5 < initial < slow < fast < 1.0
+
+
+def
test_gbt_classifier_validation_rows_are_held_out_and_stop_boosting_early(session):
+ GBTClassifier = _classifier()
+ training = _vectors(session,
+ "SELECT id, array(CAST(x AS DOUBLE)) AS xs, CAST(y AS DOUBLE) AS
label, validation "
+ "FROM VALUES
(0,-3,0,false),(1,-2,0,false),(2,2,1,false),(3,3,1,false),"
+ "(4,-3,1,true),(5,-2,1,true),(6,2,0,true),(7,3,0,true) AS
t(id,x,y,validation)")
+ options = dict(seed=42, maxDepth=1, maxIter=6, stepSize=0.2,
leafCol="leaves")
+ model = GBTClassifier(**options, validationIndicatorCol="validation",
validationTol=0.01).fit(training)
+ reference = GBTClassifier(seed=42, maxDepth=1,
maxIter=1).fit(training.filter(~F.col("validation")))
+ assert _predictions(model, training) == _predictions(reference, training)
+ rows =
model.transform(training).select(vector_to_array("leaves").alias("leaf")).collect()
+ assert all(len(r.leaf) == 1 for r in rows)
+ unvalidated =
GBTClassifier(**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_classifier_seeded_subsampling_and_feature_sampling_are_reproducible(session):
+ GBTClassifier = _classifier()
+ training = _vectors(session,
+ "SELECT id, array(CAST(id AS DOUBLE),CAST(id % 3 AS DOUBLE)) AS xs, "
+ "CAST(id >= 20 AS DOUBLE) AS label FROM range(40)")
+ estimator = GBTClassifier(seed=2**33, maxDepth=2, maxIter=5, stepSize=0.2,
+ subsamplingRate=0.8,
featureSubsetStrategy="sqrt")
+ first = _predictions(estimator.fit(training), training)
+ assert first == _predictions(estimator.fit(training), training)
+ assert first[:10] == [0.0]*10 and first[-10:] == [1.0]*10
+
+
+def test_gbt_classifier_rejects_invalid_parameters_and_training_data(session):
+ GBTClassifier = _classifier()
+ training = _vectors(session,
+ "SELECT array(CAST(x AS DOUBLE)) AS xs, CAST(y AS DOUBLE) AS label,
1.0D AS weight "
+ "FROM VALUES (-1,0),(1,1) AS t(x,y)")
+ for options in
[dict(maxIter=0),dict(stepSize=0.0),dict(stepSize=1.1),dict(validationTol=-0.1),
+ dict(lossType="squared"),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):
+ GBTClassifier(**options).fit(training)
+ with pytest.raises(Exception):
+ GBTClassifier().setThresholds([1.0,1.0,1.0]).fit(training)
+ for frame in [training.drop("label"),training.drop("features"),
+
training.withColumn("label",F.lit(2.0)),training.withColumn("label",F.lit(-1.0)),
+
training.withColumn("label",F.lit(0.5)),training.withColumn("features",F.lit(1.0))]:
+ with pytest.raises(Exception):
+ GBTClassifier(maxIter=1).fit(frame)
+ with pytest.raises(Exception):
+
GBTClassifier(weightCol="weight").fit(training.withColumn("weight",F.lit(-1.0)))
+ with pytest.raises(Exception):
+ GBTClassifier(validationIndicatorCol="missing").fit(training)
diff --git a/python/tests/test_ml_e2e.py b/python/tests/test_ml_e2e.py
index ea24f115..682880e1 100644
--- a/python/tests/test_ml_e2e.py
+++ b/python/tests/test_ml_e2e.py
@@ -244,6 +244,7 @@ def _native_estimators():
from pyspark.ml.connect import (
DecisionTreeClassifier,
DecisionTreeRegressor,
+ GBTClassifier,
KMeans,
LinearRegression,
LinearSVC,
@@ -257,6 +258,7 @@ def _native_estimators():
ml = "org.apache.spark.ml."
return [
+ (GBTClassifier(maxIter=2), ml +
"classification.GBTClassificationModel"),
(DecisionTreeRegressor(), ml +
"regression.DecisionTreeRegressionModel"),
(DecisionTreeClassifier(), ml +
"classification.DecisionTreeClassificationModel"),
(KMeans(k=2, seed=1), ml + "clustering.KMeansModel"),
diff --git a/python/tests/test_ml_offline.py b/python/tests/test_ml_offline.py
index a018f7a2..330b95c4 100644
--- a/python/tests/test_ml_offline.py
+++ b/python/tests/test_ml_offline.py
@@ -361,6 +361,14 @@ _NATIVE_PARAMS = {
seed="int", leafCol="str", minWeightFractionPerNode="float",
weightCol="str", thresholds="float_list",
),
+ "GBTClassifier": 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", thresholds="float_list",
+ ),
"RandomForestClassifier": dict(
featuresCol="str", labelCol="str", predictionCol="str",
probabilityCol="str",
rawPredictionCol="str", maxDepth="int", maxBins="int",
minInstancesPerNode="int",
@@ -2590,3 +2598,78 @@ def
test_decision_tree_regressor_native_parameters_match_official_fixture(ml_moc
operator, params = _native_request(spark, service, estimator, models)
assert operator.name ==
"org.apache.spark.ml.regression.DecisionTreeRegressor"
assert params ==
pb2.MlParams.FromString(base64.b64decode(case["params_b64"]))
+
+
[email protected]("use_setters", [False, True], ids=["constructor",
"setters"])
+def test_gbt_classifier_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 GBTClassifier as exported
+ from pyspark.ml.connect.classification import GBTClassifier
+
+ assert exported is GBTClassifier is native.GBTClassifier
+ defaults = dict(featuresCol="features", labelCol="label",
predictionCol="prediction",
+ maxDepth=5, maxBins=32, minInstancesPerNode=1,
minInfoGain=0.0,
+ maxMemoryInMB=256, cacheNodeIds=False,
checkpointInterval=10, lossType="logistic",
+ maxIter=20, stepSize=0.1, seed=None, subsamplingRate=1.0,
impurity="variance",
+ featureSubsetStrategy="all", validationTol=0.01,
validationIndicatorCol=None,
+ leafCol="", minWeightFractionPerNode=0.0, weightCol=None)
+ signature = inspect.signature(GBTClassifier)
+ 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
+ for name in ("probabilityCol", "rawPredictionCol", "thresholds"):
+ with pytest.raises(TypeError, match="unexpected keyword argument"):
+ GBTClassifier(**{name: None})
+ assert not hasattr(GBTClassifier(), "setValidationTol")
+ fixture = json.loads((Path(__file__).resolve().parents[2] /
"tests/golden/gbt_classifier.json").read_text())
+ spark, service = ml_mock
+ models = []
+ for case in fixture["cases"]:
+ values = dict(featuresCol="input", labelCol="target",
predictionCol="class", maxDepth=3,
+ maxBins=16, minInstancesPerNode=2, minInfoGain=0.01,
maxMemoryInMB=64,
+ cacheNodeIds=True, checkpointInterval=-1,
lossType="logistic", maxIter=4,
+ stepSize=0.2, seed=case["seed"], subsamplingRate=0.75,
impurity="variance",
+ featureSubsetStrategy="all",
validationIndicatorCol="validation",
+ leafCol="leaves", minWeightFractionPerNode=0.1,
weightCol="weight")
+ if use_setters:
+ estimator = GBTClassifier(validationTol=0.05)
+ for name, value in values.items():
+ assert
getattr(estimator,"set"+name[0].upper()+name[1:])(value) is estimator
+ else:
+ estimator = GBTClassifier(**values, validationTol=0.05)
+ for name, value in
[("ProbabilityCol","probs"),("RawPredictionCol","margin"),("Thresholds",[0.25,0.75])]:
+ assert getattr(estimator,"set"+name)(value) is estimator
+ operator, params = _native_request(spark, service, estimator, models)
+ assert operator.name ==
"org.apache.spark.ml.classification.GBTClassifier"
+ assert params ==
pb2.MlParams.FromString(base64.b64decode(case["params_b64"]))
+ for value in [np.float64(0.05), 1, None]:
+ sent = _native_sent(spark, service,
GBTClassifier(validationTol=value), models)
+ assert sent["validationTol"][0] == ("null" if value is None else
"double")
+ with pytest.raises(TypeError, match="Invalid param value"):
+ GBTClassifier(validationTol="invalid")
+
+
[email protected]("param", ["probabilityCol", "rawPredictionCol"])
+def test_gbt_classifier_setter_only_columns_convert_as_pyspark(ml_mock, param):
+ from pyspark.ml.connect.classification import GBTClassifier
+
+ spark, service = ml_mock
+ models = []
+ setter = "set" + param[0].upper() + param[1:]
+ for value, expected in _NATIVE_CONVERTED["str"]:
+ estimator = GBTClassifier()
+ assert getattr(estimator, setter)(value) is estimator
+ assert _native_sent(spark, service, estimator, models) == {param:
expected}
+ estimator = GBTClassifier()
+ assert getattr(estimator, setter)(None) is estimator
+ assert _native_sent(spark, service, estimator, models)[param][0] == "null"
+ for value, message in _NATIVE_REJECTED["str"]:
+ with pytest.raises(TypeError) as error:
+ getattr(GBTClassifier(), setter)(value)
+ assert str(error.value) == f'Invalid param value given for param
"{param}". {message}'
diff --git a/scripts/capture_gbt_classifier_golden.py
b/scripts/capture_gbt_classifier_golden.py
new file mode 100644
index 00000000..ca1cf383
--- /dev/null
+++ b/scripts/capture_gbt_classifier_golden.py
@@ -0,0 +1,78 @@
+#!/usr/bin/env python3
+"""Capture GBTClassifier wire parameters using official PySpark 4.3.0."""
+
+import argparse
+import base64
+import json
+from pathlib import Path
+
+from pyspark.ml.classification import GBTClassifier
+from pyspark.ml.connect.serialize import serialize_ml_params
+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_classifier.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 = (
+ GBTClassifier(
+ featuresCol="input",
+ labelCol="target",
+ predictionCol="class",
+ 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="logistic",
+ maxIter=4,
+ stepSize=0.2,
+ validationTol=0.05,
+ validationIndicatorCol="validation",
+ )
+ .setProbabilityCol("probs")
+ .setRawPredictionCol("margin")
+ .setThresholds([0.25, 0.75])
+ )
+ 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.classification.GBTClassifier",
+ "cases": cases,
+ },
+ indent=2,
+ )
+ + "\n"
+ )
+ finally:
+ spark.stop()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/golden/gbt_classifier.json b/tests/golden/gbt_classifier.json
new file mode 100644
index 00000000..e6c4f468
--- /dev/null
+++ b/tests/golden/gbt_classifier.json
@@ -0,0 +1,29 @@
+{
+ "source": "apache/spark v4.3.0 pyspark.ml.classification.GBTClassifier",
+ "cases": [
+ {
+ "seed": 42,
+ "params_b64":
"ChIKDGNhY2hlTm9kZUlkcxICGAEKIQoSY2hlY2twb2ludEludGVydmFsEgsw////////////AQoeChVmZWF0dXJlU3Vic2V0U3RyYXRlZ3kSBWoDYWxsChYKC2ZlYXR1cmVzQ29sEgdqBWlucHV0ChYKCGltcHVyaXR5EgpqCHZhcmlhbmNlChQKCGxhYmVsQ29sEghqBnRhcmdldAoTCgdsZWFmQ29sEghqBmxlYXZlcwoWCghsb3NzVHlwZRIKaghsb2dpc3RpYwoNCgdtYXhCaW5zEgIwEAoOCghtYXhEZXB0aBICMAMKDQoHbWF4SXRlchICMAQKEwoNbWF4TWVtb3J5SW5NQhICMEAKGAoLbWluSW5mb0dhaW4SCVl7FK5H4XqEPwoZChNtaW5JbnN0YW5jZXNQZXJOb2RlEgIwAgolChhtaW5XZWlnaHRGcmFjdGlvblBlck5vZGUSCVm
[...]
+ },
+ {
+ "seed": -42,
+ "params_b64":
"ChIKDGNhY2hlTm9kZUlkcxICGAEKIQoSY2hlY2twb2ludEludGVydmFsEgsw////////////AQoeChVmZWF0dXJlU3Vic2V0U3RyYXRlZ3kSBWoDYWxsChYKC2ZlYXR1cmVzQ29sEgdqBWlucHV0ChYKCGltcHVyaXR5EgpqCHZhcmlhbmNlChQKCGxhYmVsQ29sEghqBnRhcmdldAoTCgdsZWFmQ29sEghqBmxlYXZlcwoWCghsb3NzVHlwZRIKaghsb2dpc3RpYwoNCgdtYXhCaW5zEgIwEAoOCghtYXhEZXB0aBICMAMKDQoHbWF4SXRlchICMAQKEwoNbWF4TWVtb3J5SW5NQhICMEAKGAoLbWluSW5mb0dhaW4SCVl7FK5H4XqEPwoZChNtaW5JbnN0YW5jZXNQZXJOb2RlEgIwAgolChhtaW5XZWlnaHRGcmFjdGlvblBlck5vZGUSCVm
[...]
+ },
+ {
+ "seed": 2147483647,
+ "params_b64":
"ChIKDGNhY2hlTm9kZUlkcxICGAEKIQoSY2hlY2twb2ludEludGVydmFsEgsw////////////AQoeChVmZWF0dXJlU3Vic2V0U3RyYXRlZ3kSBWoDYWxsChYKC2ZlYXR1cmVzQ29sEgdqBWlucHV0ChYKCGltcHVyaXR5EgpqCHZhcmlhbmNlChQKCGxhYmVsQ29sEghqBnRhcmdldAoTCgdsZWFmQ29sEghqBmxlYXZlcwoWCghsb3NzVHlwZRIKaghsb2dpc3RpYwoNCgdtYXhCaW5zEgIwEAoOCghtYXhEZXB0aBICMAMKDQoHbWF4SXRlchICMAQKEwoNbWF4TWVtb3J5SW5NQhICMEAKGAoLbWluSW5mb0dhaW4SCVl7FK5H4XqEPwoZChNtaW5JbnN0YW5jZXNQZXJOb2RlEgIwAgolChhtaW5XZWlnaHRGcmFjdGlvblBlck5vZGUSCVm
[...]
+ },
+ {
+ "seed": 2147483648,
+ "params_b64":
"ChIKDGNhY2hlTm9kZUlkcxICGAEKIQoSY2hlY2twb2ludEludGVydmFsEgsw////////////AQoeChVmZWF0dXJlU3Vic2V0U3RyYXRlZ3kSBWoDYWxsChYKC2ZlYXR1cmVzQ29sEgdqBWlucHV0ChYKCGltcHVyaXR5EgpqCHZhcmlhbmNlChQKCGxhYmVsQ29sEghqBnRhcmdldAoTCgdsZWFmQ29sEghqBmxlYXZlcwoWCghsb3NzVHlwZRIKaghsb2dpc3RpYwoNCgdtYXhCaW5zEgIwEAoOCghtYXhEZXB0aBICMAMKDQoHbWF4SXRlchICMAQKEwoNbWF4TWVtb3J5SW5NQhICMEAKGAoLbWluSW5mb0dhaW4SCVl7FK5H4XqEPwoZChNtaW5JbnN0YW5jZXNQZXJOb2RlEgIwAgolChhtaW5XZWlnaHRGcmFjdGlvblBlck5vZGUSCVm
[...]
+ },
+ {
+ "seed": -2147483648,
+ "params_b64":
"ChIKDGNhY2hlTm9kZUlkcxICGAEKIQoSY2hlY2twb2ludEludGVydmFsEgsw////////////AQoeChVmZWF0dXJlU3Vic2V0U3RyYXRlZ3kSBWoDYWxsChYKC2ZlYXR1cmVzQ29sEgdqBWlucHV0ChYKCGltcHVyaXR5EgpqCHZhcmlhbmNlChQKCGxhYmVsQ29sEghqBnRhcmdldAoTCgdsZWFmQ29sEghqBmxlYXZlcwoWCghsb3NzVHlwZRIKaghsb2dpc3RpYwoNCgdtYXhCaW5zEgIwEAoOCghtYXhEZXB0aBICMAMKDQoHbWF4SXRlchICMAQKEwoNbWF4TWVtb3J5SW5NQhICMEAKGAoLbWluSW5mb0dhaW4SCVl7FK5H4XqEPwoZChNtaW5JbnN0YW5jZXNQZXJOb2RlEgIwAgolChhtaW5XZWlnaHRGcmFjdGlvblBlck5vZGUSCVm
[...]
+ },
+ {
+ "seed": -2147483649,
+ "params_b64":
"ChIKDGNhY2hlTm9kZUlkcxICGAEKIQoSY2hlY2twb2ludEludGVydmFsEgsw////////////AQoeChVmZWF0dXJlU3Vic2V0U3RyYXRlZ3kSBWoDYWxsChYKC2ZlYXR1cmVzQ29sEgdqBWlucHV0ChYKCGltcHVyaXR5EgpqCHZhcmlhbmNlChQKCGxhYmVsQ29sEghqBnRhcmdldAoTCgdsZWFmQ29sEghqBmxlYXZlcwoWCghsb3NzVHlwZRIKaghsb2dpc3RpYwoNCgdtYXhCaW5zEgIwEAoOCghtYXhEZXB0aBICMAMKDQoHbWF4SXRlchICMAQKEwoNbWF4TWVtb3J5SW5NQhICMEAKGAoLbWluSW5mb0dhaW4SCVl7FK5H4XqEPwoZChNtaW5JbnN0YW5jZXNQZXJOb2RlEgIwAgolChhtaW5XZWlnaHRGcmFjdGlvblBlck5vZGUSCVm
[...]
+ }
+ ]
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]