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 729a7a36 [SPARK-61358][CONNECT] Support native RandomForestClassifier 
training and prediction
729a7a36 is described below

commit 729a7a36157841de9b90279cf557ed5d536a2d84
Author: Ruifeng Zheng <[email protected]>
AuthorDate: Tue Nov 10 21:21:57 2026 +0900

    [SPARK-61358][CONNECT] Support native RandomForestClassifier training and 
prediction
    
    ### What changes were proposed in this pull request?
    
    Add native `spark_connect::ml::RandomForestClassifier` and 
`RandomForestClassificationModel`. Training uses Spark's ML fit command; 
DataFrame transforms refer to the session-scoped fitted model and return 
predictions, probabilities, raw predictions and optional per-tree leaf indices. 
Models, clones and lazy transformed DataFrames share ownership of the cached 
server model.
    
    Rust builder setters cover all 22 Spark 4.3.0 constructor parameters, 
including `pruneTree`, plus inherited class thresholds. Add the corresponding 
native Python estimator under `pyspark.ml.connect.classification` and 
`pyspark.ml.connect`, with PySpark's keyword-only constructor names/defaults 
and mutating setters. Add reference wire fixtures, native integration tests, CI 
selection and compatibility documentation.
    
    JIRA: https://issues.apache.org/jira/browse/SPARK-61358
    
    ### Why are the changes needed?
    
    The native Rust ML API lacks a random forest classifier. This adds binary 
and multiclass tree-based classification alongside the existing linear 
classifiers, using the established model-cache infrastructure.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes. Rust and native Python users can fit random forests and transform 
DataFrames, configure sampling and instance weights, and adjust predictions 
using class thresholds. A depth-three forest learns the test's nonlinear labels 
(class 1 in the middle, class 0 on either side) and predicts unseen rows.
    
    This native addition exposes fit and DataFrame transform. Tree inspection, 
feature importances, summaries, single-vector prediction and persistence remain 
outside its API; these limits are documented.
    
    ### How was this patch tested?
    
    - Five native Rust tests against a local Spark 4.3.0 Connect server: 
learned binary/multiclass forests, separate fitted references, lazy 
ownership/cloning, cross-session rejection, probabilities/raw predictions/leaf 
outputs, weights, thresholds, seeded bootstrap/feature sampling and invalid 
input.
    - Six new Python cases passed against both official PySpark and the native 
binding. All 17 selected native estimator integration cases passed.
    - Golden parameter matches for all 23 setters and six integer seed 
boundaries. Two Python offline cases verify constructor/setter requests against 
the same official fixtures and check the constructor signature/defaults.
    - Rust library: 567 passed. Python offline: 1,749 passed, 8 skipped. All 
Rust integration targets compile with and without `wasm-udf`; formatting and 
targeted Clippy pass. Core API introspection shows no new missing public names 
across the 12 checked classes.
    - Official 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: exact-master 
comparison found 55 matching error sites and zero new sites.
    - An additional broad Rust test run stalled in existing offline 
execution-hook tests. The same hook test also times out on unchanged master; 
the required library tests and compile-all checks pass.
    
    ### 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 #467 from zhengruifeng/add-random-forest-classifier.
    
    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                        | 229 +++++++++++++-
 crates/spark-connect/src/ml.rs                     | 335 +++++++++++++++++++++
 crates/spark-connect/tests/e2e_random_forest.rs    | 314 +++++++++++++++++++
 crates/spark-connect/tests/random_forest_golden.rs |  47 +++
 docs/compatibility.md                              |  20 ++
 python/pyspark/ml/connect/__init__.py              |   3 +-
 python/pyspark/ml/connect/classification.py        |   4 +-
 python/tests/test_dropin_e2e.py                    | 135 +++++++++
 python/tests/test_dropin_offline.py                |  50 +++
 scripts/capture_random_forest_golden.py            |  73 +++++
 tests/golden/random_forest.json                    |  29 ++
 13 files changed, 1237 insertions(+), 5 deletions(-)

