This is an automated email from the ASF dual-hosted git repository.
zhengruifeng 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 1538e78e [SPARK-61428][CONNECT] Support native RandomForestRegressor
training and prediction
1538e78e is described below
commit 1538e78e06ec47489312bf31ee48156f3f4cea88
Author: Ruifeng Zheng <[email protected]>
AuthorDate: Wed Nov 11 17:59:02 2026 +0800
[SPARK-61428][CONNECT] Support native RandomForestRegressor training and
prediction
### What changes were proposed in this pull request?
Add native Rust `RandomForestRegressor` and `RandomForestRegressionModel`
so users can train a random forest and predict numeric labels through Spark
Connect. Fits use the JVM estimator and its session-scoped cached model.
Transforms produce predictions and optional per-tree leaf indices; model clones
and lazy transformed DataFrames share ownership of the cached model.
Expose all 19 official PySpark constructor parameters through Rust
setters/getters and the native Python estimator at
`pyspark.ml.connect.regression.RandomForestRegressor` and
`pyspark.ml.connect.RandomForestRegressor`. The Python binding uses the shared
parameter conversion and interruptible-fit helpers. Add official wire fixtures,
live tests, CI selection and compatibility documentation.
JIRA: https://issues.apache.org/jira/browse/SPARK-61428
### Why are the changes needed?
The native Rust API has a random forest classifier but lacks its regression
counterpart. This adds nonlinear regression with numeric labels, instance
weighting and configurable sampling using the existing model-cache
infrastructure.
### Does this PR introduce _any_ user-facing change?
Yes. Rust and native Python users can fit random forest regressors and
transform DataFrames. Tests learn a nonlinear pattern with negative and
fractional labels and predict unseen rows; fitting shifted labels changes the
predictions. Instance weights change a depth-zero forest's prediction from the
unweighted mean of 1 to the weighted mean of 7.
This native addition exposes fit and DataFrame transform. Tree inspection,
feature importances, single-vector prediction and persistence remain outside
its API; these limits are documented.
### How was this patch tested?
- Four live Rust tests against Spark 4.3.0: nonlinear predictions and
separate fits, repeated seeded fits, cached references and clone/lazy
ownership, cross-session rejection, leaf output, weighted means,
bootstrap/feature sampling and invalid parameters/data.
- Five new Python cases passed with official PySpark and the built
Rust-backed Python client. Two existing native model tests also passed with the
regressor included, exercising cache release and session behavior. Extension
origin and native estimator/session identity were explicitly verified.
- Official PySpark wire fixtures for all 19 parameters and six integer seed
boundaries, Rust getter checks and Python constructor/setter golden
comparisons. Shared Python parameter conversion, omission/null and error cases
include the new estimator.
- 597 Rust library tests; 108 Python ML offline tests; 1,819 Python drop-in
offline tests passed (8 existing skips). All Rust integration targets compile
with and without `wasm-udf`. Formatting and the new Rust targets' Clippy check
pass. Introspection found no missing public names across the 12 checked core
classes; the estimator's 19 constructor names/defaults match the reference.
- Official Spark 4.3.0 Connect single-node suite through the Rust
transport: all 87 files passed; 2,638 tests passed, 589 skipped, zero
unexpected failures (the same three local-cluster exclusions used by CI).
- Workspace/Python-binding Clippy reports existing errors: comparison with
unchanged master found 54 matching error sites and zero new sites.
### 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 #505 from zhengruifeng/add-random-forest-regressor.
Authored-by: Ruifeng Zheng <[email protected]>
Signed-off-by: Ruifeng Zheng <[email protected]>
---
.github/workflows/build_python_connect.yml | 2 +-
crates/pyspark-rs/src/lib.rs | 1 +
crates/pyspark-rs/src/ml.rs | 214 +++++++++++-
crates/spark-connect/src/ml.rs | 389 +++++++++++++++++++++
.../tests/e2e_random_forest_regressor.rs | 243 +++++++++++++
.../tests/random_forest_regressor_golden.rs | 79 +++++
docs/compatibility.md | 17 +
python/pyspark/ml/connect/__init__.py | 3 +-
python/pyspark/ml/connect/regression.py | 4 +-
python/tests/test_dropin_e2e.py | 93 +++++
python/tests/test_ml_e2e.py | 2 +
python/tests/test_ml_offline.py | 49 +++
scripts/capture_random_forest_regressor_golden.py | 72 ++++
tests/golden/random_forest_regressor.json | 29 ++
14 files changed, 1191 insertions(+), 6 deletions(-)
diff --git a/.github/workflows/build_python_connect.yml
b/.github/workflows/build_python_connect.yml
index 8d2ba74f..9d41edd8 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_random_forest --test
e2e_integration \
+ --test e2e_coverage --test e2e_linear_svc --test
e2e_linear_regression --test e2e_kmeans --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 ec22760a..611ab219 100644
--- a/crates/pyspark-rs/src/lib.rs
+++ b/crates/pyspark-rs/src/lib.rs
@@ -225,6 +225,7 @@ fn _pyspark(_py: Python<'_>, m: &Bound<'_, PyModule>) ->
PyResult<()> {
m.add_class::<ml::PyLinearSVC>()?;
m.add_class::<ml::PyLinearRegression>()?;
m.add_class::<ml::PyRandomForestClassifier>()?;
+ m.add_class::<ml::PyRandomForestRegressor>()?;
m.add_class::<ml::PyKMeans>()?;
m.add_class::<ml::PyRegressionEvaluator>()?;
m.add_class::<ml::PyBinaryClassificationEvaluator>()?;
diff --git a/crates/pyspark-rs/src/ml.rs b/crates/pyspark-rs/src/ml.rs
index e4ef1002..0f806f51 100644
--- a/crates/pyspark-rs/src/ml.rs
+++ b/crates/pyspark-rs/src/ml.rs
@@ -17,8 +17,8 @@ use pyo3::PyClass;
use spark_connect::ml::{
BinaryClassificationEvaluator, CrossValidator, Estimator, Evaluator,
KMeans, LinearRegression,
LinearSVC, LogisticRegression, MaxAbsScaler, Model,
MulticlassClassificationEvaluator, Params,
- Pipeline, RandomForestClassifier, RegressionEvaluator, StandardScaler,
StringIndexer,
- Transformer, VectorAssembler,
+ Pipeline, RandomForestClassifier, RandomForestRegressor,
RegressionEvaluator, StandardScaler,
+ StringIndexer, Transformer, VectorAssembler,
};
use spark_connect::DataFrame;
@@ -1106,6 +1106,215 @@ impl PyRandomForestClassifier {
}
}
+/// Random forest regressor fitted and cached by Spark Connect.
+#[pyclass(
+ name = "RandomForestRegressor",
+ module = "pyspark.ml.connect.regression"
+)]
+pub struct PyRandomForestRegressor {
+ inner: RandomForestRegressor,
+ unsendable: Vec<&'static str>,
+}
+
+const RANDOM_FOREST_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),
+ ("subsamplingRate", Kind::Float),
+ ("seed", Kind::Int),
+ ("numTrees", Kind::Int),
+ ("featureSubsetStrategy", Kind::Str),
+ ("leafCol", Kind::Str),
+ ("minWeightFractionPerNode", Kind::Float),
+ ("weightCol", Kind::Str),
+ ("bootstrap", Kind::Bool),
+];
+
+#[pymethods]
+impl PyRandomForestRegressor {
+ #[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', subsamplingRate=1.0, seed=None, numTrees=20,
featureSubsetStrategy='auto', leafCol='', minWeightFractionPerNode=0.0,
weightCol=None, bootstrap=True)")]
+ fn new(args: &Bound<'_, PyTuple>, kwargs: Option<&Bound<'_, PyDict>>) ->
PyResult<Self> {
+ let mut this = Self {
+ inner: RandomForestRegressor::new(),
+ unsendable: Vec::new(),
+ };
+ init_params(
+ &mut this,
+ "RandomForestRegressor",
+ &[],
+ RANDOM_FOREST_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 = "setNumTrees")]
+ fn set_num_trees<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "numTrees", Kind::Int, 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 = "setBootstrap")]
+ fn set_bootstrap<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "bootstrap", Kind::Bool, value)
+ }
+
+ fn fit(slf: &Bound<'_, Self>, df: &PyDataFrame) -> PyResult<PyMLModel> {
+ fit_native(slf, df)
+ }
+}
+
/// K-means clustering backed by Spark Connect's JVM ML API.
#[pyclass(name = "KMeans", module = "pyspark.ml.connect.clustering")]
pub struct PyKMeans {
@@ -1515,6 +1724,7 @@ native!(
PyLinearSVC => LinearSVC,
PyLinearRegression => LinearRegression,
PyRandomForestClassifier => RandomForestClassifier,
+ PyRandomForestRegressor => RandomForestRegressor,
PyKMeans => KMeans,
PyRegressionEvaluator => RegressionEvaluator,
PyBinaryClassificationEvaluator => BinaryClassificationEvaluator,
diff --git a/crates/spark-connect/src/ml.rs b/crates/spark-connect/src/ml.rs
index 895529ab..0b946426 100644
--- a/crates/spark-connect/src/ml.rs
+++ b/crates/spark-connect/src/ml.rs
@@ -2232,6 +2232,326 @@ impl Model for RandomForestClassificationModel {
}
}
+/// Random forest regression using Spark's JVM implementation and ML vector
features.
+///
+/// Supports continuous numeric labels. Unset parameters use Spark's defaults.
Without a
+/// seed, the sampling uses Spark's default seed (the hash of the class name),
as with
+/// PySpark, so fits are reproducible either way; set a seed to draw other
samples.
+#[derive(Debug, Clone)]
+pub struct RandomForestRegressor {
+ operator: MlOperator,
+ params: Params,
+}
+
+impl RandomForestRegressor {
+ pub fn new() -> Self {
+ Self {
+ operator: MlOperator::new(
+ "org.apache.spark.ml.regression.RandomForestRegressor",
+ 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
+ }
+
+ /// 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
+ }
+
+ /// Number of trees in the forest; must be positive.
+ pub fn set_num_trees(mut self, value: i32) -> Self {
+ self.params = self.params.set_param_int32("numTrees", 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 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
+ }
+
+ /// Whether each tree samples training instances with replacement.
+ pub fn set_bootstrap(mut self, value: bool) -> Self {
+ self.params = self.params.set_param_bool("bootstrap", value);
+ self
+ }
+
+ /// The feature vector column (default: "features").
+ pub fn feature_col(&self) -> &str {
+ self.params.string_or("featuresCol", "features")
+ }
+
+ /// The label column (default: "label").
+ pub fn label_col(&self) -> &str {
+ self.params.string_or("labelCol", "label")
+ }
+
+ /// The regression prediction output column (default: "prediction").
+ pub fn prediction_col(&self) -> &str {
+ self.params.string_or("predictionCol", "prediction")
+ }
+
+ /// The maximum tree depth (default: 5).
+ pub fn max_depth(&self) -> i32 {
+ self.params.int_or("maxDepth", 5)
+ }
+
+ /// The maximum number of bins for continuous features (default: 32).
+ pub fn max_bins(&self) -> i32 {
+ self.params.int_or("maxBins", 32)
+ }
+
+ /// The minimum number of training instances in each child node (default:
1).
+ pub fn min_instances_per_node(&self) -> i32 {
+ self.params.int_or("minInstancesPerNode", 1)
+ }
+
+ /// The minimum information gain for a split (default: 0).
+ pub fn min_info_gain(&self) -> f64 {
+ self.params.double_or("minInfoGain", 0.0)
+ }
+
+ /// The maximum memory in MB for histogram aggregation (default: 256).
+ pub fn max_memory_in_mb(&self) -> i32 {
+ self.params.int_or("maxMemoryInMB", 256)
+ }
+
+ /// Whether to cache node IDs for training instances (default: false).
+ pub fn cache_node_ids(&self) -> bool {
+ self.params.bool_or("cacheNodeIds", false)
+ }
+
+ /// The node ID cache checkpoint interval (default: 10).
+ pub fn checkpoint_interval(&self) -> i32 {
+ self.params.int_or("checkpointInterval", 10)
+ }
+
+ /// The impurity measure (default: "variance").
+ pub fn impurity(&self) -> &str {
+ self.params.string_or("impurity", "variance")
+ }
+
+ /// The number of trees (default: 20).
+ pub fn num_trees(&self) -> i32 {
+ self.params.int_or("numTrees", 20)
+ }
+
+ /// The feature subset strategy (default: "auto").
+ pub fn feature_subset_strategy(&self) -> &str {
+ self.params.string_or("featureSubsetStrategy", "auto")
+ }
+
+ /// 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")
+ }
+
+ /// Whether each tree samples training instances with replacement
(default: true).
+ pub fn bootstrap(&self) -> bool {
+ self.params.bool_or("bootstrap", true)
+ }
+
+ fn model_from_info(
+ &self,
+ info: proto::ml_command_result::MlOperatorInfo,
+ session: &SparkSession,
+ ) -> spark_connect_core::error::Result<RandomForestRegressionModel> {
+ let cached = CachedModel::from_info(&info, session,
"RandomForestRegressor")?;
+ Ok(RandomForestRegressionModel {
+ operator: MlOperator::with_uid(
+ "org.apache.spark.ml.regression.RandomForestRegressionModel",
+ info.uid.as_deref().unwrap_or(&self.operator.uid),
+ OperatorType::Model,
+ ),
+ params: self.params.clone(),
+ cached,
+ })
+ }
+}
+
+impl Default for RandomForestRegressor {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl Estimator for RandomForestRegressor {
+ 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 random forest 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 RandomForestRegressionModel {
+ operator: MlOperator,
+ params: Params,
+ cached: CachedModel,
+}
+
+impl Transformer for RandomForestRegressionModel {
+ 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 RandomForestRegressionModel {
+ fn clone_box(&self) -> Box<dyn Model> {
+ Box::new(self.clone())
+ }
+}
+
/// K-means clustering using Spark's JVM implementation and ML vector features.
///
/// Supports Euclidean and cosine distance. Unset parameters use Spark's
defaults. Without a
@@ -3820,6 +4140,75 @@ mod tests {
.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();
+ let estimator =
RandomForestRegressor::default().set_prediction_col("value");
+ assert_eq!(
+ estimator.operator().name,
+ "org.apache.spark.ml.regression.RandomForestRegressor"
+ );
+ 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-random-forest-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.RandomForestRegressionModel"
+ );
+ 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-random-forest-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 generated_uids_name_the_class_as_pyspark() {
diff --git a/crates/spark-connect/tests/e2e_random_forest_regressor.rs
b/crates/spark-connect/tests/e2e_random_forest_regressor.rs
new file mode 100644
index 00000000..8fa407c2
--- /dev/null
+++ b/crates/spark-connect/tests/e2e_random_forest_regressor.rs
@@ -0,0 +1,243 @@
+//! Native random forest regression tests. Set SPARK_REMOTE to run against a
live Connect server.
+use spark_connect::column::{col, lit_double, lit_string};
+use spark_connect::expression::Expression;
+use spark_connect::ml::{Estimator, RandomForestRegressor};
+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 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() -> RandomForestRegressor {
+ RandomForestRegressor::new()
+ .set_seed(42)
+ .set_num_trees(3)
+ .set_feature_subset_strategy("all")
+ .set_bootstrap(false)
+}
+
+#[test]
+fn
random_forest_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_max_depth(3)
+ .set_max_bins(16)
+ .set_min_instances_per_node(1)
+ .set_min_info_gain(0.0)
+ .set_max_memory_in_mb(64)
+ .set_cache_node_ids(true)
+ .set_checkpoint_interval(-1)
+ .set_impurity("variance")
+ .set_subsampling_rate(1.0)
+ .set_min_weight_fraction_per_node(0.0)
+ .set_weight_col("weight");
+ let mut first = estimator.fit(&training).unwrap();
+ let mut second = estimator
+ .fit(&training.with_column("target", col("target") + lit_double(10.0)))
+ .unwrap();
+ let object_id = |model: &dyn spark_connect::ml::Model| {
+ let spark_connect_proto::ml_relation::MlType::Transform(t) =
+ model.build_ml_relation(&held_out).unwrap().ml_type.unwrap()
+ else {
+ panic!("transform")
+ };
+ let
Some(spark_connect_proto::ml_relation::transform::Operator::ObjRef(r)) =
t.operator
+ else {
+ panic!("cached model")
+ };
+ r.id
+ };
+ assert_ne!(object_id(first.as_ref()), object_id(second.as_ref()));
+ let mut cloned = first.clone_box();
+ let delayed = first
+ .transform(&held_out)
+ .unwrap()
+ .select([col("id"), col("value")]);
+ drop(first);
+ let output = cloned.transform(&held_out).unwrap();
+ assert_eq!(
+ predictions(output.clone(), "value"),
+ vec![-4.0, 5.5, 5.5, -4.0]
+ );
+ let leaves = output.select([vector_array("leaves")]).collect().unwrap();
+ for row in leaves {
+ let spark_connect::row::Value::List(values) = row.get(0).unwrap() else
{
+ panic!("leaf vector")
+ };
+ assert_eq!(values.len(), 3);
+ assert!(values.iter().all(|v| v.as_f64().unwrap() >= 0.0));
+ }
+ let mut repeated = estimator.fit(&training).unwrap();
+ assert_eq!(
+ predictions(repeated.transform(&held_out).unwrap(), "value"),
+ vec![-4.0, 5.5, 5.5, -4.0]
+ );
+ drop(cloned);
+ assert_eq!(predictions(delayed, "value"), vec![-4.0, 5.5, 5.5, -4.0]);
+ assert_eq!(
+ predictions(second.transform(&held_out).unwrap(), "value"),
+ vec![6.0, 15.5, 15.5, 6.0]
+ );
+ assert!(second
+ .transform(&s.new_session().range(1).unwrap())
+ .is_err());
+ s.stop().unwrap();
+}
+
+#[test]
+fn random_forest_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 random_forest_regressor_bootstrap_sampling_is_reproducible() {
+ let Some(s) = session() else {
+ return;
+ };
+ let data = vectors(
+ &s,
+ "SELECT id, array(CAST(id AS DOUBLE), CAST(id % 3 AS DOUBLE)) AS xs,
+ CAST(CASE WHEN id < 20 THEN -3 ELSE 8 END AS DOUBLE) AS label FROM
range(40)",
+ "features",
+ );
+ let mut estimator = RandomForestRegressor::new()
+ .set_seed(1_i64 << 33)
+ .set_num_trees(7)
+ .set_max_depth(3)
+ .set_bootstrap(true)
+ .set_subsampling_rate(0.8)
+ .set_feature_subset_strategy("sqrt");
+ let mut first = estimator.fit(&data).unwrap();
+ let mut second = estimator.fit(&data).unwrap();
+ let actual = predictions(first.transform(&data).unwrap(), "prediction");
+ assert_eq!(
+ actual,
+ predictions(second.transform(&data).unwrap(), "prediction")
+ );
+ assert!(actual
+ .iter()
+ .all(|x| x.is_finite() && *x >= -3.0 && *x <= 8.0));
+ assert!(actual[0] < actual[39]);
+ s.stop().unwrap();
+}
+
+#[test]
+fn random_forest_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_num_trees(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_impurity("gini"),
+ deterministic().set_feature_subset_strategy("invalid"),
+ deterministic().set_subsampling_rate(0.0),
+ deterministic().set_min_weight_fraction_per_node(0.5),
+ ] {
+ assert!(
+ estimator.fit(&data).is_err(),
+ "invalid parameters: {:?}",
+ estimator.params()
+ );
+ }
+ assert!(deterministic().fit(&data.drop(vec!["label"])).is_err());
+ assert!(deterministic()
+ .fit(&data.with_column("label", lit_double(f64::NAN)))
+ .is_err());
+ assert!(deterministic()
+ .set_weight_col("weight")
+ .fit(&data.with_column("weight", lit_double(-1.0)))
+ .is_err());
+ assert!(deterministic()
+ .fit(&data.with_column("features", lit_double(1.0)))
+ .is_err());
+ s.stop().unwrap();
+}
diff --git a/crates/spark-connect/tests/random_forest_regressor_golden.rs
b/crates/spark-connect/tests/random_forest_regressor_golden.rs
new file mode 100644
index 00000000..369dadb0
--- /dev/null
+++ b/crates/spark-connect/tests/random_forest_regressor_golden.rs
@@ -0,0 +1,79 @@
+//! Match every RandomForestRegressor parameter and seed boundary to official
PySpark.
+use base64::{engine::general_purpose::STANDARD, Engine};
+use prost::Message;
+use spark_connect::ml::{Estimator, RandomForestRegressor};
+
+#[test]
+fn random_forest_regressor_parameters_match_official_pyspark() {
+ let fixture: serde_json::Value = serde_json::from_str(include_str!(
+ "../../../tests/golden/random_forest_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 = RandomForestRegressor::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_num_trees(7)
+ .set_feature_subset_strategy("all")
+ .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_bootstrap(false);
+ assert_eq!(estimator.params().to_proto(), expected, "seed {seed}");
+ }
+ assert!(RandomForestRegressor::default()
+ .params()
+ .to_proto()
+ .params
+ .is_empty());
+}
+
+#[test]
+fn random_forest_regressor_getters_track_the_parameters() {
+ let mut estimator = RandomForestRegressor::default();
+ assert_eq!(estimator.feature_col(), "features");
+ assert_eq!(estimator.label_col(), "label");
+ assert_eq!(estimator.prediction_col(), "prediction");
+ assert_eq!(estimator.max_depth(), 5);
+ assert_eq!(estimator.max_bins(), 32);
+ assert_eq!(estimator.min_instances_per_node(), 1);
+ assert_eq!(estimator.min_info_gain(), 0.0);
+ assert_eq!(estimator.max_memory_in_mb(), 256);
+ assert!(!estimator.cache_node_ids());
+ assert_eq!(estimator.checkpoint_interval(), 10);
+ assert_eq!(estimator.impurity(), "variance");
+ assert_eq!(estimator.num_trees(), 20);
+ assert_eq!(estimator.feature_subset_strategy(), "auto");
+ assert_eq!(estimator.seed(), None);
+ assert_eq!(estimator.subsampling_rate(), 1.0);
+ assert_eq!(estimator.leaf_col(), "");
+ assert_eq!(estimator.min_weight_fraction_per_node(), 0.0);
+ assert_eq!(estimator.weight_col(), None);
+ assert!(estimator.bootstrap());
+ let params = std::mem::take(estimator.params_mut())
+ .set_param_string("labelCol", "target")
+ .set_param_int("numTrees", 7)
+ .set_param_double("subsamplingRate", 0.75)
+ .set_param_bool("bootstrap", false);
+ *estimator.params_mut() = params;
+ assert_eq!(estimator.label_col(), "target");
+ assert_eq!(estimator.num_trees(), 7);
+ assert_eq!(estimator.subsampling_rate(), 0.75);
+ assert!(!estimator.bootstrap());
+}
diff --git a/docs/compatibility.md b/docs/compatibility.md
index ac1d31a7..2cfeddc1 100644
--- a/docs/compatibility.md
+++ b/docs/compatibility.md
@@ -181,6 +181,23 @@ not given is not sent, so the server's default applies. A
list param without ele
accepted by its constructor and setters, and a fit, transform or evaluate
raises PySpark's
`CANNOT_INFER_ARRAY_ELEMENT_TYPE` for it, as PySpark's serialization does.
+## Native RandomForestRegressor
+
+`spark_connect::ml::RandomForestRegressor` fits Spark's JVM random forest
regressor
+through Connect using ML vector features and numeric labels. Rust builder
setters
+and getters cover all 19 PySpark constructor parameters, including instance
weights,
+bootstrap sampling, feature sampling and optional per-tree leaf indices. Unset
+parameters use Spark's defaults; a seed can select another reproducible sample.
+
+The native Python estimator is available from
+`pyspark.ml.connect.regression.RandomForestRegressor` and
+`pyspark.ml.connect.RandomForestRegressor`. It uses PySpark's keyword-only
constructor
+names, defaults and parameter conversions, with mutating setters. Fitted models
+expose DataFrame `transform` for the fitting session. Models, clones and lazy
+transformed DataFrames retain the cached server model until their last owner
drops.
+Tree inspection, feature importances, single-vector prediction and persistence
are
+not exposed by this native addition.
+
## Native RandomForestClassifier
`spark_connect::ml::RandomForestClassifier` trains Spark's JVM random forest
diff --git a/python/pyspark/ml/connect/__init__.py
b/python/pyspark/ml/connect/__init__.py
index 929da790..2b996117 100644
--- a/python/pyspark/ml/connect/__init__.py
+++ b/python/pyspark/ml/connect/__init__.py
@@ -12,7 +12,7 @@ from pyspark.ml.connect.feature import (
VectorAssembler,
)
from pyspark.ml.connect.classification import LinearSVC, LogisticRegression,
RandomForestClassifier
-from pyspark.ml.connect.regression import LinearRegression
+from pyspark.ml.connect.regression import LinearRegression,
RandomForestRegressor
from pyspark.ml.connect.clustering import KMeans
from pyspark.ml.connect.evaluation import (
RegressionEvaluator,
@@ -48,6 +48,7 @@ __all__ = [
"LinearSVC",
"RandomForestClassifier",
"LinearRegression",
+ "RandomForestRegressor",
"KMeans",
"RegressionEvaluator",
"BinaryClassificationEvaluator",
diff --git a/python/pyspark/ml/connect/regression.py
b/python/pyspark/ml/connect/regression.py
index b150f791..26c21f91 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
+from pyspark._pyspark import LinearRegression, RandomForestRegressor
-__all__ = ["LinearRegression"]
+__all__ = ["LinearRegression", "RandomForestRegressor"]
diff --git a/python/tests/test_dropin_e2e.py b/python/tests/test_dropin_e2e.py
index 132de5bd..694d96b6 100644
--- a/python/tests/test_dropin_e2e.py
+++ b/python/tests/test_dropin_e2e.py
@@ -5113,3 +5113,96 @@ def
test_random_forest_rejects_invalid_parameters_and_training_data(session):
RandomForestClassifier().fit(training.withColumn("label",F.lit(-1.0)))
with pytest.raises(Exception):
RandomForestClassifier(weightCol="weight").fit(training.withColumn("weight",F.lit(-1.0)))
+
+
+def _random_forest_regressor():
+ try:
+ from pyspark.ml.connect.regression import RandomForestRegressor
+ except ImportError:
+ from pyspark.ml.regression import RandomForestRegressor
+ return RandomForestRegressor
+
+
[email protected]("use_setters", [False, True], ids=["constructor",
"setters"])
+def
test_random_forest_regressor_learns_nonlinear_values_and_retains_lazy_predictions(session,
use_setters):
+ from pyspark.ml.connect.functions import vector_to_array
+ RandomForestRegressor = _random_forest_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", subsamplingRate=1.0, seed=42,
numTrees=3,
+ featureSubsetStrategy="all", leafCol="leaves",
minWeightFractionPerNode=0.0,
+ weightCol="weight", bootstrap=False)
+ if use_setters:
+ estimator = RandomForestRegressor()
+ for name, value in options.items():
+ assert getattr(estimator, "set" + name[0].upper() +
name[1:])(value) is estimator
+ else:
+ estimator = RandomForestRegressor(**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
+ leaves =
first.transform(held_out).select(vector_to_array("leaves").alias("v")).collect()
+ assert all(len(r.v)==3 and all(x>=0 for x in r.v) for r in leaves)
+ 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_random_forest_regressor_instance_weights_change_the_mean(session):
+ RandomForestRegressor = _random_forest_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, numTrees=3, maxDepth=0,
featureSubsetStrategy="all", bootstrap=False)
+ plain = RandomForestRegressor(**options).fit(training)
+ weighted = RandomForestRegressor(**options,
weightCol="weight").fit(training)
+ assert _forest_predictions(plain, training) == [1.0]*4
+ assert _forest_predictions(weighted, training) == [7.0]*4
+
+
+def
test_random_forest_regressor_seeded_bootstrap_and_feature_sampling(session):
+ RandomForestRegressor = _random_forest_regressor()
+ training = _forest_vectors(session,
+ "SELECT id, array(CAST(id AS DOUBLE),CAST(id % 3 AS DOUBLE)) AS xs, "
+ "CAST(CASE WHEN id < 20 THEN -3 ELSE 8 END AS DOUBLE) AS label FROM
range(40)")
+ estimator = RandomForestRegressor(seed=2**33, numTrees=7, maxDepth=3,
+ bootstrap=True, subsamplingRate=0.8,
+ featureSubsetStrategy="sqrt")
+ first = _forest_predictions(estimator.fit(training), training)
+ assert first == _forest_predictions(estimator.fit(training), training)
+ assert all(-3.0 <= x <= 8.0 for x in first)
+ assert first[0] < first[-1]
+
+
+def test_random_forest_regressor_rejects_invalid_parameters_and_data(session):
+ RandomForestRegressor = _random_forest_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(numTrees=0),dict(maxDepth=31),dict(maxBins=1),
+
dict(minInstancesPerNode=0),dict(minInfoGain=-1.0),dict(maxMemoryInMB=-1),
+ dict(checkpointInterval=0),dict(impurity="gini"),
+
dict(featureSubsetStrategy="invalid"),dict(subsamplingRate=0.0),
+ dict(minWeightFractionPerNode=0.5)]:
+ with pytest.raises(Exception):
+ RandomForestRegressor(**options).fit(training)
+ with pytest.raises(Exception):
+ RandomForestRegressor().fit(training.drop("label"))
+ with pytest.raises(Exception):
+
RandomForestRegressor().fit(training.withColumn("label",F.lit(float("nan"))))
+ with pytest.raises(Exception):
+
RandomForestRegressor(weightCol="weight").fit(training.withColumn("weight",F.lit(-1.0)))
+ with pytest.raises(Exception):
+ RandomForestRegressor().fit(training.withColumn("features",F.lit(1.0)))
diff --git a/python/tests/test_ml_e2e.py b/python/tests/test_ml_e2e.py
index d4331dd9..42693b80 100644
--- a/python/tests/test_ml_e2e.py
+++ b/python/tests/test_ml_e2e.py
@@ -248,6 +248,7 @@ def _native_estimators():
LogisticRegression,
MaxAbsScaler,
RandomForestClassifier,
+ RandomForestRegressor,
StandardScaler,
StringIndexer,
)
@@ -259,6 +260,7 @@ def _native_estimators():
(LinearRegression(maxIter=2), ml + "regression.LinearRegressionModel"),
(LogisticRegression(maxIter=2), ml +
"classification.LogisticRegressionModel"),
(RandomForestClassifier(numTrees=2), ml +
"classification.RandomForestClassificationModel"),
+ (RandomForestRegressor(numTrees=2), ml +
"regression.RandomForestRegressionModel"),
(StandardScaler(inputCol="features", outputCol="o"), ml +
"feature.StandardScalerModel"),
(MaxAbsScaler(inputCol="features", outputCol="o"), ml +
"feature.MaxAbsScalerModel"),
(StringIndexer(inputCol="s", outputCol="o"), ml +
"feature.StringIndexerModel"),
diff --git a/python/tests/test_ml_offline.py b/python/tests/test_ml_offline.py
index 5623fa00..b30de5d8 100644
--- a/python/tests/test_ml_offline.py
+++ b/python/tests/test_ml_offline.py
@@ -341,6 +341,13 @@ _NATIVE_PARAMS = {
seed="int", subsamplingRate="float", leafCol="str",
minWeightFractionPerNode="float",
weightCol="str", bootstrap="bool", thresholds="float_list",
),
+ "RandomForestRegressor": dict(
+ featuresCol="str", labelCol="str", predictionCol="str", maxDepth="int",
+ maxBins="int", minInstancesPerNode="int", minInfoGain="float",
maxMemoryInMB="int",
+ cacheNodeIds="bool", checkpointInterval="int", impurity="str",
subsamplingRate="float",
+ seed="int", numTrees="int", featureSubsetStrategy="str", leafCol="str",
+ minWeightFractionPerNode="float", weightCol="str", bootstrap="bool",
+ ),
"KMeans": dict(
featuresCol="str", predictionCol="str", k="int", initMode="str",
initSteps="int",
tol="float", maxIter="int", seed="int", distanceMeasure="str",
weightCol="str",
@@ -2314,3 +2321,45 @@ def
test_ml_none_params_send_null_and_empty_lists_raise_at_the_command_as_pyspar
assert params.params["inputCols"] == text_format.Parse(
expected % _UTF8, pb2.Expression.Literal()
)
+
+
[email protected]("use_setters", [False, True], ids=["constructor",
"setters"])
+def
test_random_forest_regressor_native_parameters_match_official_fixture(ml_mock,
use_setters):
+ import base64
+ import inspect
+ import json
+ from pathlib import Path
+
+ from pyspark.ml.connect import RandomForestRegressor as exported
+ from pyspark.ml.connect.regression import RandomForestRegressor
+
+ assert exported is RandomForestRegressor
+ 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", subsamplingRate=1.0, seed=None,
numTrees=20,
+ featureSubsetStrategy="auto", leafCol="",
minWeightFractionPerNode=0.0,
+ weightCol=None, bootstrap=True)
+ signature = inspect.signature(RandomForestRegressor)
+ 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/random_forest_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", numTrees=7,
+ featureSubsetStrategy="all", seed=case["seed"],
subsamplingRate=0.75,
+ leafCol="leaves", minWeightFractionPerNode=0.1,
weightCol="weight", bootstrap=False)
+ if use_setters:
+ estimator = RandomForestRegressor()
+ for name, value in values.items():
+ assert
getattr(estimator,"set"+name[0].upper()+name[1:])(value) is estimator
+ else:
+ estimator = RandomForestRegressor(**values)
+ operator, params = _native_request(spark, service, estimator, models)
+ assert operator.name ==
"org.apache.spark.ml.regression.RandomForestRegressor"
+ assert params ==
pb2.MlParams.FromString(base64.b64decode(case["params_b64"]))
diff --git a/scripts/capture_random_forest_regressor_golden.py
b/scripts/capture_random_forest_regressor_golden.py
new file mode 100644
index 00000000..e9720ba4
--- /dev/null
+++ b/scripts/capture_random_forest_regressor_golden.py
@@ -0,0 +1,72 @@
+#!/usr/bin/env python3
+"""Capture RandomForestRegressor 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 RandomForestRegressor
+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/random_forest_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 = RandomForestRegressor(
+ featuresCol="input",
+ labelCol="target",
+ predictionCol="value",
+ maxDepth=3,
+ maxBins=16,
+ minInstancesPerNode=2,
+ minInfoGain=0.01,
+ maxMemoryInMB=64,
+ cacheNodeIds=True,
+ checkpointInterval=-1,
+ impurity="variance",
+ numTrees=7,
+ featureSubsetStrategy="all",
+ seed=seed,
+ subsamplingRate=0.75,
+ leafCol="leaves",
+ minWeightFractionPerNode=0.1,
+ weightCol="weight",
+ bootstrap=False,
+ )
+ 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.RandomForestRegressor",
+ "cases": cases,
+ },
+ indent=2,
+ )
+ + "\n"
+ )
+ finally:
+ spark.stop()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/golden/random_forest_regressor.json
b/tests/golden/random_forest_regressor.json
new file mode 100644
index 00000000..d8a49199
--- /dev/null
+++ b/tests/golden/random_forest_regressor.json
@@ -0,0 +1,29 @@
+{
+ "source": "apache/spark v4.3.0 pyspark.ml.regression.RandomForestRegressor",
+ "cases": [
+ {
+ "seed": 42,
+ "params_b64":
"Cg8KCWJvb3RzdHJhcBICGAAKEgoMY2FjaGVOb2RlSWRzEgIYAQohChJjaGVja3BvaW50SW50ZXJ2YWwSCzD///////////8BCh4KFWZlYXR1cmVTdWJzZXRTdHJhdGVneRIFagNhbGwKFgoLZmVhdHVyZXNDb2wSB2oFaW5wdXQKFgoIaW1wdXJpdHkSCmoIdmFyaWFuY2UKFAoIbGFiZWxDb2wSCGoGdGFyZ2V0ChMKB2xlYWZDb2wSCGoGbGVhdmVzCg0KB21heEJpbnMSAjAQCg4KCG1heERlcHRoEgIwAwoTCg1tYXhNZW1vcnlJbk1CEgIwQAoYCgttaW5JbmZvR2FpbhIJWXsUrkfheoQ/ChkKE21pbkluc3RhbmNlc1Blck5vZGUSAjACCiUKGG1pbldlaWdodEZyYWN0aW9uUGVyTm9kZRIJWZqZmZmZmbk/Cg4KCG51bVRyZWVzEgI
[...]
+ },
+ {
+ "seed": -42,
+ "params_b64":
"Cg8KCWJvb3RzdHJhcBICGAAKEgoMY2FjaGVOb2RlSWRzEgIYAQohChJjaGVja3BvaW50SW50ZXJ2YWwSCzD///////////8BCh4KFWZlYXR1cmVTdWJzZXRTdHJhdGVneRIFagNhbGwKFgoLZmVhdHVyZXNDb2wSB2oFaW5wdXQKFgoIaW1wdXJpdHkSCmoIdmFyaWFuY2UKFAoIbGFiZWxDb2wSCGoGdGFyZ2V0ChMKB2xlYWZDb2wSCGoGbGVhdmVzCg0KB21heEJpbnMSAjAQCg4KCG1heERlcHRoEgIwAwoTCg1tYXhNZW1vcnlJbk1CEgIwQAoYCgttaW5JbmZvR2FpbhIJWXsUrkfheoQ/ChkKE21pbkluc3RhbmNlc1Blck5vZGUSAjACCiUKGG1pbldlaWdodEZyYWN0aW9uUGVyTm9kZRIJWZqZmZmZmbk/Cg4KCG51bVRyZWVzEgI
[...]
+ },
+ {
+ "seed": 2147483647,
+ "params_b64":
"Cg8KCWJvb3RzdHJhcBICGAAKEgoMY2FjaGVOb2RlSWRzEgIYAQohChJjaGVja3BvaW50SW50ZXJ2YWwSCzD///////////8BCh4KFWZlYXR1cmVTdWJzZXRTdHJhdGVneRIFagNhbGwKFgoLZmVhdHVyZXNDb2wSB2oFaW5wdXQKFgoIaW1wdXJpdHkSCmoIdmFyaWFuY2UKFAoIbGFiZWxDb2wSCGoGdGFyZ2V0ChMKB2xlYWZDb2wSCGoGbGVhdmVzCg0KB21heEJpbnMSAjAQCg4KCG1heERlcHRoEgIwAwoTCg1tYXhNZW1vcnlJbk1CEgIwQAoYCgttaW5JbmZvR2FpbhIJWXsUrkfheoQ/ChkKE21pbkluc3RhbmNlc1Blck5vZGUSAjACCiUKGG1pbldlaWdodEZyYWN0aW9uUGVyTm9kZRIJWZqZmZmZmbk/Cg4KCG51bVRyZWVzEgI
[...]
+ },
+ {
+ "seed": 2147483648,
+ "params_b64":
"Cg8KCWJvb3RzdHJhcBICGAAKEgoMY2FjaGVOb2RlSWRzEgIYAQohChJjaGVja3BvaW50SW50ZXJ2YWwSCzD///////////8BCh4KFWZlYXR1cmVTdWJzZXRTdHJhdGVneRIFagNhbGwKFgoLZmVhdHVyZXNDb2wSB2oFaW5wdXQKFgoIaW1wdXJpdHkSCmoIdmFyaWFuY2UKFAoIbGFiZWxDb2wSCGoGdGFyZ2V0ChMKB2xlYWZDb2wSCGoGbGVhdmVzCg0KB21heEJpbnMSAjAQCg4KCG1heERlcHRoEgIwAwoTCg1tYXhNZW1vcnlJbk1CEgIwQAoYCgttaW5JbmZvR2FpbhIJWXsUrkfheoQ/ChkKE21pbkluc3RhbmNlc1Blck5vZGUSAjACCiUKGG1pbldlaWdodEZyYWN0aW9uUGVyTm9kZRIJWZqZmZmZmbk/Cg4KCG51bVRyZWVzEgI
[...]
+ },
+ {
+ "seed": -2147483648,
+ "params_b64":
"Cg8KCWJvb3RzdHJhcBICGAAKEgoMY2FjaGVOb2RlSWRzEgIYAQohChJjaGVja3BvaW50SW50ZXJ2YWwSCzD///////////8BCh4KFWZlYXR1cmVTdWJzZXRTdHJhdGVneRIFagNhbGwKFgoLZmVhdHVyZXNDb2wSB2oFaW5wdXQKFgoIaW1wdXJpdHkSCmoIdmFyaWFuY2UKFAoIbGFiZWxDb2wSCGoGdGFyZ2V0ChMKB2xlYWZDb2wSCGoGbGVhdmVzCg0KB21heEJpbnMSAjAQCg4KCG1heERlcHRoEgIwAwoTCg1tYXhNZW1vcnlJbk1CEgIwQAoYCgttaW5JbmZvR2FpbhIJWXsUrkfheoQ/ChkKE21pbkluc3RhbmNlc1Blck5vZGUSAjACCiUKGG1pbldlaWdodEZyYWN0aW9uUGVyTm9kZRIJWZqZmZmZmbk/Cg4KCG51bVRyZWVzEgI
[...]
+ },
+ {
+ "seed": -2147483649,
+ "params_b64":
"Cg8KCWJvb3RzdHJhcBICGAAKEgoMY2FjaGVOb2RlSWRzEgIYAQohChJjaGVja3BvaW50SW50ZXJ2YWwSCzD///////////8BCh4KFWZlYXR1cmVTdWJzZXRTdHJhdGVneRIFagNhbGwKFgoLZmVhdHVyZXNDb2wSB2oFaW5wdXQKFgoIaW1wdXJpdHkSCmoIdmFyaWFuY2UKFAoIbGFiZWxDb2wSCGoGdGFyZ2V0ChMKB2xlYWZDb2wSCGoGbGVhdmVzCg0KB21heEJpbnMSAjAQCg4KCG1heERlcHRoEgIwAwoTCg1tYXhNZW1vcnlJbk1CEgIwQAoYCgttaW5JbmZvR2FpbhIJWXsUrkfheoQ/ChkKE21pbkluc3RhbmNlc1Blck5vZGUSAjACCiUKGG1pbldlaWdodEZyYWN0aW9uUGVyTm9kZRIJWZqZmZmZmbk/Cg4KCG51bVRyZWVzEgI
[...]
+ }
+ ]
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]