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 f3bfab86 [SPARK-61453][CONNECT] Support native DecisionTreeRegressor
training and prediction
f3bfab86 is described below
commit f3bfab8630c8875bd4bd66dfa850cbecc4b3c913
Author: Ruifeng Zheng <[email protected]>
AuthorDate: Thu Nov 12 16:09:08 2026 +0900
[SPARK-61453][CONNECT] Support native DecisionTreeRegressor training and
prediction
### What changes were proposed in this pull request?
Add native Rust `DecisionTreeRegressor` and `DecisionTreeRegressionModel`,
plus `pyspark.ml.connect.regression.DecisionTreeRegressor` and its top-level
Connect export. The estimator fits Spark's JVM implementation through the
Connect ML command; fitted models transform DataFrames through their cached
server references.
Rust setters/getters cover all 16 Spark 4.3.0 constructor parameters,
including `varianceCol`, `weightCol` and `leafCol`. The Python constructor
mirrors the official keyword-only signature and uses the existing parameter
conversion and fit helpers. Models, clones and lazy transformed DataFrames
retain the cached model in its fitting session until their last owner is
dropped.
Add official PySpark wire fixtures, Rust and native Python tests,
compatibility documentation and the live Rust test target to CI.
### Why are the changes needed?
The native Rust and native Python Connect APIs currently lack
DecisionTreeRegressor. This makes decision-tree regression available through
the same native path as DecisionTreeClassifier and RandomForestRegressor.
### Does this PR introduce _any_ user-facing change?
Yes. The new estimator supports continuous numeric labels, ML vector
features, instance weights, custom column names, prediction output, optional
weighted variance within the predicted leaf and optional scalar double leaf
IDs. This addition covers fitting and DataFrame transformation; tree
inspection, feature importances, single-vector prediction and persistence are
outside its scope.
### How was this patch tested?
- 604 Rust library tests passed; all integration tests compile in release
mode, both with and without `wasm-udf`.
- Official PySpark 4.3.0 wire fixtures cover all 16 parameters and six seed
boundaries; the Rust golden test and four live Rust tests passed.
- The same five DecisionTreeRegressor behavior cases passed with official
PySpark and the rebuilt native Python extension. They exercise
constructor/setter equivalence, nonlinear continuous labels, scalar leaf IDs,
weighted leaf variances, weights, repeated fits, invalid parameters/data and
lazy model lifetime. Shared native ML tests cover server-model cleanup and
cross-session rejection.
- 1,931 native Python offline tests passed (8 skipped); seven selected
native live tests passed.
- Official Spark 4.3.0 Connect suite through the rebuilt Rust transport:
2,638 passed, 589 skipped across 87 files, zero unexpected failures.
- The 12-class public API introspection comparison found no unexpected
gaps. Rust formatting, Ruff 0.14.0 lint/format, vendored-path lint exclusions
and whitespace checks passed. Direct Clippy checks of the Rust library and new
integration targets passed. Workspace/binding Clippy has 52 existing error
sites, verified against the exact base source; this patch introduces none.
### 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 #515 from zhengruifeng/add-decision-tree-regressor.
Lead-authored-by: Ruifeng Zheng <[email protected]>
Co-authored-by: Hyukjin Kwon <[email protected]>
Signed-off-by: Hyukjin Kwon <[email protected]>
---
.github/workflows/build_python_connect.yml | 2 +-
crates/pyspark-rs/src/lib.rs | 1 +
crates/pyspark-rs/src/ml.rs | 188 +++++++-
crates/spark-connect/src/ml.rs | 482 +++++++++++++++++++++
.../tests/decision_tree_regressor_golden.rs | 42 ++
.../tests/e2e_decision_tree_regressor.rs | 218 ++++++++++
docs/compatibility.md | 22 +
python/pyspark/ml/connect/__init__.py | 7 +-
python/pyspark/ml/connect/regression.py | 4 +-
python/tests/test_dropin_e2e.py | 104 +++++
python/tests/test_ml_e2e.py | 2 +
python/tests/test_ml_offline.py | 49 +++
scripts/capture_decision_tree_regressor_golden.py | 69 +++
tests/golden/decision_tree_regressor.json | 29 ++
14 files changed, 1212 insertions(+), 7 deletions(-)
diff --git a/.github/workflows/build_python_connect.yml
b/.github/workflows/build_python_connect.yml
index 8e4dd469..0a68f0ea 100644
--- a/.github/workflows/build_python_connect.yml
+++ b/.github/workflows/build_python_connect.yml
@@ -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_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_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 24640522..4beb2d55 100644
--- a/crates/pyspark-rs/src/lib.rs
+++ b/crates/pyspark-rs/src/lib.rs
@@ -227,6 +227,7 @@ fn _pyspark(_py: Python<'_>, m: &Bound<'_, PyModule>) ->
PyResult<()> {
m.add_class::<ml::PyLinearRegression>()?;
m.add_class::<ml::PyDecisionTreeClassifier>()?;
m.add_class::<ml::PyRandomForestClassifier>()?;
+ m.add_class::<ml::PyDecisionTreeRegressor>()?;
m.add_class::<ml::PyRandomForestRegressor>()?;
m.add_class::<ml::PyKMeans>()?;
m.add_class::<ml::PyRegressionEvaluator>()?;
diff --git a/crates/pyspark-rs/src/ml.rs b/crates/pyspark-rs/src/ml.rs
index 8830b662..de337bf8 100644
--- a/crates/pyspark-rs/src/ml.rs
+++ b/crates/pyspark-rs/src/ml.rs
@@ -15,9 +15,9 @@ use pyo3::pyclass::boolean_struct::False;
use pyo3::types::{PyDict, PyTuple, PyType};
use pyo3::PyClass;
use spark_connect::ml::{
- BinaryClassificationEvaluator, CrossValidator, DecisionTreeClassifier,
Estimator, Evaluator,
- KMeans, LinearRegression, LinearSVC, LogisticRegression, MaxAbsScaler,
Model,
- MulticlassClassificationEvaluator, Params, Pipeline,
RandomForestClassifier,
+ BinaryClassificationEvaluator, CrossValidator, DecisionTreeClassifier,
DecisionTreeRegressor,
+ Estimator, Evaluator, KMeans, LinearRegression, LinearSVC,
LogisticRegression, MaxAbsScaler,
+ Model, MulticlassClassificationEvaluator, Params, Pipeline,
RandomForestClassifier,
RandomForestRegressor, RegressionEvaluator, StandardScaler, StringIndexer,
Transformer,
VectorAssembler,
};
@@ -1339,6 +1339,187 @@ impl PyRandomForestClassifier {
}
}
+/// Decision tree regressor fitted and cached by Spark Connect.
+#[pyclass(
+ name = "DecisionTreeRegressor",
+ module = "pyspark.ml.connect.regression"
+)]
+pub struct PyDecisionTreeRegressor {
+ inner: DecisionTreeRegressor,
+ unsendable: Vec<&'static str>,
+}
+
+const DECISION_TREE_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),
+ ("checkpointInterval", Kind::Int),
+ ("impurity", Kind::Str),
+ ("seed", Kind::Int),
+ ("varianceCol", Kind::Str),
+ ("leafCol", Kind::Str),
+ ("minWeightFractionPerNode", Kind::Float),
+ ("weightCol", Kind::Str),
+];
+
+#[pymethods]
+impl PyDecisionTreeRegressor {
+ #[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,
impurity='variance', seed=None, varianceCol=None, weightCol=None, leafCol='',
minWeightFractionPerNode=0.0)")]
+ fn new(args: &Bound<'_, PyTuple>, kwargs: Option<&Bound<'_, PyDict>>) ->
PyResult<Self> {
+ let mut this = Self {
+ inner: DecisionTreeRegressor::new(),
+ unsendable: Vec::new(),
+ };
+ init_params(
+ &mut this,
+ "DecisionTreeRegressor",
+ &[],
+ DECISION_TREE_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 = "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 = "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 = "setVarianceCol")]
+ fn set_variance_col<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "varianceCol", Kind::Str, value)
+ }
+
+ fn fit(slf: &Bound<'_, Self>, df: &PyDataFrame) -> PyResult<PyMLModel> {
+ fit_native(slf, df)
+ }
+}
/// Random forest regressor fitted and cached by Spark Connect.
#[pyclass(
name = "RandomForestRegressor",
@@ -1965,6 +2146,7 @@ native!(
PyLinearRegression => LinearRegression,
PyDecisionTreeClassifier => DecisionTreeClassifier,
PyRandomForestClassifier => RandomForestClassifier,
+ PyDecisionTreeRegressor => DecisionTreeRegressor,
PyRandomForestRegressor => RandomForestRegressor,
PyKMeans => KMeans,
PyRegressionEvaluator => RegressionEvaluator,
diff --git a/crates/spark-connect/src/ml.rs b/crates/spark-connect/src/ml.rs
index 9b663d15..3d527aee 100644
--- a/crates/spark-connect/src/ml.rs
+++ b/crates/spark-connect/src/ml.rs
@@ -2564,6 +2564,292 @@ impl Model for RandomForestClassificationModel {
}
}
+/// Decision tree regression using Spark's JVM implementation and ML vector
features.
+///
+/// Supports continuous numeric labels. Unset parameters use Spark's defaults.
Without a
+/// seed, tie-breaking uses Spark's default seed (the hash of the class name),
as with
+/// PySpark, so fits are reproducible either way; set a seed to change
tie-breaking.
+#[derive(Debug, Clone)]
+pub struct DecisionTreeRegressor {
+ operator: MlOperator,
+ params: Params,
+}
+
+impl DecisionTreeRegressor {
+ pub fn new() -> Self {
+ Self {
+ operator: MlOperator::new(
+ "org.apache.spark.ml.regression.DecisionTreeRegressor",
+ 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 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
+ }
+
+ /// Optional output column for the weighted label variance in the
predicted leaf.
+ pub fn set_variance_col(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("varianceCol", 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 measure: variance.
+ pub fn set_impurity(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("impurity", value);
+ self
+ }
+
+ /// Random seed for breaking ties between equally good splits.
+ pub fn set_seed(mut self, value: i64) -> Self {
+ self.params = self.params.set_param_int_narrow("seed", value);
+ self
+ }
+
+ /// Optional scalar leaf index output column; 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 prediction variance output column, if one is set.
+ pub fn variance_col(&self) -> Option<&str> {
+ self.params.string_opt("varianceCol")
+ }
+
+ /// 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 random seed, if one is set; else Spark's default seed applies.
+ pub fn seed(&self) -> Option<i64> {
+ self.params.long_opt("seed")
+ }
+
+ /// 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")
+ }
+
+ fn model_from_info(
+ &self,
+ info: proto::ml_command_result::MlOperatorInfo,
+ session: &SparkSession,
+ ) -> spark_connect_core::error::Result<DecisionTreeRegressionModel> {
+ let cached = CachedModel::from_info(&info, session,
"DecisionTreeRegressor")?;
+ Ok(DecisionTreeRegressionModel {
+ operator: MlOperator::with_uid(
+ "org.apache.spark.ml.regression.DecisionTreeRegressionModel",
+ info.uid.as_deref().unwrap_or(&self.operator.uid),
+ OperatorType::Model,
+ ),
+ params: self.params.clone(),
+ cached,
+ })
+ }
+}
+
+impl Default for DecisionTreeRegressor {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl Estimator for DecisionTreeRegressor {
+ 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 decision tree 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 DecisionTreeRegressionModel {
+ operator: MlOperator,
+ params: Params,
+ cached: CachedModel,
+}
+
+impl Transformer for DecisionTreeRegressionModel {
+ 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 DecisionTreeRegressionModel {
+ fn clone_box(&self) -> Box<dyn Model> {
+ Box::new(self.clone())
+ }
+}
/// Random forest regression using Spark's JVM implementation and ML vector
features.
///
/// Supports continuous numeric labels. Unset parameters use Spark's defaults.
Without a
@@ -4686,6 +4972,200 @@ mod tests {
.is_err());
assert!(model.clone_box().transform(&df).is_ok());
}
+ #[test]
+ fn
decision_tree_regressor_getters_follow_defaults_builders_and_mutable_params() {
+ let mut tree = DecisionTreeRegressor::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.seed(), None);
+ assert_eq!(tree.variance_col(), None);
+ assert_eq!(tree.weight_col(), None);
+ assert_eq!(tree.leaf_col(), "");
+ assert_eq!(tree.min_weight_fraction_per_node(), 0.0);
+ let mut built = DecisionTreeRegressor::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_seed(1_i64 << 33)
+ .set_variance_col("uncertainty")
+ .set_weight_col("weight")
+ .set_leaf_col("leaf")
+ .set_min_weight_fraction_per_node(0.1);
+ *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_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_string("varianceCol", "uncertainty");
+ assert_eq!(tree.variance_col(), Some("uncertainty"));
+ assert_eq!(built.variance_col(), tree.variance_col());
+ *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("leafCol",
"leaf");
+ assert_eq!(tree.leaf_col(), "leaf");
+ 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()
+ );
+ assert_eq!(tree.params().to_proto(), built.params().to_proto());
+ assert!(built
+ .operator_mut()
+ .uid
+ .starts_with("DecisionTreeRegressor_"));
+ }
+
+ #[test]
+ fn
decision_tree_regressor_validates_fitted_references_and_model_metadata() {
+ let session = offline_session();
+ let estimator =
DecisionTreeRegressor::default().set_prediction_col("value");
+ assert_eq!(
+ estimator.operator().name,
+ "org.apache.spark.ml.regression.DecisionTreeRegressor"
+ );
+ 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-decision-tree-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.DecisionTreeRegressionModel"
+ );
+ 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-decision-tree-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
random_forest_regressor_validates_fitted_references_and_model_metadata() {
let session = offline_session();
@@ -4798,6 +5278,8 @@ mod tests {
assert_eq!(sent(forest.params()), Some(expected.clone()));
let tree = DecisionTreeClassifier::new().set_seed(seed);
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 cv = CrossValidator::new().set_seed(seed);
assert_eq!(sent(cv.params()), Some(expected));
}
diff --git a/crates/spark-connect/tests/decision_tree_regressor_golden.rs
b/crates/spark-connect/tests/decision_tree_regressor_golden.rs
new file mode 100644
index 00000000..4c40b433
--- /dev/null
+++ b/crates/spark-connect/tests/decision_tree_regressor_golden.rs
@@ -0,0 +1,42 @@
+//! Match every DecisionTreeRegressor parameter and seed boundary to official
PySpark.
+use base64::{engine::general_purpose::STANDARD, Engine};
+use prost::Message;
+use spark_connect::ml::{DecisionTreeRegressor, Estimator};
+
+#[test]
+fn decision_tree_regressor_parameters_match_official_pyspark() {
+ let fixture: serde_json::Value = serde_json::from_str(include_str!(
+ "../../../tests/golden/decision_tree_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 = DecisionTreeRegressor::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_seed(seed)
+ .set_variance_col("uncertainty")
+ .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!(DecisionTreeRegressor::default()
+ .params()
+ .to_proto()
+ .params
+ .is_empty());
+}
diff --git a/crates/spark-connect/tests/e2e_decision_tree_regressor.rs
b/crates/spark-connect/tests/e2e_decision_tree_regressor.rs
new file mode 100644
index 00000000..ed740577
--- /dev/null
+++ b/crates/spark-connect/tests/e2e_decision_tree_regressor.rs
@@ -0,0 +1,218 @@
+//! Native decision tree regression tests. Set SPARK_REMOTE to run against a
live Connect server.
+use spark_connect::column::{col, lit_double};
+use spark_connect::expression::Expression;
+use spark_connect::ml::{DecisionTreeRegressor, Estimator};
+use spark_connect::{Column, DataFrame, SparkSession};
+
+fn session() -> Option<SparkSession> {
+ let remote = std::env::var("SPARK_REMOTE").ok()?;
+ Some(
+ SparkSession::builder()
+ .remote(&remote)
+ .get_or_create()
+ .unwrap(),
+ )
+}
+
+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 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() -> DecisionTreeRegressor {
+ DecisionTreeRegressor::new().set_seed(42)
+}
+
+#[test]
+fn
decision_tree_regressor_learns_nonlinear_labels_and_keeps_cached_models_alive()
{
+ let Some(s) = 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_variance_col("uncertainty")
+ .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_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]
+ );
+ assert_eq!(
+ predictions(output.clone(), "leaves"),
+ vec![0.0, 1.0, 1.0, 2.0]
+ );
+ assert_eq!(predictions(output, "uncertainty"), vec![0.0; 4]);
+ 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 decision_tree_regressor_weights_change_the_predicted_mean() {
+ let Some(s) = 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 decision_tree_regressor_rejects_invalid_parameters_and_data() {
+ let Some(s) = 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_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_impurity("gini"),
+ 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 decision_tree_regressor_reports_weighted_variance_in_each_leaf() {
+ let Some(s) = session() else {
+ return;
+ };
+ let data = vectors(&s,
+ "SELECT array(CAST(x AS DOUBLE)) AS xs, CAST(y AS DOUBLE) AS label,
CAST(w AS DOUBLE) AS weight
+ FROM VALUES (-2,-2,1),(-1,0,3),(1,4,1),(2,8,3) AS t(x,y,w)",
"features");
+ let held_out = vectors(
+ &s,
+ "SELECT id, array(CAST(x AS DOUBLE)) AS xs FROM VALUES
(0,-1.5),(1,1.5) AS t(id,x)",
+ "features",
+ );
+ let mut model = deterministic()
+ .set_max_depth(1)
+ .set_weight_col("weight")
+ .set_variance_col("uncertainty")
+ .set_leaf_col("leaf")
+ .fit(&data)
+ .unwrap();
+ let output = model.transform(&held_out).unwrap();
+ assert_eq!(predictions(output.clone(), "prediction"), vec![-0.5, 7.0]);
+ assert_eq!(predictions(output.clone(), "uncertainty"), vec![0.75, 3.0]);
+ assert_eq!(predictions(output, "leaf"), vec![0.0, 1.0]);
+ s.stop().unwrap();
+}
diff --git a/docs/compatibility.md b/docs/compatibility.md
index fe4ed992..1a66cdf3 100644
--- a/docs/compatibility.md
+++ b/docs/compatibility.md
@@ -209,6 +209,28 @@ 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 DecisionTreeRegressor
+
+`spark_connect::ml::DecisionTreeRegressor` fits Spark's JVM decision tree
+regressor through Connect with ML vector features and continuous numeric
labels.
+Rust builder setters/getters cover all 16 PySpark constructor parameters,
+including `set_variance_col`, `set_weight_col` and `set_leaf_col`. Unset
+parameters use Spark's defaults.
+
+The native Python binding is available as
+`pyspark.ml.connect.regression.DecisionTreeRegressor` and
+`pyspark.ml.connect.DecisionTreeRegressor`. Its keyword-only constructor
mirrors
+PySpark's parameter names and defaults. Mutating `setFeaturesCol`,
`setMaxDepth`,
+`setVarianceCol`, etc. methods return the estimator.
+
+Fitted models expose DataFrame `transform`, including predictions, optional
+weighted label variance in the predicted leaf and optional scalar double leaf
+indices. Variance is computed within the predicted leaf; it is not a confidence
+interval for the prediction. Models, clones and lazy transformed DataFrames
keep
+the cached server model alive in its fitting session until the last owner is
+dropped. Tree inspection, feature importances, single-vector prediction and
+persistence are outside this addition.
+
## Native DecisionTreeClassifier
`spark_connect::ml::DecisionTreeClassifier` trains Spark's JVM decision tree
diff --git a/python/pyspark/ml/connect/__init__.py
b/python/pyspark/ml/connect/__init__.py
index 0d662273..4cbb5bcf 100644
--- a/python/pyspark/ml/connect/__init__.py
+++ b/python/pyspark/ml/connect/__init__.py
@@ -17,7 +17,11 @@ from pyspark.ml.connect.classification import (
LogisticRegression,
RandomForestClassifier,
)
-from pyspark.ml.connect.regression import LinearRegression,
RandomForestRegressor
+from pyspark.ml.connect.regression import (
+ DecisionTreeRegressor,
+ LinearRegression,
+ RandomForestRegressor,
+)
from pyspark.ml.connect.clustering import KMeans
from pyspark.ml.connect.evaluation import (
RegressionEvaluator,
@@ -54,6 +58,7 @@ __all__ = [
"DecisionTreeClassifier",
"RandomForestClassifier",
"LinearRegression",
+ "DecisionTreeRegressor",
"RandomForestRegressor",
"KMeans",
"RegressionEvaluator",
diff --git a/python/pyspark/ml/connect/regression.py
b/python/pyspark/ml/connect/regression.py
index 26c21f91..c05b998d 100644
--- a/python/pyspark/ml/connect/regression.py
+++ b/python/pyspark/ml/connect/regression.py
@@ -1,4 +1,4 @@
"""Native regression estimators backed by Spark Connect's JVM ML API."""
-from pyspark._pyspark import LinearRegression, RandomForestRegressor
+from pyspark._pyspark import DecisionTreeRegressor, LinearRegression,
RandomForestRegressor
-__all__ = ["LinearRegression", "RandomForestRegressor"]
+__all__ = ["DecisionTreeRegressor", "LinearRegression",
"RandomForestRegressor"]
diff --git a/python/tests/test_dropin_e2e.py b/python/tests/test_dropin_e2e.py
index e666d1be..e94dfd61 100644
--- a/python/tests/test_dropin_e2e.py
+++ b/python/tests/test_dropin_e2e.py
@@ -5443,6 +5443,110 @@ def
test_decision_tree_classifier_rejects_invalid_parameters_and_training_data(s
DecisionTreeClassifier().fit(training.withColumn("features",F.array(F.lit(1.0))))
+def _decision_tree_regressor():
+ try:
+ from pyspark.ml.connect.regression import DecisionTreeRegressor
+ except ImportError:
+ from pyspark.ml.regression import DecisionTreeRegressor
+ return DecisionTreeRegressor
+
+
[email protected]("use_setters", [False, True], ids=["constructor",
"setters"])
+def
test_decision_tree_regressor_learns_nonlinear_values_and_retains_lazy_predictions(session,
use_setters):
+ DecisionTreeRegressor = _decision_tree_regressor()
+ training = _forest_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 = _forest_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, checkpointInterval=-1,
+ impurity="variance", seed=42,
+ leafCol="leaves", varianceCol="uncertainty",
minWeightFractionPerNode=0.0,
+ weightCol="weight")
+ if use_setters:
+ estimator = DecisionTreeRegressor()
+ for name, value in options.items():
+ assert getattr(estimator, "set" + name[0].upper() +
name[1:])(value) is estimator
+ else:
+ estimator = DecisionTreeRegressor(**options)
+ 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 _forest_predictions(first, held_out, "value") == expected
+ assert _forest_predictions(second, held_out, "value") == [6.0, 15.5, 15.5,
6.0]
+ assert _forest_predictions(estimator.fit(training), held_out, "value") ==
expected
+ output = first.transform(held_out).orderBy("id")
+ assert output.schema["leaves"].dataType == DoubleType()
+ assert output.schema["uncertainty"].dataType == DoubleType()
+ assert [r.leaves for r in output.select("leaves").collect()] ==
[0.0,1.0,1.0,2.0]
+ assert [r.uncertainty for r in output.select("uncertainty").collect()] ==
[0.0]*4
+ delayed = first.transform(held_out).select("id", "value")
+ del first
+ import gc
+ gc.collect()
+ assert [r.value for r in delayed.orderBy("id").collect()] == expected
+
+
+def test_decision_tree_regressor_instance_weights_change_the_mean(session):
+ DecisionTreeRegressor = _decision_tree_regressor()
+ training = _forest_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)")
+ options = dict(seed=42, maxDepth=0)
+ plain = DecisionTreeRegressor(**options).fit(training)
+ weighted = DecisionTreeRegressor(**options,
weightCol="weight").fit(training)
+ assert _forest_predictions(plain, training) == [1.0]*4
+ assert _forest_predictions(weighted, training) == [7.0]*4
+ assert "variance" not in plain.transform(training).columns
+ assert "leaf" not in plain.transform(training).columns
+
+
+def test_decision_tree_regressor_rejects_invalid_parameters_and_data(session):
+ DecisionTreeRegressor = _decision_tree_regressor()
+ training = _forest_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(maxDepth=31),dict(maxBins=1),
+
dict(minInstancesPerNode=0),dict(minInfoGain=-1.0),dict(maxMemoryInMB=-1),
+ dict(checkpointInterval=0),dict(impurity="gini"),
+
+ dict(minWeightFractionPerNode=0.5)]:
+ with pytest.raises(Exception):
+ DecisionTreeRegressor(**options).fit(training)
+ with pytest.raises(Exception):
+ DecisionTreeRegressor().fit(training.drop("label"))
+ with pytest.raises(Exception):
+
DecisionTreeRegressor().fit(training.withColumn("label",F.lit(float("nan"))))
+ with pytest.raises(Exception):
+
DecisionTreeRegressor(weightCol="weight").fit(training.withColumn("weight",F.lit(-1.0)))
+ with pytest.raises(Exception):
+ DecisionTreeRegressor().fit(training.withColumn("features",F.lit(1.0)))
+
+
+
+
+def
test_decision_tree_regressor_reports_weighted_variance_in_each_leaf(session):
+ DecisionTreeRegressor = _decision_tree_regressor()
+ training = _forest_vectors(session,
+ "SELECT array(CAST(x AS DOUBLE)) AS xs, CAST(y AS DOUBLE) AS label, "
+ "CAST(w AS DOUBLE) AS weight "
+ "FROM VALUES (-2,-2,1),(-1,0,3),(1,4,1),(2,8,3) AS t(x,y,w)")
+ held_out = _forest_vectors(session,
+ "SELECT id, array(CAST(x AS DOUBLE)) AS xs "
+ "FROM VALUES (0,-1.5),(1,1.5) AS t(id,x)")
+ estimator = DecisionTreeRegressor(seed=2**33, maxDepth=1,
weightCol="weight",
+ varianceCol="uncertainty",
leafCol="leaf")
+ first = estimator.fit(training)
+ rows = first.transform(held_out).orderBy("id").select("prediction",
"uncertainty", "leaf").collect()
+ assert [r.prediction for r in rows] == [-0.5,7.0]
+ assert [r.uncertainty for r in rows] == [0.75,3.0]
+ assert [r.leaf for r in rows] == [0.0,1.0]
+ assert _forest_predictions(estimator.fit(training), held_out) == [-0.5,7.0]
+
+
def test_binary_subclasses_are_sent_as_the_bytes_of_pyspark(session):
class Bytes(bytes):
def __bytes__(self):
diff --git a/python/tests/test_ml_e2e.py b/python/tests/test_ml_e2e.py
index 5623d330..e2d75507 100644
--- a/python/tests/test_ml_e2e.py
+++ b/python/tests/test_ml_e2e.py
@@ -243,6 +243,7 @@ def _native_estimators():
# caches for its fit, and data that it fits.
from pyspark.ml.connect import (
DecisionTreeClassifier,
+ DecisionTreeRegressor,
KMeans,
LinearRegression,
LinearSVC,
@@ -256,6 +257,7 @@ def _native_estimators():
ml = "org.apache.spark.ml."
return [
+ (DecisionTreeRegressor(), ml +
"regression.DecisionTreeRegressionModel"),
(DecisionTreeClassifier(), ml +
"classification.DecisionTreeClassificationModel"),
(KMeans(k=2, seed=1), ml + "clustering.KMeansModel"),
(LinearSVC(maxIter=2), ml + "classification.LinearSVCModel"),
diff --git a/python/tests/test_ml_offline.py b/python/tests/test_ml_offline.py
index ced21483..516f1516 100644
--- a/python/tests/test_ml_offline.py
+++ b/python/tests/test_ml_offline.py
@@ -368,6 +368,13 @@ _NATIVE_PARAMS = {
seed="int", subsamplingRate="float", leafCol="str",
minWeightFractionPerNode="float",
weightCol="str", bootstrap="bool", thresholds="float_list",
),
+ "DecisionTreeRegressor": dict(
+ featuresCol="str", labelCol="str", predictionCol="str", maxDepth="int",
+ maxBins="int", minInstancesPerNode="int", minInfoGain="float",
maxMemoryInMB="int",
+ cacheNodeIds="bool", checkpointInterval="int", impurity="str",
+ seed="int", varianceCol="str", leafCol="str",
+ minWeightFractionPerNode="float", weightCol="str",
+ ),
"RandomForestRegressor": dict(
featuresCol="str", labelCol="str", predictionCol="str", maxDepth="int",
maxBins="int", minInstancesPerNode="int", minInfoGain="float",
maxMemoryInMB="int",
@@ -2496,3 +2503,45 @@ def
test_decision_tree_classifier_native_parameters_match_official_fixture(ml_mo
operator, params = _native_request(spark, service, estimator, models)
assert operator.name ==
"org.apache.spark.ml.classification.DecisionTreeClassifier"
assert params ==
pb2.MlParams.FromString(base64.b64decode(case["params_b64"]))
+
+
[email protected]("use_setters", [False, True], ids=["constructor",
"setters"])
+def
test_decision_tree_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 DecisionTreeRegressor as exported
+ from pyspark.ml.connect.regression import DecisionTreeRegressor
+
+ assert exported is DecisionTreeRegressor is native.DecisionTreeRegressor
+ defaults = dict(featuresCol="features", labelCol="label",
predictionCol="prediction",
+ maxDepth=5, maxBins=32, minInstancesPerNode=1,
minInfoGain=0.0,
+ maxMemoryInMB=256, cacheNodeIds=False,
checkpointInterval=10,
+ impurity="variance", seed=None, varianceCol=None,
weightCol=None,
+ leafCol="", minWeightFractionPerNode=0.0)
+ signature = inspect.signature(DecisionTreeRegressor)
+ 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
+ fixture = json.loads((Path(__file__).resolve().parents[2] /
"tests/golden/decision_tree_regressor.json").read_text())
+ spark, service = ml_mock
+ models = []
+ 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, checkpointInterval=-1,
impurity="variance",
+ seed=case["seed"], varianceCol="uncertainty",
weightCol="weight",
+ leafCol="leaves", minWeightFractionPerNode=0.1)
+ if use_setters:
+ estimator = DecisionTreeRegressor()
+ for name, value in values.items():
+ assert
getattr(estimator,"set"+name[0].upper()+name[1:])(value) is estimator
+ else:
+ estimator = DecisionTreeRegressor(**values)
+ 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"]))
diff --git a/scripts/capture_decision_tree_regressor_golden.py
b/scripts/capture_decision_tree_regressor_golden.py
new file mode 100644
index 00000000..6b7987d9
--- /dev/null
+++ b/scripts/capture_decision_tree_regressor_golden.py
@@ -0,0 +1,69 @@
+#!/usr/bin/env python3
+"""Capture DecisionTreeRegressor 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 DecisionTreeRegressor
+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/decision_tree_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 = DecisionTreeRegressor(
+ featuresCol="input",
+ labelCol="target",
+ predictionCol="value",
+ maxDepth=3,
+ maxBins=16,
+ minInstancesPerNode=2,
+ minInfoGain=0.01,
+ maxMemoryInMB=64,
+ cacheNodeIds=True,
+ checkpointInterval=-1,
+ impurity="variance",
+ seed=seed,
+ varianceCol="uncertainty",
+ leafCol="leaves",
+ minWeightFractionPerNode=0.1,
+ weightCol="weight",
+ )
+ 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.DecisionTreeRegressor",
+ "cases": cases,
+ },
+ indent=2,
+ )
+ + "\n"
+ )
+ finally:
+ spark.stop()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/golden/decision_tree_regressor.json
b/tests/golden/decision_tree_regressor.json
new file mode 100644
index 00000000..23427a93
--- /dev/null
+++ b/tests/golden/decision_tree_regressor.json
@@ -0,0 +1,29 @@
+{
+ "source": "apache/spark v4.3.0 pyspark.ml.regression.DecisionTreeRegressor",
+ "cases": [
+ {
+ "seed": 42,
+ "params_b64":
"ChIKDGNhY2hlTm9kZUlkcxICGAEKIQoSY2hlY2twb2ludEludGVydmFsEgsw////////////AQoWCgtmZWF0dXJlc0NvbBIHagVpbnB1dAoWCghpbXB1cml0eRIKagh2YXJpYW5jZQoUCghsYWJlbENvbBIIagZ0YXJnZXQKEwoHbGVhZkNvbBIIagZsZWF2ZXMKDQoHbWF4QmlucxICMBAKDgoIbWF4RGVwdGgSAjADChMKDW1heE1lbW9yeUluTUISAjBAChgKC21pbkluZm9HYWluEglZexSuR+F6hD8KGQoTbWluSW5zdGFuY2VzUGVyTm9kZRICMAIKJQoYbWluV2VpZ2h0RnJhY3Rpb25QZXJOb2RlEglZmpmZmZmZuT8KGAoNcHJlZGljdGlvbkNvbBIHagV2YWx1ZQoKCgRzZWVkEgIwKgocCgt2YXJpYW5jZUNvbBINagt1bmNlcnR
[...]
+ },
+ {
+ "seed": -42,
+ "params_b64":
"ChIKDGNhY2hlTm9kZUlkcxICGAEKIQoSY2hlY2twb2ludEludGVydmFsEgsw////////////AQoWCgtmZWF0dXJlc0NvbBIHagVpbnB1dAoWCghpbXB1cml0eRIKagh2YXJpYW5jZQoUCghsYWJlbENvbBIIagZ0YXJnZXQKEwoHbGVhZkNvbBIIagZsZWF2ZXMKDQoHbWF4QmlucxICMBAKDgoIbWF4RGVwdGgSAjADChMKDW1heE1lbW9yeUluTUISAjBAChgKC21pbkluZm9HYWluEglZexSuR+F6hD8KGQoTbWluSW5zdGFuY2VzUGVyTm9kZRICMAIKJQoYbWluV2VpZ2h0RnJhY3Rpb25QZXJOb2RlEglZmpmZmZmZuT8KGAoNcHJlZGljdGlvbkNvbBIHagV2YWx1ZQoTCgRzZWVkEgsw1v//////////AQocCgt2YXJpYW5jZUNvbBI
[...]
+ },
+ {
+ "seed": 2147483647,
+ "params_b64":
"ChIKDGNhY2hlTm9kZUlkcxICGAEKIQoSY2hlY2twb2ludEludGVydmFsEgsw////////////AQoWCgtmZWF0dXJlc0NvbBIHagVpbnB1dAoWCghpbXB1cml0eRIKagh2YXJpYW5jZQoUCghsYWJlbENvbBIIagZ0YXJnZXQKEwoHbGVhZkNvbBIIagZsZWF2ZXMKDQoHbWF4QmlucxICMBAKDgoIbWF4RGVwdGgSAjADChMKDW1heE1lbW9yeUluTUISAjBAChgKC21pbkluZm9HYWluEglZexSuR+F6hD8KGQoTbWluSW5zdGFuY2VzUGVyTm9kZRICMAIKJQoYbWluV2VpZ2h0RnJhY3Rpb25QZXJOb2RlEglZmpmZmZmZuT8KGAoNcHJlZGljdGlvbkNvbBIHagV2YWx1ZQoOCgRzZWVkEgYw/////wcKHAoLdmFyaWFuY2VDb2wSDWoLdW5
[...]
+ },
+ {
+ "seed": 2147483648,
+ "params_b64":
"ChIKDGNhY2hlTm9kZUlkcxICGAEKIQoSY2hlY2twb2ludEludGVydmFsEgsw////////////AQoWCgtmZWF0dXJlc0NvbBIHagVpbnB1dAoWCghpbXB1cml0eRIKagh2YXJpYW5jZQoUCghsYWJlbENvbBIIagZ0YXJnZXQKEwoHbGVhZkNvbBIIagZsZWF2ZXMKDQoHbWF4QmlucxICMBAKDgoIbWF4RGVwdGgSAjADChMKDW1heE1lbW9yeUluTUISAjBAChgKC21pbkluZm9HYWluEglZexSuR+F6hD8KGQoTbWluSW5zdGFuY2VzUGVyTm9kZRICMAIKJQoYbWluV2VpZ2h0RnJhY3Rpb25QZXJOb2RlEglZmpmZmZmZuT8KGAoNcHJlZGljdGlvbkNvbBIHagV2YWx1ZQoOCgRzZWVkEgY4gICAgAgKHAoLdmFyaWFuY2VDb2wSDWoLdW5
[...]
+ },
+ {
+ "seed": -2147483648,
+ "params_b64":
"ChIKDGNhY2hlTm9kZUlkcxICGAEKIQoSY2hlY2twb2ludEludGVydmFsEgsw////////////AQoWCgtmZWF0dXJlc0NvbBIHagVpbnB1dAoWCghpbXB1cml0eRIKagh2YXJpYW5jZQoUCghsYWJlbENvbBIIagZ0YXJnZXQKEwoHbGVhZkNvbBIIagZsZWF2ZXMKDQoHbWF4QmlucxICMBAKDgoIbWF4RGVwdGgSAjADChMKDW1heE1lbW9yeUluTUISAjBAChgKC21pbkluZm9HYWluEglZexSuR+F6hD8KGQoTbWluSW5zdGFuY2VzUGVyTm9kZRICMAIKJQoYbWluV2VpZ2h0RnJhY3Rpb25QZXJOb2RlEglZmpmZmZmZuT8KGAoNcHJlZGljdGlvbkNvbBIHagV2YWx1ZQoTCgRzZWVkEgswgICAgPj/////AQocCgt2YXJpYW5jZUNvbBI
[...]
+ },
+ {
+ "seed": -2147483649,
+ "params_b64":
"ChIKDGNhY2hlTm9kZUlkcxICGAEKIQoSY2hlY2twb2ludEludGVydmFsEgsw////////////AQoWCgtmZWF0dXJlc0NvbBIHagVpbnB1dAoWCghpbXB1cml0eRIKagh2YXJpYW5jZQoUCghsYWJlbENvbBIIagZ0YXJnZXQKEwoHbGVhZkNvbBIIagZsZWF2ZXMKDQoHbWF4QmlucxICMBAKDgoIbWF4RGVwdGgSAjADChMKDW1heE1lbW9yeUluTUISAjBAChgKC21pbkluZm9HYWluEglZexSuR+F6hD8KGQoTbWluSW5zdGFuY2VzUGVyTm9kZRICMAIKJQoYbWluV2VpZ2h0RnJhY3Rpb25QZXJOb2RlEglZmpmZmZmZuT8KGAoNcHJlZGljdGlvbkNvbBIHagV2YWx1ZQoTCgRzZWVkEgs4//////f/////AQocCgt2YXJpYW5jZUNvbBI
[...]
+ }
+ ]
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]