diff --git a/.github/workflows/build_python_connect.yml 
b/.github/workflows/build_python_connect.yml
index 960fac10..1e13414a 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_integration \
+            --test e2e_coverage --test e2e_linear_svc --test 
e2e_linear_regression --test e2e_kmeans --test e2e_random_forest --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 c2ab246f..2740654e 100644
--- a/crates/pyspark-rs/src/lib.rs
+++ b/crates/pyspark-rs/src/lib.rs
@@ -240,6 +240,7 @@ fn _pyspark(_py: Python<'_>, m: &Bound<'_, PyModule>) -> 
PyResult<()> {
     m.add_class::<ml::PyLogisticRegression>()?;
     m.add_class::<ml::PyLinearSVC>()?;
     m.add_class::<ml::PyLinearRegression>()?;
+    m.add_class::<ml::PyRandomForestClassifier>()?;
     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 a064efd1..9cbf2e88 100644
--- a/crates/pyspark-rs/src/ml.rs
+++ b/crates/pyspark-rs/src/ml.rs
@@ -10,7 +10,8 @@ use pyo3::prelude::*;
 use spark_connect::ml::{
     BinaryClassificationEvaluator, CrossValidator, Estimator, Evaluator, 
KMeans, LinearRegression,
     LinearSVC, LogisticRegression, MaxAbsScaler, Model, 
MulticlassClassificationEvaluator,
-    Pipeline, RegressionEvaluator, StandardScaler, StringIndexer, Transformer, 
VectorAssembler,
+    Pipeline, RandomForestClassifier, RegressionEvaluator, StandardScaler, 
StringIndexer,
+    Transformer, VectorAssembler,
 };
 
 use crate::dataframe::PyDataFrame;
@@ -545,6 +546,232 @@ impl PyLinearRegression {
 }
 
 /// K-means clustering backed by Spark Connect's JVM ML API.
+/// Random forest classifier fitted and cached by Spark Connect.
+#[pyclass(
+    name = "RandomForestClassifier",
+    module = "pyspark.ml.connect.classification"
+)]
+pub struct PyRandomForestClassifier {
+    inner: RandomForestClassifier,
+}
+
+#[pymethods]
+impl PyRandomForestClassifier {
+    #[new]
+    #[pyo3(signature = (*, featuresCol="features", labelCol="label", 
predictionCol="prediction", probabilityCol="probability", 
rawPredictionCol="rawPrediction", maxDepth=5, maxBins=32, 
minInstancesPerNode=1, minInfoGain=0.0, pruneTree=true, maxMemoryInMB=256, 
cacheNodeIds=false, checkpointInterval=10, impurity="gini", numTrees=20, 
featureSubsetStrategy="auto", seed=None, subsamplingRate=1.0, leafCol="", 
minWeightFractionPerNode=0.0, weightCol=None, bootstrap=true))]
+    #[allow(non_snake_case, clippy::too_many_arguments)]
+    fn new(
+        featuresCol: &str,
+        labelCol: &str,
+        predictionCol: &str,
+        probabilityCol: &str,
+        rawPredictionCol: &str,
+        maxDepth: i32,
+        maxBins: i32,
+        minInstancesPerNode: i32,
+        minInfoGain: f64,
+        pruneTree: bool,
+        maxMemoryInMB: i32,
+        cacheNodeIds: bool,
+        checkpointInterval: i32,
+        impurity: &str,
+        numTrees: i32,
+        featureSubsetStrategy: &str,
+        seed: Option<i64>,
+        subsamplingRate: f64,
+        leafCol: &str,
+        minWeightFractionPerNode: f64,
+        weightCol: Option<&str>,
+        bootstrap: Option<bool>,
+    ) -> Self {
+        let mut inner = RandomForestClassifier::new()
+            .set_feature_col(featuresCol)
+            .set_label_col(labelCol)
+            .set_prediction_col(predictionCol)
+            .set_probability_col(probabilityCol)
+            .set_raw_prediction_col(rawPredictionCol)
+            .set_max_depth(maxDepth)
+            .set_max_bins(maxBins)
+            .set_min_instances_per_node(minInstancesPerNode)
+            .set_min_info_gain(minInfoGain)
+            .set_prune_tree(pruneTree)
+            .set_max_memory_in_mb(maxMemoryInMB)
+            .set_cache_node_ids(cacheNodeIds)
+            .set_checkpoint_interval(checkpointInterval)
+            .set_impurity(impurity)
+            .set_num_trees(numTrees)
+            .set_feature_subset_strategy(featureSubsetStrategy)
+            .set_subsampling_rate(subsamplingRate)
+            .set_leaf_col(leafCol)
+            .set_min_weight_fraction_per_node(minWeightFractionPerNode);
+        if let Some(value) = seed {
+            inner = inner.set_seed(value);
+        }
+        if let Some(value) = weightCol {
+            inner = inner.set_weight_col(value);
+        }
+        if let Some(value) = bootstrap {
+            inner = inner.set_bootstrap(value);
+        }
+        Self { inner }
+    }
+
+    #[pyo3(name = "setFeaturesCol")]
+    fn set_feature_col<'py>(mut slf: PyRefMut<'py, Self>, value: &str) -> 
PyRefMut<'py, Self> {
+        slf.inner = slf.inner.clone().set_feature_col(value);
+        slf
+    }
+
+    #[pyo3(name = "setLabelCol")]
+    fn set_label_col<'py>(mut slf: PyRefMut<'py, Self>, value: &str) -> 
PyRefMut<'py, Self> {
+        slf.inner = slf.inner.clone().set_label_col(value);
+        slf
+    }
+
+    #[pyo3(name = "setPredictionCol")]
+    fn set_prediction_col<'py>(mut slf: PyRefMut<'py, Self>, value: &str) -> 
PyRefMut<'py, Self> {
+        slf.inner = slf.inner.clone().set_prediction_col(value);
+        slf
+    }
+
+    #[pyo3(name = "setProbabilityCol")]
+    fn set_probability_col<'py>(mut slf: PyRefMut<'py, Self>, value: &str) -> 
PyRefMut<'py, Self> {
+        slf.inner = slf.inner.clone().set_probability_col(value);
+        slf
+    }
+
+    #[pyo3(name = "setRawPredictionCol")]
+    fn set_raw_prediction_col<'py>(
+        mut slf: PyRefMut<'py, Self>,
+        value: &str,
+    ) -> PyRefMut<'py, Self> {
+        slf.inner = slf.inner.clone().set_raw_prediction_col(value);
+        slf
+    }
+
+    #[pyo3(name = "setMaxDepth")]
+    fn set_max_depth(mut slf: PyRefMut<'_, Self>, value: i32) -> PyRefMut<'_, 
Self> {
+        slf.inner = slf.inner.clone().set_max_depth(value);
+        slf
+    }
+
+    #[pyo3(name = "setMaxBins")]
+    fn set_max_bins(mut slf: PyRefMut<'_, Self>, value: i32) -> PyRefMut<'_, 
Self> {
+        slf.inner = slf.inner.clone().set_max_bins(value);
+        slf
+    }
+
+    #[pyo3(name = "setMinInstancesPerNode")]
+    fn set_min_instances_per_node(mut slf: PyRefMut<'_, Self>, value: i32) -> 
PyRefMut<'_, Self> {
+        slf.inner = slf.inner.clone().set_min_instances_per_node(value);
+        slf
+    }
+
+    #[pyo3(name = "setMinInfoGain")]
+    fn set_min_info_gain(mut slf: PyRefMut<'_, Self>, value: f64) -> 
PyRefMut<'_, Self> {
+        slf.inner = slf.inner.clone().set_min_info_gain(value);
+        slf
+    }
+
+    #[pyo3(name = "setPruneTree")]
+    fn set_prune_tree(mut slf: PyRefMut<'_, Self>, value: bool) -> 
PyRefMut<'_, Self> {
+        slf.inner = slf.inner.clone().set_prune_tree(value);
+        slf
+    }
+
+    #[pyo3(name = "setMaxMemoryInMB")]
+    fn set_max_memory_in_mb(mut slf: PyRefMut<'_, Self>, value: i32) -> 
PyRefMut<'_, Self> {
+        slf.inner = slf.inner.clone().set_max_memory_in_mb(value);
+        slf
+    }
+
+    #[pyo3(name = "setCacheNodeIds")]
+    fn set_cache_node_ids(mut slf: PyRefMut<'_, Self>, value: bool) -> 
PyRefMut<'_, Self> {
+        slf.inner = slf.inner.clone().set_cache_node_ids(value);
+        slf
+    }
+
+    #[pyo3(name = "setCheckpointInterval")]
+    fn set_checkpoint_interval(mut slf: PyRefMut<'_, Self>, value: i32) -> 
PyRefMut<'_, Self> {
+        slf.inner = slf.inner.clone().set_checkpoint_interval(value);
+        slf
+    }
+
+    #[pyo3(name = "setImpurity")]
+    fn set_impurity<'py>(mut slf: PyRefMut<'py, Self>, value: &str) -> 
PyRefMut<'py, Self> {
+        slf.inner = slf.inner.clone().set_impurity(value);
+        slf
+    }
+
+    #[pyo3(name = "setNumTrees")]
+    fn set_num_trees(mut slf: PyRefMut<'_, Self>, value: i32) -> PyRefMut<'_, 
Self> {
+        slf.inner = slf.inner.clone().set_num_trees(value);
+        slf
+    }
+
+    #[pyo3(name = "setFeatureSubsetStrategy")]
+    fn set_feature_subset_strategy<'py>(
+        mut slf: PyRefMut<'py, Self>,
+        value: &str,
+    ) -> PyRefMut<'py, Self> {
+        slf.inner = slf.inner.clone().set_feature_subset_strategy(value);
+        slf
+    }
+
+    #[pyo3(name = "setSeed")]
+    fn set_seed(mut slf: PyRefMut<'_, Self>, value: i64) -> PyRefMut<'_, Self> 
{
+        slf.inner = slf.inner.clone().set_seed(value);
+        slf
+    }
+
+    #[pyo3(name = "setSubsamplingRate")]
+    fn set_subsampling_rate(mut slf: PyRefMut<'_, Self>, value: f64) -> 
PyRefMut<'_, Self> {
+        slf.inner = slf.inner.clone().set_subsampling_rate(value);
+        slf
+    }
+
+    #[pyo3(name = "setLeafCol")]
+    fn set_leaf_col<'py>(mut slf: PyRefMut<'py, Self>, value: &str) -> 
PyRefMut<'py, Self> {
+        slf.inner = slf.inner.clone().set_leaf_col(value);
+        slf
+    }
+
+    #[pyo3(name = "setMinWeightFractionPerNode")]
+    fn set_min_weight_fraction_per_node(
+        mut slf: PyRefMut<'_, Self>,
+        value: f64,
+    ) -> PyRefMut<'_, Self> {
+        slf.inner = slf.inner.clone().set_min_weight_fraction_per_node(value);
+        slf
+    }
+
+    #[pyo3(name = "setWeightCol")]
+    fn set_weight_col<'py>(mut slf: PyRefMut<'py, Self>, value: &str) -> 
PyRefMut<'py, Self> {
+        slf.inner = slf.inner.clone().set_weight_col(value);
+        slf
+    }
+
+    #[pyo3(name = "setBootstrap")]
+    fn set_bootstrap(mut slf: PyRefMut<'_, Self>, value: bool) -> PyRefMut<'_, 
Self> {
+        slf.inner = slf.inner.clone().set_bootstrap(value);
+        slf
+    }
+
+    #[pyo3(name = "setThresholds")]
+    fn set_thresholds(mut slf: PyRefMut<'_, Self>, value: Vec<f64>) -> 
PyRefMut<'_, Self> {
+        slf.inner = slf.inner.clone().set_thresholds(value);
+        slf
+    }
+
+    fn fit(&self, py: Python<'_>, df: &PyDataFrame) -> PyResult<PyMLModel> {
+        let mut estimator = self.inner.clone();
+        let model = interruptible(py, &df.dataframe.spark_session(), || {
+            estimator.fit(&df.dataframe).map_err(Box::new)
+        })?;
+        Ok(PyMLModel { model })
+    }
+}
+
 #[pyclass(name = "KMeans", module = "pyspark.ml.connect.clustering")]
 pub struct PyKMeans {
     inner: KMeans,
diff --git a/crates/spark-connect/src/ml.rs b/crates/spark-connect/src/ml.rs
index cb38c927..f6f16587 100644
--- a/crates/spark-connect/src/ml.rs
+++ b/crates/spark-connect/src/ml.rs
@@ -93,6 +93,23 @@ impl Params {
         self
     }
 
+    /// Encode an ML parameter whose JVM type is `Array[Double]`, as PySpark 
sends thresholds.
+    fn set_param_double_array(mut self, name: &str, values: impl 
IntoIterator<Item = f64>) -> Self {
+        let literal = LiteralExpression::Array {
+            element_type: Box::new(DataType::Double),
+            elements: 
values.into_iter().map(LiteralExpression::Double).collect(),
+        }
+        .to_literal_proto();
+        self.params.insert(
+            name.to_string(),
+            proto::Expression {
+                expr_type: Some(proto::expression::ExprType::Literal(literal)),
+                ..Default::default()
+            },
+        );
+        self
+    }
+
     /// Set a parameter to a double value.
     pub fn set_param_double(mut self, name: &str, value: f64) -> Self {
         let mut literal = proto::Expression::default();
@@ -1562,6 +1579,255 @@ impl Model for LinearRegressionModel {
     }
 }
 
+/// Random forest classification using Spark's JVM implementation and ML 
vector features.
+///
+/// Supports binary and multiclass labels. Unset parameters use Spark's 
defaults.
+/// Set a seed explicitly for reproducible sampling.
+#[derive(Debug, Clone)]
+pub struct RandomForestClassifier {
+    operator: MlOperator,
+    params: Params,
+}
+
+impl RandomForestClassifier {
+    pub fn new() -> Self {
+        Self {
+            operator: MlOperator::new(
+                "org.apache.spark.ml.classification.RandomForestClassifier",
+                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 label column; labels must be contiguous class indices starting 
at zero.
+    pub fn set_label_col(mut self, value: &str) -> Self {
+        self.params = self.params.set_param_string("labelCol", value);
+        self
+    }
+
+    /// Predicted class output column.
+    pub fn set_prediction_col(mut self, value: &str) -> Self {
+        self.params = self.params.set_param_string("predictionCol", value);
+        self
+    }
+
+    /// Class probability output column.
+    pub fn set_probability_col(mut self, value: &str) -> Self {
+        self.params = self.params.set_param_string("probabilityCol", value);
+        self
+    }
+
+    /// Raw class prediction output column.
+    pub fn set_raw_prediction_col(mut self, value: &str) -> Self {
+        self.params = self.params.set_param_string("rawPredictionCol", value);
+        self
+    }
+
+    /// Maximum tree depth, from 0 to 30.
+    pub fn set_max_depth(mut self, value: i32) -> Self {
+        self.params = self.params.set_param_int32("maxDepth", value);
+        self
+    }
+
+    /// Maximum number of bins for discretizing continuous features.
+    pub fn set_max_bins(mut self, value: i32) -> Self {
+        self.params = self.params.set_param_int32("maxBins", value);
+        self
+    }
+
+    /// Minimum number of training instances in each child node.
+    pub fn set_min_instances_per_node(mut self, value: i32) -> Self {
+        self.params = self.params.set_param_int32("minInstancesPerNode", 
value);
+        self
+    }
+
+    /// Minimum information gain for a split.
+    pub fn set_min_info_gain(mut self, value: f64) -> Self {
+        self.params = self.params.set_param_double("minInfoGain", value);
+        self
+    }
+
+    /// Whether to prune redundant nodes, as supported by Spark 4.3.0.
+    pub fn set_prune_tree(mut self, value: bool) -> Self {
+        self.params = self.params.set_param_bool("pruneTree", 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: gini or entropy.
+    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
+    }
+
+    /// Per-class thresholds: predictions maximize probability divided by 
threshold.
+    /// Provide one nonnegative value per class, with at most one zero.
+    pub fn set_thresholds(mut self, values: impl IntoIterator<Item = f64>) -> 
Self {
+        self.params = self.params.set_param_double_array("thresholds", values);
+        self
+    }
+
+    fn model_from_info(
+        &self,
+        info: proto::ml_command_result::MlOperatorInfo,
+        session: &SparkSession,
+    ) -> spark_connect_core::error::Result<RandomForestClassificationModel> {
+        let cached = CachedModel::from_info(&info, session, 
"RandomForestClassifier")?;
+        Ok(RandomForestClassificationModel {
+            operator: MlOperator::with_uid(
+                
"org.apache.spark.ml.classification.RandomForestClassificationModel",
+                info.uid.as_deref().unwrap_or(&self.operator.uid),
+                OperatorType::Model,
+            ),
+            params: self.params.clone(),
+            cached,
+        })
+    }
+}
+
+impl Default for RandomForestClassifier {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl Estimator for RandomForestClassifier {
+    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 classification model fitted by Spark Connect.
+///
+/// Obtain it through [`Estimator::fit`]. The model, its clones and transformed
+/// DataFrames retain the cached server model until the last owner is dropped.
+#[derive(Debug, Clone)]
+pub struct RandomForestClassificationModel {
+    operator: MlOperator,
+    params: Params,
+    cached: CachedModel,
+}
+
+impl Transformer for RandomForestClassificationModel {
+    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 RandomForestClassificationModel {
+    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.
@@ -2990,4 +3256,73 @@ mod tests {
             .is_err());
         assert!(model.clone_box().transform(&df).is_ok());
     }
+    #[test]
+    fn random_forest_validates_fitted_references_and_model_metadata() {
+        let session = offline_session();
+        let estimator = 
RandomForestClassifier::default().set_prediction_col("class");
+        assert_eq!(
+            estimator.operator().name,
+            "org.apache.spark.ml.classification.RandomForestClassifier"
+        );
+        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".into(),
+                },
+            )),
+            uid,
+            ..Default::default()
+        };
+        let mut model = estimator
+            .model_from_info(info(Some("returned-uid".into())), &session)
+            .unwrap();
+        assert_eq!(model.operator().uid, "returned-uid");
+        assert_eq!(
+            model.operator().name,
+            
"org.apache.spark.ml.classification.RandomForestClassificationModel"
+        );
+        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".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());
+    }
 }
diff --git a/crates/spark-connect/tests/e2e_random_forest.rs 
b/crates/spark-connect/tests/e2e_random_forest.rs
new file mode 100644
index 00000000..865e2e58
--- /dev/null
+++ b/crates/spark-connect/tests/e2e_random_forest.rs
@@ -0,0 +1,314 @@
+//! Native random forest 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, RandomForestClassifier};
+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() -> RandomForestClassifier {
+    RandomForestClassifier::new()
+        .set_seed(42)
+        .set_num_trees(3)
+        .set_feature_subset_strategy("all")
+        .set_bootstrap(false)
+}
+
+#[test]
+fn random_forest_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,0),(-2,0),(-1,1),(0,1),(1,1),(2,0),(3,0) AS t(x,y)",
+        "input",
+    );
+    let held_out = vectors(
+        &s,
+        "SELECT id, array(CAST(x AS DOUBLE)) AS xs
+         FROM VALUES (0,-2.5),(1,-0.5),(2,0.5),(3,2.5) AS t(id,x)",
+        "input",
+    );
+    let mut estimator = deterministic()
+        .set_feature_col("input")
+        .set_label_col("target")
+        .set_prediction_col("class")
+        .set_probability_col("probs")
+        .set_raw_prediction_col("votes")
+        .set_leaf_col("leaves")
+        .set_max_depth(3)
+        .set_max_bins(16)
+        .set_min_instances_per_node(1)
+        .set_min_info_gain(0.0)
+        .set_prune_tree(false)
+        .set_max_memory_in_mb(64)
+        .set_cache_node_ids(true)
+        .set_checkpoint_interval(-1)
+        .set_impurity("entropy")
+        .set_subsampling_rate(1.0)
+        .set_min_weight_fraction_per_node(0.0)
+        .set_weight_col("weight");
+    let mut first = estimator.fit(&training).unwrap();
+    let mut second = estimator
+        .fit(&training.with_column("target", lit_double(1.0) - col("target")))
+        .unwrap();
+    let object_id = |model: &dyn spark_connect::ml::Model| {
+        let spark_connect_proto::ml_relation::MlType::Transform(t) =
+            model.build_ml_relation(&held_out).unwrap().ml_type.unwrap()
+        else {
+            panic!("transform")
+        };
+        let 
Some(spark_connect_proto::ml_relation::transform::Operator::ObjRef(r)) = 
t.operator
+        else {
+            panic!("cached model")
+        };
+        r.id
+    };
+    assert_ne!(object_id(first.as_ref()), object_id(second.as_ref()));
+    let mut cloned = first.clone_box();
+    let delayed = first
+        .transform(&held_out)
+        .unwrap()
+        .select([col("id"), col("class")]);
+    drop(first);
+    let output = cloned.transform(&held_out).unwrap();
+    assert_eq!(
+        predictions(output.clone(), "class"),
+        vec![0.0, 1.0, 1.0, 0.0]
+    );
+    let vectors = output
+        .select([
+            vector_array("probs"),
+            vector_array("votes"),
+            vector_array("leaves"),
+        ])
+        .collect()
+        .unwrap();
+    for row in vectors {
+        for (i, size) in [(0, 2), (1, 2), (2, 3)] {
+            let spark_connect::row::Value::List(values) = row.get(i).unwrap() 
else {
+                panic!("vector array")
+            };
+            assert_eq!(values.len(), size);
+        }
+    }
+    let mut repeated = estimator.fit(&training).unwrap();
+    assert_eq!(
+        predictions(repeated.transform(&held_out).unwrap(), "class"),
+        vec![0.0, 1.0, 1.0, 0.0]
+    );
+    drop(cloned);
+    assert_eq!(predictions(delayed, "class"), vec![0.0, 1.0, 1.0, 0.0]);
+    assert_eq!(
+        predictions(second.transform(&held_out).unwrap(), "class"),
+        vec![1.0, 0.0, 0.0, 1.0]
+    );
+    assert!(second
+        .transform(&s.new_session().range(1).unwrap())
+        .is_err());
+    s.stop().unwrap();
+}
+
+#[test]
+fn random_forest_supports_multiclass_probabilities_and_leaf_indices() {
+    let Some(s) = session() else {
+        return;
+    };
+    let training = vectors(
+        &s,
+        "SELECT array(CAST(x AS DOUBLE)) AS xs, CAST(y AS DOUBLE) AS label
+         FROM VALUES (-3,0),(-2,0),(-1,1),(0,1),(1,2),(2,2) AS t(x,y)",
+        "features",
+    );
+    let held_out = vectors(&s,
+        "SELECT id, array(CAST(x AS DOUBLE)) AS xs FROM VALUES 
(0,-2.5),(1,-0.5),(2,1.5) AS t(id,x)", "features");
+    let mut model = deterministic()
+        .set_max_depth(3)
+        .set_leaf_col("leaves")
+        .fit(&training)
+        .unwrap();
+    let output = model.transform(&held_out).unwrap();
+    assert_eq!(
+        predictions(output.clone(), "prediction"),
+        vec![0.0, 1.0, 2.0]
+    );
+    let rows = output
+        .order_by(vec![col("id").asc().expression().clone()])
+        .select([
+            vector_array("probability"),
+            vector_array("rawPrediction"),
+            vector_array("leaves"),
+        ])
+        .collect()
+        .unwrap();
+    for (class, row) in rows.iter().enumerate() {
+        let spark_connect::row::Value::List(probs) = row.get(0).unwrap() else {
+            panic!("probability vector")
+        };
+        let spark_connect::row::Value::List(raw) = row.get(1).unwrap() else {
+            panic!("raw vector")
+        };
+        let spark_connect::row::Value::List(leaves) = row.get(2).unwrap() else 
{
+            panic!("leaf vector")
+        };
+        assert_eq!(probs.len(), 3);
+        assert_eq!(raw.len(), 3);
+        assert_eq!(leaves.len(), 3);
+        for i in 0..3 {
+            assert_eq!(probs[i].as_f64(), Some(if i == class { 1.0 } else { 
0.0 }));
+            assert_eq!(raw[i].as_f64(), Some(if i == class { 3.0 } else { 0.0 
}));
+        }
+    }
+    s.stop().unwrap();
+}
+
+#[test]
+fn random_forest_weights_and_class_thresholds_change_predictions() {
+    let Some(s) = session() else {
+        return;
+    };
+    // No split: the class probability is the (weighted) label frequency.
+    let training = vectors(
+        &s,
+        "SELECT array(0.0D) AS xs, CAST(y AS DOUBLE) AS label, CAST(w AS 
DOUBLE) AS weight
+         FROM VALUES (0,1),(0,1),(0,1),(1,9) AS t(y,w)",
+        "features",
+    );
+    let held_out = vectors(&s, "SELECT 0 AS id, array(0.0D) AS xs", 
"features");
+    let mut plain = deterministic().set_max_depth(0).fit(&training).unwrap();
+    let mut weighted = deterministic()
+        .set_max_depth(0)
+        .set_weight_col("weight")
+        .fit(&training)
+        .unwrap();
+    let mut thresholded = deterministic()
+        .set_max_depth(0)
+        .set_thresholds([1.0, 0.1])
+        .fit(&training)
+        .unwrap();
+    assert_eq!(
+        predictions(plain.transform(&held_out).unwrap(), "prediction"),
+        vec![0.0]
+    );
+    assert_eq!(
+        predictions(weighted.transform(&held_out).unwrap(), "prediction"),
+        vec![1.0]
+    );
+    assert_eq!(
+        predictions(thresholded.transform(&held_out).unwrap(), "prediction"),
+        vec![1.0]
+    );
+    s.stop().unwrap();
+}
+
+#[test]
+fn random_forest_bootstrap_and_feature_sampling_train_reproducibly() {
+    let Some(s) = session() else {
+        return;
+    };
+    let training = vectors(
+        &s,
+        "SELECT id, array(CAST(id AS DOUBLE), CAST(id % 3 AS DOUBLE)) AS xs,
+         CAST(CASE WHEN id < 20 THEN 0 ELSE 1 END AS DOUBLE) AS label FROM 
range(40)",
+        "features",
+    );
+    let mut estimator = RandomForestClassifier::default()
+        .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(&training).unwrap();
+    let mut repeated = estimator.fit(&training).unwrap();
+    let first = predictions(first.transform(&training).unwrap(), "prediction");
+    assert_eq!(
+        first,
+        predictions(repeated.transform(&training).unwrap(), "prediction")
+    );
+    assert!(first[..15].iter().all(|p| *p == 0.0));
+    assert!(first[25..].iter().all(|p| *p == 1.0));
+    s.stop().unwrap();
+}
+
+#[test]
+fn random_forest_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,0),(1,1) 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("invalid"),
+        deterministic().set_feature_subset_strategy("invalid"),
+        deterministic().set_subsampling_rate(0.0),
+        deterministic().set_min_weight_fraction_per_node(0.5),
+        deterministic().set_thresholds([1.0, 1.0, 1.0]),
+    ] {
+        assert!(
+            estimator.fit(&data).is_err(),
+            "invalid params: {:?}",
+            estimator.params()
+        );
+    }
+    assert!(deterministic().fit(&data.drop(vec!["label"])).is_err());
+    assert!(deterministic()
+        .fit(&data.with_column("label", lit_double(-1.0)))
+        .is_err());
+    assert!(deterministic()
+        .set_weight_col("weight")
+        .fit(&data.with_column("weight", lit_double(-1.0)))
+        .is_err());
+    s.stop().unwrap();
+}
diff --git a/crates/spark-connect/tests/random_forest_golden.rs 
b/crates/spark-connect/tests/random_forest_golden.rs
new file mode 100644
index 00000000..847f36d1
--- /dev/null
+++ b/crates/spark-connect/tests/random_forest_golden.rs
@@ -0,0 +1,47 @@
+//! Match every RandomForestClassifier parameter and seed boundary to official 
PySpark.
+use base64::{engine::general_purpose::STANDARD, Engine};
+use prost::Message;
+use spark_connect::ml::{Estimator, RandomForestClassifier};
+
+#[test]
+fn random_forest_parameters_match_official_pyspark() {
+    let fixture: serde_json::Value =
+        
serde_json::from_str(include_str!("../../../tests/golden/random_forest.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 = RandomForestClassifier::new()
+            .set_feature_col("input")
+            .set_label_col("target")
+            .set_prediction_col("class")
+            .set_probability_col("probs")
+            .set_raw_prediction_col("votes")
+            .set_max_depth(3)
+            .set_max_bins(16)
+            .set_min_instances_per_node(2)
+            .set_min_info_gain(0.01)
+            .set_prune_tree(false)
+            .set_max_memory_in_mb(64)
+            .set_cache_node_ids(true)
+            .set_checkpoint_interval(-1)
+            .set_impurity("entropy")
+            .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)
+            .set_thresholds([0.25, 0.75]);
+        assert_eq!(estimator.params().to_proto(), expected, "seed {seed}");
+    }
+    assert!(RandomForestClassifier::default()
+        .params()
+        .to_proto()
+        .params
+        .is_empty());
+}
diff --git a/docs/compatibility.md b/docs/compatibility.md
index f4a0b98e..82b89387 100644
--- a/docs/compatibility.md
+++ b/docs/compatibility.md
@@ -90,6 +90,26 @@ executed later. When the last of them is dropped, the cached 
model is deleted on
 server, as `pyspark.ml` does, without waiting for the server; a fit that is 
dropped
 at once leaves nothing cached.
 
+## Native RandomForestClassifier
+
+`spark_connect::ml::RandomForestClassifier` trains Spark's JVM random forest
+classifier through Connect with ML vector features and contiguous numeric class
+labels starting at zero. Rust builder setters cover all 22 PySpark constructor
+parameters, including `pruneTree` (Spark 4.3.0), plus class thresholds. Unset
+parameters use Spark's defaults; set a seed for reproducible sampling.
+
+The native Python binding is available as
+`pyspark.ml.connect.classification.RandomForestClassifier` and
+`pyspark.ml.connect.RandomForestClassifier`. Its keyword-only constructor 
matches
+PySpark's parameter names and defaults, with mutating `setFeaturesCol`,
+`setNumTrees`, etc. methods and `setThresholds`.
+
+Fitted models expose DataFrame `transform`, including prediction, probability,
+raw prediction and optional per-tree leaf index columns. Models, clones and 
lazy
+transformed DataFrames retain the cached model in its fitting session until the
+last owner is dropped. Tree inspection, feature importances, training 
summaries,
+single-vector prediction and persistence are not exposed by this native 
addition.
+
 ## Native KMeans
 
 `spark_connect::ml::KMeans` fits Spark's JVM K-means estimator with ML vector
diff --git a/python/pyspark/ml/connect/__init__.py 
b/python/pyspark/ml/connect/__init__.py
index 328dd191..929da790 100644
--- a/python/pyspark/ml/connect/__init__.py
+++ b/python/pyspark/ml/connect/__init__.py
@@ -11,7 +11,7 @@ from pyspark.ml.connect.feature import (
     StringIndexer,
     VectorAssembler,
 )
-from pyspark.ml.connect.classification import LinearSVC, LogisticRegression
+from pyspark.ml.connect.classification import LinearSVC, LogisticRegression, 
RandomForestClassifier
 from pyspark.ml.connect.regression import LinearRegression
 from pyspark.ml.connect.clustering import KMeans
 from pyspark.ml.connect.evaluation import (
@@ -46,6 +46,7 @@ __all__ = [
     "VectorAssembler",
     "LogisticRegression",
     "LinearSVC",
+    "RandomForestClassifier",
     "LinearRegression",
     "KMeans",
     "RegressionEvaluator",
diff --git a/python/pyspark/ml/connect/classification.py 
b/python/pyspark/ml/connect/classification.py
index 263aa135..18eac07f 100644
--- a/python/pyspark/ml/connect/classification.py
+++ b/python/pyspark/ml/connect/classification.py
@@ -1,4 +1,4 @@
 """Classification estimators (pyspark.ml.connect.classification)."""
-from pyspark._pyspark import LinearSVC, LogisticRegression
+from pyspark._pyspark import LinearSVC, LogisticRegression, 
RandomForestClassifier
 
-__all__ = ["LinearSVC", "LogisticRegression"]
+__all__ = ["LinearSVC", "LogisticRegression", "RandomForestClassifier"]
diff --git a/python/tests/test_dropin_e2e.py b/python/tests/test_dropin_e2e.py
index f7404170..67669ce0 100644
--- a/python/tests/test_dropin_e2e.py
+++ b/python/tests/test_dropin_e2e.py
@@ -4808,3 +4808,138 @@ def 
test_higher_order_functions_take_columns_and_reject_lists_as_pyspark(session
     assert session.range(1).select(
         F.exists(F.array(F.lit(1), F.lit(2)), lambda x: x > 
1).alias("e")).collect() == [
             Row(e=True)]
+
+
+# These cases run unchanged against the native binding and the official 
JVM-backed estimator.
+def _random_forest_classifier():
+    try:
+        from pyspark.ml.connect.classification import RandomForestClassifier
+    except ImportError:
+        from pyspark.ml.classification import RandomForestClassifier
+    return RandomForestClassifier
+
+
+def _forest_vectors(session, sql, column="features"):
+    from pyspark.ml.connect.functions import array_to_vector
+    return session.sql(sql).withColumn(column, array_to_vector("xs"))
+
+
+def _forest_predictions(model, frame, column="prediction"):
+    return [r[column] for r in model.transform(frame).orderBy("id").collect()]
+
+
[email protected]("use_setters", [False, True], ids=["constructor", 
"setters"])
+def 
test_random_forest_learns_nonlinear_labels_and_preserves_lazy_predictions(session,
 use_setters):
+    from pyspark.ml.connect.functions import vector_to_array
+    RandomForestClassifier = _random_forest_classifier()
+    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,0),(-2,0),(-1,1),(0,1),(1,1),(2,0),(3,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")
+    kwargs = dict(featuresCol="input", labelCol="target", 
predictionCol="class",
+                  probabilityCol="probs", rawPredictionCol="votes", maxDepth=3,
+                  maxBins=16, minInstancesPerNode=1, minInfoGain=0.0, 
pruneTree=False,
+                  maxMemoryInMB=64, cacheNodeIds=True, checkpointInterval=-1,
+                  impurity="entropy", numTrees=3, featureSubsetStrategy="all", 
seed=42,
+                  subsamplingRate=1.0, leafCol="leaves", 
minWeightFractionPerNode=0.0,
+                  weightCol="weight", bootstrap=False)
+    if use_setters:
+        estimator = RandomForestClassifier()
+        for name, value in kwargs.items():
+            assert getattr(estimator, "set" + name[0].upper() + 
name[1:])(value) is estimator
+    else:
+        estimator = RandomForestClassifier(**kwargs)
+    model = estimator.fit(training)
+    other = estimator.fit(training.withColumn("target", 1.0 - F.col("target")))
+    delayed = model.transform(held_out).select("id", "class")
+    rows = model.transform(held_out).orderBy("id").select(
+        vector_to_array("probs").alias("p"), 
vector_to_array("votes").alias("v"),
+        vector_to_array("leaves").alias("l")).collect()
+    assert [r.p for r in rows] == [[1.0,0.0],[0.0,1.0],[0.0,1.0],[1.0,0.0]]
+    assert [r.v for r in rows] == [[3.0,0.0],[0.0,3.0],[0.0,3.0],[3.0,0.0]]
+    assert all(len(r.l) == 3 for r in rows)
+    assert _forest_predictions(model, held_out, "class") == [0.0,1.0,1.0,0.0]
+    assert _forest_predictions(estimator.fit(training), held_out, "class") == 
[0.0,1.0,1.0,0.0]
+    del model
+    import gc
+    gc.collect()
+    assert [r["class"] for r in delayed.orderBy("id").collect()] == 
[0.0,1.0,1.0,0.0]
+    assert _forest_predictions(other, held_out, "class") == [1.0,0.0,0.0,1.0]
+
+
+def test_random_forest_multiclass_probabilities_and_leaf_indices(session):
+    from pyspark.ml.connect.functions import vector_to_array
+    RandomForestClassifier = _random_forest_classifier()
+    training = _forest_vectors(session,
+        "SELECT array(CAST(x AS DOUBLE)) AS xs, CAST(y AS DOUBLE) AS label "
+        "FROM VALUES (-3,0),(-2,0),(-1,1),(0,1),(1,2),(2,2) AS t(x,y)")
+    held_out = _forest_vectors(session,
+        "SELECT id, array(CAST(x AS DOUBLE)) AS xs "
+        "FROM VALUES (0,-2.5),(1,-0.5),(2,1.5) AS t(id,x)")
+    model = RandomForestClassifier(seed=42, numTrees=3, maxDepth=3,
+                                   featureSubsetStrategy="all", 
bootstrap=False,
+                                   leafCol="leaves").fit(training)
+    assert _forest_predictions(model, held_out) == [0.0,1.0,2.0]
+    rows = model.transform(held_out).orderBy("id").select(
+        vector_to_array("probability").alias("p"),
+        vector_to_array("rawPrediction").alias("v"), 
vector_to_array("leaves").alias("l")).collect()
+    assert [r.p for r in rows] == [[1.0,0.0,0.0],[0.0,1.0,0.0],[0.0,0.0,1.0]]
+    assert [r.v for r in rows] == [[3.0,0.0,0.0],[0.0,3.0,0.0],[0.0,0.0,3.0]]
+    assert all(len(r.l)==3 for r in rows)
+
+
+def 
test_random_forest_weights_and_class_thresholds_change_predictions(session):
+    from pyspark.ml.connect.functions import vector_to_array
+    RandomForestClassifier = _random_forest_classifier()
+    training = _forest_vectors(session,
+        "SELECT array(0.0D) AS xs, CAST(y AS DOUBLE) AS label, CAST(w AS 
DOUBLE) AS weight "
+        "FROM VALUES (0,1),(0,1),(0,1),(1,9) AS t(y,w)")
+    held_out = _forest_vectors(session, "SELECT 0 AS id, array(0.0D) AS xs")
+    options = dict(seed=42, numTrees=3, maxDepth=0, 
featureSubsetStrategy="all", bootstrap=False)
+    plain = RandomForestClassifier(**options).fit(training)
+    weighted = RandomForestClassifier(**options, 
weightCol="weight").fit(training)
+    estimator = RandomForestClassifier(**options)
+    assert estimator.setThresholds([1.0,0.1]) is estimator
+    thresholded = estimator.fit(training)
+    assert _forest_predictions(plain, held_out) == [0.0]
+    assert _forest_predictions(weighted, held_out) == [1.0]
+    assert _forest_predictions(thresholded, held_out) == [1.0]
+    for model, expected in [(plain,[0.75,0.25]), (weighted,[0.25,0.75]), 
(thresholded,[0.75,0.25])]:
+        assert 
model.transform(held_out).select(vector_to_array("probability").alias("p")).first().p
 == expected
+
+
+def test_random_forest_bootstrap_sampling_is_reproducible(session):
+    RandomForestClassifier = _random_forest_classifier()
+    training = _forest_vectors(session,
+        "SELECT id, array(CAST(id AS DOUBLE),CAST(id % 3 AS DOUBLE)) AS xs, "
+        "CAST(CASE WHEN id < 20 THEN 0 ELSE 1 END AS DOUBLE) AS label FROM 
range(40)")
+    estimator = RandomForestClassifier(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 first[:15] == [0.0]*15 and first[25:] == [1.0]*15
+
+
+def test_random_forest_rejects_invalid_parameters_and_training_data(session):
+    RandomForestClassifier = _random_forest_classifier()
+    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,0),(1,1) 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="invalid"),dict(featureSubsetStrategy="invalid"),
+                    
dict(subsamplingRate=0.0),dict(minWeightFractionPerNode=0.5)]:
+        with pytest.raises(Exception):
+            RandomForestClassifier(**options).fit(training)
+    with pytest.raises(Exception):
+        RandomForestClassifier().setThresholds([1.0,1.0,1.0]).fit(training)
+    with pytest.raises(Exception):
+        RandomForestClassifier().fit(training.drop("label"))
+    with pytest.raises(Exception):
+        RandomForestClassifier().fit(training.withColumn("label",F.lit(-1.0)))
+    with pytest.raises(Exception):
+        
RandomForestClassifier(weightCol="weight").fit(training.withColumn("weight",F.lit(-1.0)))
diff --git a/python/tests/test_dropin_offline.py 
b/python/tests/test_dropin_offline.py
index 2cbb63ff..0d23d653 100644
--- a/python/tests/test_dropin_offline.py
+++ b/python/tests/test_dropin_offline.py
@@ -18885,3 +18885,53 @@ def 
test_schemas_of_plans_over_the_server_threshold_are_sent_compressed(mock_con
     plan = 
parse_message(parse_message(service.analyze_requests[-1])[4][0])[1][0]
     assert 1 not in parse_message(plan)
     assert parse_message(parse_message(plan)[3][0])[3] == [1]
+
+
[email protected]("use_setters", [False, True], ids=["constructor", 
"setters"])
+def test_random_forest_native_binding_sends_reference_parameters(mock_connect, 
use_setters):
+    import base64
+    import inspect
+    from pathlib import Path
+
+    from pyspark.ml.connect import RandomForestClassifier as exported
+    from pyspark.ml.connect.classification import RandomForestClassifier
+    from pyspark.sql.connect import proto
+
+    assert exported is RandomForestClassifier
+    defaults = dict(featuresCol="features", labelCol="label", 
predictionCol="prediction",
+                    probabilityCol="probability", 
rawPredictionCol="rawPrediction",
+                    maxDepth=5, maxBins=32, minInstancesPerNode=1, 
minInfoGain=0.0,
+                    pruneTree=True, maxMemoryInMB=256, cacheNodeIds=False,
+                    checkpointInterval=10, impurity="gini", numTrees=20,
+                    featureSubsetStrategy="auto", seed=None, 
subsamplingRate=1.0,
+                    leafCol="", minWeightFractionPerNode=0.0, weightCol=None, 
bootstrap=True)
+    signature = inspect.signature(RandomForestClassifier)
+    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.json").read_text())
+    spark, service = mock_connect
+    for case in fixture["cases"]:
+        values = dict(featuresCol="input", labelCol="target", 
predictionCol="class",
+                      probabilityCol="probs", rawPredictionCol="votes", 
maxDepth=3,
+                      maxBins=16, minInstancesPerNode=2, minInfoGain=0.01, 
pruneTree=False,
+                      maxMemoryInMB=64, cacheNodeIds=True, 
checkpointInterval=-1,
+                      impurity="entropy", numTrees=7, 
featureSubsetStrategy="all",
+                      seed=case["seed"], subsamplingRate=0.75, 
leafCol="leaves",
+                      minWeightFractionPerNode=0.1, weightCol="weight", 
bootstrap=False)
+        if use_setters:
+            estimator = RandomForestClassifier()
+            for name, value in values.items():
+                assert getattr(estimator, "set" + name[0].upper() + 
name[1:])(value) is estimator
+        else:
+            estimator = RandomForestClassifier(**values)
+        assert estimator.setThresholds([0.25, 0.75]) is estimator
+        # The fake service returns no fitted model. Inspect the real native 
fit request.
+        with pytest.raises(Exception, match="server returned no fitted model"):
+            estimator.fit(spark.range(3))
+        request = 
proto.ExecutePlanRequest.FromString(service.execute_requests[-1])
+        fit = request.plan.command.ml_command.fit
+        assert fit.estimator.name == 
"org.apache.spark.ml.classification.RandomForestClassifier"
+        expected = 
proto.MlParams.FromString(base64.b64decode(case["params_b64"]))
+        assert fit.params == expected
diff --git a/scripts/capture_random_forest_golden.py 
b/scripts/capture_random_forest_golden.py
new file mode 100644
index 00000000..08f7b821
--- /dev/null
+++ b/scripts/capture_random_forest_golden.py
@@ -0,0 +1,73 @@
+#!/usr/bin/env python3
+"""Capture RandomForestClassifier wire parameters using official PySpark 
4.3.0."""
+
+import argparse
+import base64
+import json
+from pathlib import Path
+
+from pyspark.ml.classification import RandomForestClassifier
+from pyspark.ml.connect.serialize import serialize_ml_params
+from pyspark.sql import SparkSession
+
+
+def main():
+    parser = argparse.ArgumentParser(description=__doc__)
+    parser.add_argument("--remote", default="sc://localhost:15002")
+    parser.add_argument("--out", type=Path, 
default=Path("tests/golden/random_forest.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 = RandomForestClassifier(
+                featuresCol="input",
+                labelCol="target",
+                predictionCol="class",
+                probabilityCol="probs",
+                rawPredictionCol="votes",
+                maxDepth=3,
+                maxBins=16,
+                minInstancesPerNode=2,
+                minInfoGain=0.01,
+                pruneTree=False,
+                maxMemoryInMB=64,
+                cacheNodeIds=True,
+                checkpointInterval=-1,
+                impurity="entropy",
+                numTrees=7,
+                featureSubsetStrategy="all",
+                seed=seed,
+                subsamplingRate=0.75,
+                leafCol="leaves",
+                minWeightFractionPerNode=0.1,
+                weightCol="weight",
+                bootstrap=False,
+            ).setThresholds([0.25, 0.75])
+            params = serialize_ml_params(estimator, spark.client)
+            cases.append(
+                {
+                    "seed": seed,
+                    "params_b64": base64.b64encode(
+                        params.SerializeToString(deterministic=True)
+                    ).decode(),
+                }
+            )
+        args.out.write_text(
+            json.dumps(
+                {
+                    "source": "apache/spark v4.3.0 
pyspark.ml.classification.RandomForestClassifier",
+                    "cases": cases,
+                },
+                indent=2,
+            )
+            + "\n"
+        )
+    finally:
+        spark.stop()
+
+
+if __name__ == "__main__":
+    main()
diff --git a/tests/golden/random_forest.json b/tests/golden/random_forest.json
new file mode 100644
index 00000000..a11ffc4a
--- /dev/null
+++ b/tests/golden/random_forest.json
@@ -0,0 +1,29 @@
+{
+  "source": "apache/spark v4.3.0 
pyspark.ml.classification.RandomForestClassifier",
+  "cases": [
+    {
+      "seed": 42,
+      "params_b64": 
"Cg8KCWJvb3RzdHJhcBICGAAKEgoMY2FjaGVOb2RlSWRzEgIYAQohChJjaGVja3BvaW50SW50ZXJ2YWwSCzD///////////8BCh4KFWZlYXR1cmVTdWJzZXRTdHJhdGVneRIFagNhbGwKFgoLZmVhdHVyZXNDb2wSB2oFaW5wdXQKFQoIaW1wdXJpdHkSCWoHZW50cm9weQoUCghsYWJlbENvbBIIagZ0YXJnZXQKEwoHbGVhZkNvbBIIagZsZWF2ZXMKDQoHbWF4QmlucxICMBAKDgoIbWF4RGVwdGgSAjADChMKDW1heE1lbW9yeUluTUISAjBAChgKC21pbkluZm9HYWluEglZexSuR+F6hD8KGQoTbWluSW5zdGFuY2VzUGVyTm9kZRICMAIKJQoYbWluV2VpZ2h0RnJhY3Rpb25QZXJOb2RlEglZmpmZmZmZuT8KDgoIbnVtVHJlZXMSAjA
 [...]
+    },
+    {
+      "seed": -42,
+      "params_b64": 
"Cg8KCWJvb3RzdHJhcBICGAAKEgoMY2FjaGVOb2RlSWRzEgIYAQohChJjaGVja3BvaW50SW50ZXJ2YWwSCzD///////////8BCh4KFWZlYXR1cmVTdWJzZXRTdHJhdGVneRIFagNhbGwKFgoLZmVhdHVyZXNDb2wSB2oFaW5wdXQKFQoIaW1wdXJpdHkSCWoHZW50cm9weQoUCghsYWJlbENvbBIIagZ0YXJnZXQKEwoHbGVhZkNvbBIIagZsZWF2ZXMKDQoHbWF4QmlucxICMBAKDgoIbWF4RGVwdGgSAjADChMKDW1heE1lbW9yeUluTUISAjBAChgKC21pbkluZm9HYWluEglZexSuR+F6hD8KGQoTbWluSW5zdGFuY2VzUGVyTm9kZRICMAIKJQoYbWluV2VpZ2h0RnJhY3Rpb25QZXJOb2RlEglZmpmZmZmZuT8KDgoIbnVtVHJlZXMSAjA
 [...]
+    },
+    {
+      "seed": 2147483647,
+      "params_b64": 
"Cg8KCWJvb3RzdHJhcBICGAAKEgoMY2FjaGVOb2RlSWRzEgIYAQohChJjaGVja3BvaW50SW50ZXJ2YWwSCzD///////////8BCh4KFWZlYXR1cmVTdWJzZXRTdHJhdGVneRIFagNhbGwKFgoLZmVhdHVyZXNDb2wSB2oFaW5wdXQKFQoIaW1wdXJpdHkSCWoHZW50cm9weQoUCghsYWJlbENvbBIIagZ0YXJnZXQKEwoHbGVhZkNvbBIIagZsZWF2ZXMKDQoHbWF4QmlucxICMBAKDgoIbWF4RGVwdGgSAjADChMKDW1heE1lbW9yeUluTUISAjBAChgKC21pbkluZm9HYWluEglZexSuR+F6hD8KGQoTbWluSW5zdGFuY2VzUGVyTm9kZRICMAIKJQoYbWluV2VpZ2h0RnJhY3Rpb25QZXJOb2RlEglZmpmZmZmZuT8KDgoIbnVtVHJlZXMSAjA
 [...]
+    },
+    {
+      "seed": 2147483648,
+      "params_b64": 
"Cg8KCWJvb3RzdHJhcBICGAAKEgoMY2FjaGVOb2RlSWRzEgIYAQohChJjaGVja3BvaW50SW50ZXJ2YWwSCzD///////////8BCh4KFWZlYXR1cmVTdWJzZXRTdHJhdGVneRIFagNhbGwKFgoLZmVhdHVyZXNDb2wSB2oFaW5wdXQKFQoIaW1wdXJpdHkSCWoHZW50cm9weQoUCghsYWJlbENvbBIIagZ0YXJnZXQKEwoHbGVhZkNvbBIIagZsZWF2ZXMKDQoHbWF4QmlucxICMBAKDgoIbWF4RGVwdGgSAjADChMKDW1heE1lbW9yeUluTUISAjBAChgKC21pbkluZm9HYWluEglZexSuR+F6hD8KGQoTbWluSW5zdGFuY2VzUGVyTm9kZRICMAIKJQoYbWluV2VpZ2h0RnJhY3Rpb25QZXJOb2RlEglZmpmZmZmZuT8KDgoIbnVtVHJlZXMSAjA
 [...]
+    },
+    {
+      "seed": -2147483648,
+      "params_b64": 
"Cg8KCWJvb3RzdHJhcBICGAAKEgoMY2FjaGVOb2RlSWRzEgIYAQohChJjaGVja3BvaW50SW50ZXJ2YWwSCzD///////////8BCh4KFWZlYXR1cmVTdWJzZXRTdHJhdGVneRIFagNhbGwKFgoLZmVhdHVyZXNDb2wSB2oFaW5wdXQKFQoIaW1wdXJpdHkSCWoHZW50cm9weQoUCghsYWJlbENvbBIIagZ0YXJnZXQKEwoHbGVhZkNvbBIIagZsZWF2ZXMKDQoHbWF4QmlucxICMBAKDgoIbWF4RGVwdGgSAjADChMKDW1heE1lbW9yeUluTUISAjBAChgKC21pbkluZm9HYWluEglZexSuR+F6hD8KGQoTbWluSW5zdGFuY2VzUGVyTm9kZRICMAIKJQoYbWluV2VpZ2h0RnJhY3Rpb25QZXJOb2RlEglZmpmZmZmZuT8KDgoIbnVtVHJlZXMSAjA
 [...]
+    },
+    {
+      "seed": -2147483649,
+      "params_b64": 
"Cg8KCWJvb3RzdHJhcBICGAAKEgoMY2FjaGVOb2RlSWRzEgIYAQohChJjaGVja3BvaW50SW50ZXJ2YWwSCzD///////////8BCh4KFWZlYXR1cmVTdWJzZXRTdHJhdGVneRIFagNhbGwKFgoLZmVhdHVyZXNDb2wSB2oFaW5wdXQKFQoIaW1wdXJpdHkSCWoHZW50cm9weQoUCghsYWJlbENvbBIIagZ0YXJnZXQKEwoHbGVhZkNvbBIIagZsZWF2ZXMKDQoHbWF4QmlucxICMBAKDgoIbWF4RGVwdGgSAjADChMKDW1heE1lbW9yeUluTUISAjBAChgKC21pbkluZm9HYWluEglZexSuR+F6hD8KGQoTbWluSW5zdGFuY2VzUGVyTm9kZRICMAIKJQoYbWluV2VpZ2h0RnJhY3Rpb25QZXJOb2RlEglZmpmZmZmZuT8KDgoIbnVtVHJlZXMSAjA
 [...]
+    }
+  ]
+}


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to