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 419e893a [SPARK-61546][CONNECT] Support native BisectingKMeans 
training and prediction
419e893a is described below

commit 419e893a47d7bf3cf6d85bcc67c961ec4784fded
Author: Ruifeng Zheng <[email protected]>
AuthorDate: Thu Nov 12 23:15:04 2026 +0900

    [SPARK-61546][CONNECT] Support native BisectingKMeans training and 
prediction
    
    ### What changes were proposed in this pull request?
    
    Add native Rust `BisectingKMeans` / `BisectingKMeansModel` training and 
DataFrame cluster assignment, and expose `BisectingKMeans` through the 
Rust-backed Python Connect API. Support all eight constructor parameters and 
named setters, with corresponding Rust getters, and reuse the existing 
cached-model ownership/session checks.
    
    Add official-PySpark golden fixtures at six signed seed/integer-width 
boundaries, native offline/live tests, CI registration and compatibility 
documentation.
    
    ### Why are the changes needed?
    
    Extend native clustering support beyond KMeans to hierarchical bisecting 
K-means with Euclidean/cosine distance, instance weights and minimum divisible 
cluster sizes.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes. Rust and Rust-backed Python users can train BisectingKMeans and 
transform dense/sparse-vector DataFrames to cluster IDs. All eight PySpark 
constructor parameters and setters are supported: `featuresCol`, 
`predictionCol`, `maxIter`, `seed`, `k`, `minDivisibleClusterSize`, 
`distanceMeasure` and `weightCol`.
    
    The Python constructor matches official keyword order/defaults and 
parameter conversions. Unset values are omitted, preserving server defaults 
including `k=4`. The native surface covers construction, setters, fit and 
DataFrame transform; cluster-center/summary/cost inspection, single-vector 
prediction and persistence are outside its scope.
    
    ### How was this patch tested?
    
    - All 638 Rust library tests pass; every integration test compiles with 
default features and `wasm-udf`.
    - Five Rust live tests pass, covering independent fits/model clones, lazy 
lifetime/session isolation, weights, cosine distance, divisibility limits and 
invalid parameters/data. Cluster-partition assertions allow permuted cluster 
IDs.
    - The golden test matches every parameter against official PySpark at six 
signed/integer-width seed cases.
    - All 16 behavior cases pass with official PySpark. The native extension 
passes those same cases and two shared ownership/session tests (18 passed).
    - Native Python offline suites: 2,068 passed, 8 skipped and 14 subtests 
passed.
    - The constructor and eight named setters match official PySpark. The 
12-class SQL API introspection diff has zero missing public members.
    - Official Spark 4.3 Connect transport suite: 2,638 passed, 589 skipped 
across 87 files; zero unexpected failures.
    - Rust formatting, Ruff lint/format, Ruff exclusion and whitespace checks 
pass. Clippy passes for the core library and new test targets. Workspace and 
Python-wrapper Clippy report errors on unchanged source lines; none of the 
reported primary error sites was introduced by this patch.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Codex (GPT-6)
    
    This pull request and its description were written by Isaac.
    
    Closes #576 from zhengruifeng/add-bisecting-kmeans.
    
    Authored-by: Ruifeng Zheng <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 .github/workflows/build_python_connect.yml         |   4 +-
 crates/pyspark-rs/src/lib.rs                       |   1 +
 crates/pyspark-rs/src/ml.rs                        | 116 ++++++-
 crates/spark-connect/src/ml.rs                     | 340 +++++++++++++++++++++
 .../spark-connect/tests/bisecting_kmeans_golden.rs |  32 ++
 crates/spark-connect/tests/e2e_bisecting_kmeans.rs | 234 ++++++++++++++
 docs/compatibility.md                              |  25 ++
 python/pyspark/ml/connect/__init__.py              |   3 +-
 python/pyspark/ml/connect/clustering.py            |   4 +-
 python/tests/test_bisecting_kmeans_e2e.py          | 209 +++++++++++++
 python/tests/test_ml_e2e.py                        |   2 +
 python/tests/test_ml_offline.py                    |  60 ++++
 scripts/capture_bisecting_kmeans_golden.py         |  58 ++++
 tests/golden/bisecting_kmeans.json                 |  29 ++
 14 files changed, 1107 insertions(+), 10 deletions(-)

diff --git a/.github/workflows/build_python_connect.yml 
b/.github/workflows/build_python_connect.yml
index 0839b090..8d5af740 100644
--- a/.github/workflows/build_python_connect.yml
+++ b/.github/workflows/build_python_connect.yml
@@ -227,7 +227,7 @@ jobs:
         env:
           SPARK_REMOTE: sc://localhost:15002
           PYTHONPATH: ${{ github.workspace }}/python
-        run: python -m pytest tests/test_arrow_e2e.py tests/test_dropin_e2e.py 
tests/test_ml_e2e.py tests/test_gbt_classifier_e2e.py 
tests/test_gbt_regressor_e2e.py tests/test_naive_bayes_e2e.py -q
+        run: python -m pytest tests/test_arrow_e2e.py tests/test_dropin_e2e.py 
tests/test_ml_e2e.py tests/test_gbt_classifier_e2e.py 
tests/test_gbt_regressor_e2e.py tests/test_naive_bayes_e2e.py 
tests/test_bisecting_kmeans_e2e.py -q
 
       - name: Restart Connect server in local-cluster mode
         # Resource profiles and artifact distribution across executors can 
only be
@@ -556,7 +556,7 @@ jobs:
         run: |
           cargo test -p apache-spark-connect \
             --test e2e_functions --test e2e_columns --test e2e_dataframe \
-            --test e2e_coverage --test e2e_linear_svc --test 
e2e_linear_regression --test e2e_kmeans --test e2e_decision_tree_regressor 
--test e2e_decision_tree_classifier --test e2e_gbt_regressor --test 
e2e_naive_bayes --test e2e_gbt_classifier --test e2e_random_forest --test 
e2e_random_forest_regressor --test e2e_integration \
+            --test e2e_coverage --test e2e_linear_svc --test 
e2e_linear_regression --test e2e_kmeans --test e2e_bisecting_kmeans --test 
e2e_decision_tree_regressor --test e2e_decision_tree_classifier --test 
e2e_gbt_regressor --test e2e_naive_bayes --test e2e_gbt_classifier --test 
e2e_random_forest --test e2e_random_forest_regressor --test e2e_integration \
             --test arrow_map_input --test array_literal --test 
execute_plan_hook --test raw_relation \
             --test types_roundtrip \
             --test e2e_reattach_drop \
diff --git a/crates/pyspark-rs/src/lib.rs b/crates/pyspark-rs/src/lib.rs
index 144b136b..7ec7d03b 100644
--- a/crates/pyspark-rs/src/lib.rs
+++ b/crates/pyspark-rs/src/lib.rs
@@ -254,6 +254,7 @@ fn _pyspark(_py: Python<'_>, m: &Bound<'_, PyModule>) -> 
PyResult<()> {
     m.add_class::<ml::PyDecisionTreeRegressor>()?;
     m.add_class::<ml::PyRandomForestRegressor>()?;
     m.add_class::<ml::PyKMeans>()?;
+    m.add_class::<ml::PyBisectingKMeans>()?;
     m.add_class::<ml::PyRegressionEvaluator>()?;
     m.add_class::<ml::PyBinaryClassificationEvaluator>()?;
     m.add_class::<ml::PyPipeline>()?;
diff --git a/crates/pyspark-rs/src/ml.rs b/crates/pyspark-rs/src/ml.rs
index 4c63a917..79b4ab55 100644
--- a/crates/pyspark-rs/src/ml.rs
+++ b/crates/pyspark-rs/src/ml.rs
@@ -15,11 +15,12 @@ use pyo3::pyclass::boolean_struct::False;
 use pyo3::types::{PyDict, PyTuple, PyType};
 use pyo3::PyClass;
 use spark_connect::ml::{
-    BinaryClassificationEvaluator, CrossValidator, DecisionTreeClassifier, 
DecisionTreeRegressor,
-    Estimator, Evaluator, GBTClassifier, GBTRegressor, KMeans, 
LinearRegression, LinearSVC,
-    LogisticRegression, MaxAbsScaler, Model, 
MulticlassClassificationEvaluator, NaiveBayes, Params,
-    Pipeline, RandomForestClassifier, RandomForestRegressor, 
RegressionEvaluator, StandardScaler,
-    StringIndexer, Transformer, VectorAssembler,
+    BinaryClassificationEvaluator, BisectingKMeans, CrossValidator, 
DecisionTreeClassifier,
+    DecisionTreeRegressor, Estimator, Evaluator, GBTClassifier, GBTRegressor, 
KMeans,
+    LinearRegression, LinearSVC, LogisticRegression, MaxAbsScaler, Model,
+    MulticlassClassificationEvaluator, NaiveBayes, Params, Pipeline, 
RandomForestClassifier,
+    RandomForestRegressor, RegressionEvaluator, StandardScaler, StringIndexer, 
Transformer,
+    VectorAssembler,
 };
 use spark_connect::DataFrame;
 
@@ -2898,6 +2899,110 @@ impl PyBinaryClassificationEvaluator {
     }
 }
 
+/// Bisecting K-means fitted and cached by Spark Connect.
+#[pyclass(name = "BisectingKMeans", module = "pyspark.ml.connect.clustering")]
+pub struct PyBisectingKMeans {
+    inner: BisectingKMeans,
+    unsendable: Vec<&'static str>,
+}
+
+const BISECTING_KMEANS_PARAMS: &[(&str, Kind)] = &[
+    ("featuresCol", Kind::Str),
+    ("predictionCol", Kind::Str),
+    ("maxIter", Kind::Int),
+    ("seed", Kind::Int),
+    ("k", Kind::Int),
+    ("minDivisibleClusterSize", Kind::Float),
+    ("distanceMeasure", Kind::Str),
+    ("weightCol", Kind::Str),
+];
+
+#[pymethods]
+impl PyBisectingKMeans {
+    #[new]
+    #[pyo3(signature = (*args, **kwargs), text_signature = "(*, 
featuresCol='features', predictionCol='prediction', maxIter=20, seed=None, k=4, 
minDivisibleClusterSize=1.0, distanceMeasure='euclidean', weightCol=None)")]
+    fn new(args: &Bound<'_, PyTuple>, kwargs: Option<&Bound<'_, PyDict>>) -> 
PyResult<Self> {
+        let mut this = Self {
+            inner: BisectingKMeans::new(),
+            unsendable: Vec::new(),
+        };
+        init_params(
+            &mut this,
+            "BisectingKMeans",
+            &[],
+            BISECTING_KMEANS_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 = "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 = "setK")]
+    fn set_k<'py>(slf: Bound<'py, Self>, value: &Bound<'py, PyAny>) -> 
PyResult<Bound<'py, Self>> {
+        set_param(slf, "k", Kind::Int, value)
+    }
+
+    #[pyo3(name = "setMaxIter")]
+    fn set_max_iter<'py>(
+        slf: Bound<'py, Self>,
+        value: &Bound<'py, PyAny>,
+    ) -> PyResult<Bound<'py, Self>> {
+        set_param(slf, "maxIter", Kind::Int, value)
+    }
+
+    #[pyo3(name = "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 = "setDistanceMeasure")]
+    fn set_distance_measure<'py>(
+        slf: Bound<'py, Self>,
+        value: &Bound<'py, PyAny>,
+    ) -> PyResult<Bound<'py, Self>> {
+        set_param(slf, "distanceMeasure", Kind::Str, 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 = "setMinDivisibleClusterSize")]
+    fn set_min_divisible_cluster_size<'py>(
+        slf: Bound<'py, Self>,
+        value: &Bound<'py, PyAny>,
+    ) -> PyResult<Bound<'py, Self>> {
+        set_param(slf, "minDivisibleClusterSize", Kind::Float, value)
+    }
+
+    fn fit(slf: &Bound<'_, Self>, df: &PyDataFrame) -> PyResult<PyMLModel> {
+        fit_native(slf, df)
+    }
+}
+
 /// Pipeline estimator (chains stages by name).
 #[pyclass(name = "Pipeline", module = "pyspark.ml.connect.pipeline")]
 pub struct PyPipeline {
@@ -3077,6 +3182,7 @@ native!(
     PyDecisionTreeRegressor => DecisionTreeRegressor,
     PyRandomForestRegressor => RandomForestRegressor,
     PyKMeans => KMeans,
+    PyBisectingKMeans => BisectingKMeans,
     PyRegressionEvaluator => RegressionEvaluator,
     PyMulticlassClassificationEvaluator => MulticlassClassificationEvaluator,
     PyPipeline => Pipeline,
diff --git a/crates/spark-connect/src/ml.rs b/crates/spark-connect/src/ml.rs
index d79d2cc8..dd893521 100644
--- a/crates/spark-connect/src/ml.rs
+++ b/crates/spark-connect/src/ml.rs
@@ -4363,6 +4363,206 @@ impl Model for KMeansModel {
     }
 }
 
+/// Hierarchical bisecting K-means using Spark's JVM implementation and ML 
vectors.
+///
+/// Starts with one cluster and repeatedly splits divisible leaf clusters 
until there
+/// are k leaves or no further splits are possible. Supports Euclidean and 
cosine distance,
+/// instance weights and seeded initialization. Unset parameters use Spark's 
defaults.
+#[derive(Debug, Clone)]
+pub struct BisectingKMeans {
+    operator: MlOperator,
+    params: Params,
+}
+
+impl BisectingKMeans {
+    pub fn new() -> Self {
+        Self {
+            operator: MlOperator::new(
+                "org.apache.spark.ml.clustering.BisectingKMeans",
+                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
+    }
+
+    /// Cluster assignment output column.
+    pub fn set_prediction_col(mut self, value: &str) -> Self {
+        self.params = self.params.set_param_string("predictionCol", value);
+        self
+    }
+
+    /// Number of clusters; must be greater than 1.
+    pub fn set_k(mut self, value: i32) -> Self {
+        self.params = self.params.set_param_int32("k", value);
+        self
+    }
+
+    /// Minimum cluster size eligible for splitting: an absolute count when at 
least 1,
+    /// or a fraction of the total number of points when less than 1. Must be 
positive.
+    pub fn set_min_divisible_cluster_size(mut self, value: f64) -> Self {
+        self.params = self
+            .params
+            .set_param_double("minDivisibleClusterSize", value);
+        self
+    }
+
+    /// Maximum number of clustering iterations.
+    pub fn set_max_iter(mut self, value: i32) -> Self {
+        self.params = self.params.set_param_int32("maxIter", value);
+        self
+    }
+
+    /// Random seed for initialization.
+    pub fn set_seed(mut self, value: i64) -> Self {
+        self.params = self.params.set_param_int_narrow("seed", value);
+        self
+    }
+
+    /// Distance measure: euclidean or cosine.
+    pub fn set_distance_measure(mut self, value: &str) -> Self {
+        self.params = self.params.set_param_string("distanceMeasure", value);
+        self
+    }
+
+    /// Optional instance weight column.
+    pub fn set_weight_col(mut self, value: &str) -> Self {
+        self.params = self.params.set_param_string("weightCol", value);
+        self
+    }
+
+    /// The feature vector column (default: "features").
+    pub fn feature_col(&self) -> &str {
+        self.params.string_or("featuresCol", "features")
+    }
+
+    /// The cluster assignment output column (default: "prediction").
+    pub fn prediction_col(&self) -> &str {
+        self.params.string_or("predictionCol", "prediction")
+    }
+
+    /// The desired number of leaf clusters (default: 4).
+    pub fn k(&self) -> i32 {
+        self.params.int_or("k", 4)
+    }
+
+    /// The minimum divisible cluster size (default: 1.0).
+    pub fn min_divisible_cluster_size(&self) -> f64 {
+        self.params.double_or("minDivisibleClusterSize", 1.0)
+    }
+
+    /// The maximum number of clustering iterations (default: 20).
+    pub fn max_iter(&self) -> i32 {
+        self.params.int_or("maxIter", 20)
+    }
+
+    /// 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 distance measure (default: "euclidean").
+    pub fn distance_measure(&self) -> &str {
+        self.params.string_or("distanceMeasure", "euclidean")
+    }
+
+    /// The instance weight column, if one is set.
+    pub fn weight_col(&self) -> Option<&str> {
+        self.params.string_opt("weightCol")
+    }
+
+    fn model_from_info(
+        &self,
+        info: proto::ml_command_result::MlOperatorInfo,
+        session: &SparkSession,
+    ) -> spark_connect_core::error::Result<BisectingKMeansModel> {
+        let cached = CachedModel::from_info(&info, session, 
"BisectingKMeans")?;
+        Ok(BisectingKMeansModel {
+            operator: MlOperator::with_uid(
+                "org.apache.spark.ml.clustering.BisectingKMeansModel",
+                info.uid.as_deref().unwrap_or(&self.operator.uid),
+                OperatorType::Model,
+            ),
+            params: self.params.clone(),
+            cached,
+        })
+    }
+}
+
+impl Default for BisectingKMeans {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl Estimator for BisectingKMeans {
+    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 bisecting K-means 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 BisectingKMeansModel {
+    operator: MlOperator,
+    params: Params,
+    cached: CachedModel,
+}
+
+impl Transformer for BisectingKMeansModel {
+    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 BisectingKMeansModel {
+    fn clone_box(&self) -> Box<dyn Model> {
+        Box::new(self.clone())
+    }
+}
+
 /// RegressionEvaluator: evaluates regression models.
 #[derive(Debug, Clone)]
 pub struct RegressionEvaluator {
@@ -5572,6 +5772,144 @@ mod tests {
         assert!(model.clone_box().transform(&df).is_ok());
     }
 
+    #[test]
+    fn bisecting_kmeans_getters_follow_defaults_builders_and_mutable_params() {
+        let mut estimator = BisectingKMeans::default();
+        assert_eq!(estimator.feature_col(), "features");
+        assert_eq!(estimator.prediction_col(), "prediction");
+        assert_eq!(estimator.max_iter(), 20);
+        assert_eq!(estimator.seed(), None);
+        assert_eq!(estimator.k(), 4);
+        assert_eq!(estimator.min_divisible_cluster_size(), 1.0);
+        assert_eq!(estimator.distance_measure(), "euclidean");
+        assert_eq!(estimator.weight_col(), None);
+        let built = BisectingKMeans::new()
+            .set_feature_col("input")
+            .set_prediction_col("cluster")
+            .set_max_iter(30)
+            .set_seed(1_i64 << 33)
+            .set_k(3)
+            .set_min_divisible_cluster_size(0.1)
+            .set_distance_measure("cosine")
+            .set_weight_col("weight");
+        *estimator.params_mut() = estimator
+            .params()
+            .clone()
+            .set_param_string("featuresCol", "input");
+        assert_eq!(estimator.feature_col(), "input");
+        assert_eq!(built.feature_col(), estimator.feature_col());
+        *estimator.params_mut() = estimator
+            .params()
+            .clone()
+            .set_param_string("predictionCol", "cluster");
+        assert_eq!(estimator.prediction_col(), "cluster");
+        assert_eq!(built.prediction_col(), estimator.prediction_col());
+        *estimator.params_mut() = 
estimator.params().clone().set_param_int32("maxIter", 30);
+        assert_eq!(estimator.max_iter(), 30);
+        assert_eq!(built.max_iter(), estimator.max_iter());
+        *estimator.params_mut() = estimator
+            .params()
+            .clone()
+            .set_param_int_narrow("seed", 1_i64 << 33);
+        assert_eq!(estimator.seed(), Some(1_i64 << 33));
+        assert_eq!(built.seed(), estimator.seed());
+        *estimator.params_mut() = 
estimator.params().clone().set_param_int32("k", 3);
+        assert_eq!(estimator.k(), 3);
+        assert_eq!(built.k(), estimator.k());
+        *estimator.params_mut() = estimator
+            .params()
+            .clone()
+            .set_param_double("minDivisibleClusterSize", 0.1);
+        assert_eq!(estimator.min_divisible_cluster_size(), 0.1);
+        assert_eq!(
+            built.min_divisible_cluster_size(),
+            estimator.min_divisible_cluster_size()
+        );
+        *estimator.params_mut() = estimator
+            .params()
+            .clone()
+            .set_param_string("distanceMeasure", "cosine");
+        assert_eq!(estimator.distance_measure(), "cosine");
+        assert_eq!(built.distance_measure(), estimator.distance_measure());
+        *estimator.params_mut() = estimator
+            .params()
+            .clone()
+            .set_param_string("weightCol", "weight");
+        assert_eq!(estimator.weight_col(), Some("weight"));
+        assert_eq!(built.weight_col(), estimator.weight_col());
+        assert_eq!(built.params().to_proto(), estimator.params().to_proto());
+        assert!(estimator.operator_mut().uid.starts_with("BisectingKMeans_"));
+    }
+
+    #[test]
+    fn bisecting_kmeans_validates_fitted_references_and_model_metadata() {
+        let session = offline_session();
+        let estimator = 
BisectingKMeans::default().set_prediction_col("cluster");
+        assert_eq!(
+            estimator.operator().name,
+            "org.apache.spark.ml.clustering.BisectingKMeans"
+        );
+        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-bisecting-kmeans".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.clustering.BisectingKMeansModel"
+        );
+        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-bisecting-kmeans".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 kmeans_validates_fitted_references_and_model_metadata() {
         let session = offline_session();
@@ -6875,6 +7213,8 @@ mod tests {
         ] {
             let kmeans = KMeans::new().set_seed(seed);
             assert_eq!(sent(kmeans.params()), Some(expected.clone()));
+            let bkm = BisectingKMeans::new().set_seed(seed);
+            assert_eq!(sent(bkm.params()), Some(expected.clone()));
             let forest = RandomForestClassifier::new().set_seed(seed);
             assert_eq!(sent(forest.params()), Some(expected.clone()));
             let tree = DecisionTreeClassifier::new().set_seed(seed);
diff --git a/crates/spark-connect/tests/bisecting_kmeans_golden.rs 
b/crates/spark-connect/tests/bisecting_kmeans_golden.rs
new file mode 100644
index 00000000..2125ae73
--- /dev/null
+++ b/crates/spark-connect/tests/bisecting_kmeans_golden.rs
@@ -0,0 +1,32 @@
+//! Match all BisectingKMeans parameter encodings and integer seed boundaries 
to PySpark.
+use base64::{engine::general_purpose::STANDARD, Engine};
+use prost::Message;
+use spark_connect::ml::{BisectingKMeans, Estimator};
+
+#[test]
+fn bisecting_kmeans_parameters_match_official_pyspark() {
+    let fixture: serde_json::Value =
+        
serde_json::from_str(include_str!("../../../tests/golden/bisecting_kmeans.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 = BisectingKMeans::new()
+            .set_feature_col("input")
+            .set_prediction_col("cluster")
+            .set_k(3)
+            .set_max_iter(50)
+            .set_seed(seed)
+            .set_min_divisible_cluster_size(0.25)
+            .set_distance_measure("cosine")
+            .set_weight_col("weight");
+        assert_eq!(estimator.params().to_proto(), expected, "seed {seed}");
+    }
+    assert!(BisectingKMeans::default()
+        .params()
+        .to_proto()
+        .params
+        .is_empty());
+}
diff --git a/crates/spark-connect/tests/e2e_bisecting_kmeans.rs 
b/crates/spark-connect/tests/e2e_bisecting_kmeans.rs
new file mode 100644
index 00000000..7fcf453e
--- /dev/null
+++ b/crates/spark-connect/tests/e2e_bisecting_kmeans.rs
@@ -0,0 +1,234 @@
+//! Native BisectingKMeans tests. Set SPARK_REMOTE to run against a live 
Connect server.
+mod common;
+
+use common::live_session;
+use spark_connect::column::{col, lit_double};
+use spark_connect::expression::Expression;
+use spark_connect::ml::{BisectingKMeans, Estimator};
+use spark_connect::{Column, DataFrame};
+
+fn vectorize(df: DataFrame, name: &str) -> DataFrame {
+    df.with_column(
+        name,
+        Column::new(Expression::function(
+            "array_to_vector",
+            vec![col("xs").expression().clone()],
+        )),
+    )
+}
+
+fn predictions(df: DataFrame, name: &str) -> Vec<i64> {
+    df.order_by(vec![col("id").asc().expression().clone()])
+        .select([col(name)])
+        .collect()
+        .unwrap()
+        .into_iter()
+        .map(|r| r.get(0).unwrap().as_i64().unwrap())
+        .collect()
+}
+
+// Cluster numbers may be permuted without changing the clustering.
+fn assert_partition(actual: &[i64], expected: &[i64]) {
+    assert_eq!(actual.len(), expected.len());
+    for i in 0..actual.len() {
+        for j in 0..actual.len() {
+            assert_eq!(
+                actual[i] == actual[j],
+                expected[i] == expected[j],
+                "{actual:?}"
+            );
+        }
+    }
+}
+
+#[test]
+fn bisecting_kmeans_learns_distinct_models_and_keeps_lazy_predictions_alive() {
+    let Some(s) = live_session() else {
+        return;
+    };
+    let training = vectorize(
+        s.sql(
+            "SELECT array(CAST(x AS DOUBLE)) AS xs, 1.0D AS weight
+         FROM VALUES (9), (10), (11), (29), (30), (31) AS t(x)",
+        )
+        .unwrap(),
+        "input",
+    );
+    let shifted = vectorize(
+        s.sql(
+            "SELECT array(CAST(x AS DOUBLE)) AS xs, 1.0D AS weight
+         FROM VALUES (29), (30), (31), (49), (50), (51) AS t(x)",
+        )
+        .unwrap(),
+        "input",
+    );
+    let held_out = vectorize(
+        s.sql(
+            "SELECT id, array(CAST(x AS DOUBLE)) AS xs
+         FROM VALUES (0,10), (1,19), (2,30), (3,41), (4,50) AS t(id,x)",
+        )
+        .unwrap(),
+        "input",
+    );
+    let mut estimator = BisectingKMeans::new()
+        .set_feature_col("input")
+        .set_prediction_col("cluster")
+        .set_k(2)
+        .set_min_divisible_cluster_size(1.0)
+        .set_max_iter(50)
+        .set_seed(42)
+        .set_distance_measure("euclidean")
+        .set_weight_col("weight");
+    let mut first = estimator.fit(&training).unwrap();
+    let mut second = estimator.fit(&shifted).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("cluster")]);
+    drop(first);
+    let original = predictions(cloned.transform(&held_out).unwrap(), 
"cluster");
+    assert_partition(&original, &[0, 0, 1, 1, 1]);
+    let mut repeated = estimator.fit(&training).unwrap();
+    assert_eq!(
+        original,
+        predictions(repeated.transform(&held_out).unwrap(), "cluster")
+    );
+    drop(cloned);
+    assert_partition(&predictions(delayed, "cluster"), &[0, 0, 1, 1, 1]);
+    assert_partition(
+        &predictions(second.transform(&held_out).unwrap(), "cluster"),
+        &[0, 0, 0, 1, 1],
+    );
+    assert!(second
+        .transform(&s.new_session().range(1).unwrap())
+        .is_err());
+    s.stop().unwrap();
+}
+
+#[test]
+fn bisecting_kmeans_weights_move_a_cluster_boundary() {
+    let Some(s) = live_session() else {
+        return;
+    };
+    let training=vectorize(s.sql("SELECT array(x) xs, weight FROM VALUES 
(-10.0D,1.0D),(-9.0D,1.0D),(-8.0D,1.0D),(2.0D,100.0D),(3.0D,1.0D),(4.0D,1.0D),(10.0D,1.0D),(11.0D,1.0D)
 AS t(x,weight)").unwrap(),"features");
+    let held_out = vectorize(
+        s.sql(
+            "SELECT id, array(x) xs FROM VALUES 
(0,-9.0D),(1,-2.0D),(2,2.0D),(3,11.0D) AS t(id,x)",
+        )
+        .unwrap(),
+        "features",
+    );
+    let mut plain = BisectingKMeans::new()
+        .set_k(2)
+        .set_seed(42)
+        .fit(&training)
+        .unwrap();
+    let mut weighted = BisectingKMeans::new()
+        .set_k(2)
+        .set_seed(42)
+        .set_weight_col("weight")
+        .fit(&training)
+        .unwrap();
+    assert_partition(
+        &predictions(plain.transform(&held_out).unwrap(), "prediction"),
+        &[0, 0, 1, 1],
+    );
+    assert_partition(
+        &predictions(weighted.transform(&held_out).unwrap(), "prediction"),
+        &[0, 1, 1, 1],
+    );
+}
+
+#[test]
+fn bisecting_kmeans_divisibility_limits_the_number_of_leaf_clusters() {
+    let Some(s) = live_session() else {
+        return;
+    };
+    // The nonzero centroid avoids coincident initial split centers.
+    let data=vectorize(s.sql("SELECT id, array(x,y) xs FROM VALUES 
(0,9.0D,20.0D),(1,11.0D,20.0D),(2,9.0D,40.0D),(3,11.0D,40.0D),(4,29.0D,20.0D),(5,31.0D,20.0D),(6,29.0D,40.0D),(7,31.0D,40.0D)
 AS t(id,x,y)").unwrap(),"features");
+    for (size, expected) in [(1.0, 4), (0.75, 2), (9.0, 1)] {
+        let mut estimator = BisectingKMeans::new().set_seed(42);
+        if size != 1.0 {
+            estimator = 
estimator.set_k(4).set_min_divisible_cluster_size(size);
+        }
+        let mut model = estimator.fit(&data).unwrap();
+        let labels = predictions(model.transform(&data).unwrap(), 
"prediction");
+        assert_eq!(
+            labels
+                .iter()
+                .copied()
+                .collect::<std::collections::HashSet<_>>()
+                .len(),
+            expected
+        );
+    }
+}
+
+#[test]
+fn bisecting_kmeans_cosine_distance_groups_directions_across_magnitudes() {
+    let Some(s) = live_session() else {
+        return;
+    };
+    let training=vectorize(s.sql("SELECT array(x,y) xs FROM VALUES 
(1.0D,0.0D),(5.0D,0.1D),(0.0D,1.0D),(0.1D,5.0D),(-1.0D,-1.0D),(-5.0D,-4.0D) AS 
t(x,y)").unwrap(),"features");
+    let held_out=vectorize(s.sql("SELECT id, array(x,y) xs FROM VALUES 
(0,100.0D,0.0D),(1,0.01D,0.0D),(2,0.0D,100.0D),(3,0.0D,0.01D),(4,-100.0D,-100.0D),(5,-0.01D,-0.01D)
 AS t(id,x,y)").unwrap(),"features");
+    let mut model = BisectingKMeans::new()
+        .set_k(3)
+        .set_seed(42)
+        .set_distance_measure("cosine")
+        .fit(&training)
+        .unwrap();
+    assert_partition(
+        &predictions(model.transform(&held_out).unwrap(), "prediction"),
+        &[0, 0, 1, 1, 2, 2],
+    );
+}
+
+#[test]
+fn bisecting_kmeans_rejects_invalid_parameters_and_data() {
+    let Some(s) = live_session() else {
+        return;
+    };
+    let training=vectorize(s.sql("SELECT array(x,y) xs FROM VALUES 
(1.0D,1.0D),(2.0D,2.0D),(9.0D,9.0D),(10.0D,10.0D) AS 
t(x,y)").unwrap(),"features");
+    for mut estimator in [
+        BisectingKMeans::new().set_k(1),
+        BisectingKMeans::new().set_max_iter(-1),
+        BisectingKMeans::new().set_min_divisible_cluster_size(-1.0),
+        BisectingKMeans::new().set_distance_measure("unknown"),
+    ] {
+        assert!(estimator.fit(&training).is_err());
+    }
+    assert!(BisectingKMeans::new()
+        .set_weight_col("weight")
+        .fit(&training.with_column("weight", lit_double(-1.0)))
+        .is_err());
+    assert!(BisectingKMeans::new()
+        .fit(&training.with_column("features", lit_double(1.0)))
+        .is_err());
+    let zero = vectorize(
+        s.sql("SELECT array(0.0D,0.0D) xs FROM range(4)").unwrap(),
+        "features",
+    );
+    assert!(BisectingKMeans::new()
+        .set_distance_measure("cosine")
+        .fit(&zero)
+        .is_err());
+    let empty = vectorize(
+        s.sql("SELECT array(1.0D,1.0D) xs WHERE false").unwrap(),
+        "features",
+    );
+    assert!(BisectingKMeans::new().fit(&empty).is_err());
+}
diff --git a/docs/compatibility.md b/docs/compatibility.md
index 1a323813..1c33c9ce 100644
--- a/docs/compatibility.md
+++ b/docs/compatibility.md
@@ -521,3 +521,28 @@ This native surface covers construction, parameter 
setters, fit and DataFrame
 transform. Model coefficient/statistic inspection, single-vector prediction and
 persistence are outside this surface. The vendored `pyspark.ml.classification`
 API continues to use its existing implementation.
+
+
+## Native BisectingKMeans
+
+The Rust `ml::BisectingKMeans` and `ml::BisectingKMeansModel` support training 
and
+DataFrame cluster assignment through Spark Connect's cached-model protocol. 
Python
+exports the native estimator from `pyspark.ml.connect` and
+`pyspark.ml.connect.clustering`; `fit` returns the shared native `MLModel`.
+
+All eight constructor parameters and named setters are supported: 
`featuresCol`,
+`predictionCol`, `maxIter`, `seed`, `k`, `minDivisibleClusterSize`, 
`distanceMeasure`
+and `weightCol`. Rust also provides parameter getters. The keyword-only Python
+constructor matches official PySpark's order/defaults and parameter 
conversions.
+Unset parameters are omitted so the server uses its defaults, including `k=4`.
+
+Live tests cover hierarchical splitting, absolute/fractional minimum divisible
+cluster sizes (which may produce fewer than `k` leaves), instance weights,
+Euclidean/cosine distance, sparse/dense inputs, seeded reproducibility, 
independent
+fits, session isolation and lazy model lifetime. Golden fixtures compare all 
eight
+parameters at six signed seed/integer-width boundaries with official PySpark.
+
+This native API covers construction, setters, fit and DataFrame transform.
+Cluster-center/summary/cost inspection, single-vector prediction and 
persistence
+are outside this surface. The vendored `pyspark.ml.clustering` API retains its
+existing implementation.
diff --git a/python/pyspark/ml/connect/__init__.py 
b/python/pyspark/ml/connect/__init__.py
index 167fbfa3..7acf6aa3 100644
--- a/python/pyspark/ml/connect/__init__.py
+++ b/python/pyspark/ml/connect/__init__.py
@@ -25,7 +25,7 @@ from pyspark.ml.connect.regression import (
     LinearRegression,
     RandomForestRegressor,
 )
-from pyspark.ml.connect.clustering import KMeans
+from pyspark.ml.connect.clustering import BisectingKMeans, KMeans
 from pyspark.ml.connect.evaluation import (
     RegressionEvaluator,
     BinaryClassificationEvaluator,
@@ -67,6 +67,7 @@ __all__ = [
     "DecisionTreeRegressor",
     "RandomForestRegressor",
     "KMeans",
+    "BisectingKMeans",
     "RegressionEvaluator",
     "BinaryClassificationEvaluator",
     "MulticlassClassificationEvaluator",
diff --git a/python/pyspark/ml/connect/clustering.py 
b/python/pyspark/ml/connect/clustering.py
index 867c288c..b2ca6c17 100644
--- a/python/pyspark/ml/connect/clustering.py
+++ b/python/pyspark/ml/connect/clustering.py
@@ -1,4 +1,4 @@
 """Native clustering estimators backed by Spark Connect's JVM ML API."""
-from pyspark._pyspark import KMeans
+from pyspark._pyspark import BisectingKMeans, KMeans
 
-__all__ = ["KMeans"]
+__all__ = ["BisectingKMeans", "KMeans"]
diff --git a/python/tests/test_bisecting_kmeans_e2e.py 
b/python/tests/test_bisecting_kmeans_e2e.py
new file mode 100644
index 00000000..b2db90c8
--- /dev/null
+++ b/python/tests/test_bisecting_kmeans_e2e.py
@@ -0,0 +1,209 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+"""Native BisectingKMeans behaviors, also run with official PySpark."""
+
+import gc
+import os
+
+import pytest
+from pyspark.ml.connect.functions import array_to_vector
+from pyspark.ml.linalg import Vectors
+from pyspark.sql import SparkSession
+from pyspark.sql import functions as F
+
+
[email protected]
+def session():
+    remote = os.environ.get("SPARK_REMOTE")
+    if not remote:
+        pytest.skip("SPARK_REMOTE is required for live tests")
+    spark = SparkSession.builder.remote(remote).getOrCreate()
+    try:
+        yield spark
+    finally:
+        spark.stop()
+
+
+def _estimator():
+    try:
+        from pyspark.ml.connect.clustering import BisectingKMeans
+    except ImportError:
+        from pyspark.ml.clustering import BisectingKMeans
+    return BisectingKMeans
+
+
+def _vectors(session, sql, name="features"):
+    return session.sql(sql).withColumn(name, array_to_vector("xs"))
+
+
+def _predictions(model, frame, name="prediction"):
+    return [r[0] for r in 
model.transform(frame).orderBy("id").select(name).collect()]
+
+
+def _assert_partition(actual, expected):
+    assert len(actual) == len(expected)
+    for i in range(len(actual)):
+        for j in range(len(actual)):
+            assert (actual[i] == actual[j]) == (expected[i] == expected[j]), 
actual
+
+
+def _quadrants(session):
+    return _vectors(
+        session,
+        "SELECT id, array(x,y) xs FROM VALUES "
+        "(0,9.0D,20.0D),(1,11.0D,20.0D),(2,9.0D,40.0D),(3,11.0D,40.0D),"
+        "(4,29.0D,20.0D),(5,31.0D,20.0D),(6,29.0D,40.0D),(7,31.0D,40.0D) AS 
t(id,x,y)",
+    )
+
+
[email protected]("use_setters", [False, True], ids=["constructor", 
"setters"])
+def 
test_bisecting_kmeans_learns_independent_models_and_retains_lazy_predictions(
+    session, use_setters
+):
+    BisectingKMeans = _estimator()
+    training = _vectors(
+        session,
+        "SELECT array(CAST(x AS DOUBLE)) xs, 1.0D weight "
+        "FROM VALUES (10),(11),(12),(28),(29),(30) AS t(x)",
+        "input",
+    )
+    shifted = _vectors(
+        session,
+        "SELECT array(CAST(x AS DOUBLE)) xs, 1.0D weight "
+        "FROM VALUES (30),(31),(32),(48),(49),(50) AS t(x)",
+        "input",
+    )
+    points = [11.0, 19.0, 29.0, 41.0, 49.0]
+    held_out = session.createDataFrame(
+        [
+            (i, Vectors.sparse(1, {0: x})) if i % 2 else (i, 
Vectors.dense([x]))
+            for i, x in enumerate(points)
+        ],
+        ["id", "input"],
+    )
+    values = dict(
+        featuresCol="input",
+        predictionCol="cluster",
+        maxIter=30,
+        seed=42,
+        k=2,
+        minDivisibleClusterSize=1.0,
+        distanceMeasure="euclidean",
+        weightCol="weight",
+    )
+    if use_setters:
+        estimator = BisectingKMeans()
+        for name, value in values.items():
+            assert getattr(estimator, "set" + name[0].upper() + 
name[1:])(value) is estimator
+    else:
+        estimator = BisectingKMeans(**values)
+    first = estimator.fit(training)
+    second = estimator.fit(shifted)
+    lazy = first.transform(held_out).orderBy("id").select("cluster")
+    estimator.setPredictionCol("changed")
+    del first, estimator
+    gc.collect()
+    _assert_partition([r[0] for r in lazy.collect()], [0, 0, 1, 1, 1])
+    _assert_partition(_predictions(second, held_out, "cluster"), [0, 0, 0, 1, 
1])
+
+
[email protected]("size,clusters", [(1.0, 4), (0.75, 2), (9.0, 1)])
+def 
test_bisecting_kmeans_divisibility_and_default_k_control_leaf_count(session, 
size, clusters):
+    frame = _quadrants(session)
+    options = dict(seed=42)
+    if size != 1.0:
+        options.update(k=4, minDivisibleClusterSize=size)
+    values = _predictions(_estimator()(**options).fit(frame), frame)
+    assert len(set(values)) == clusters
+
+
+def test_bisecting_kmeans_cosine_distance_ignores_vector_magnitude(session):
+    training = _vectors(
+        session,
+        "SELECT array(x,y) xs FROM VALUES "
+        "(1.0D,0.0D),(5.0D,0.1D),(0.0D,1.0D),(0.1D,5.0D),"
+        "(-1.0D,-1.0D),(-5.0D,-4.0D) AS t(x,y)",
+    )
+    held_out = session.createDataFrame(
+        [
+            (i, Vectors.sparse(2, {j: v for j, v in enumerate(x) if v}))
+            for i, x in enumerate(
+                [
+                    [100.0, 0.0],
+                    [0.01, 0.0],
+                    [0.0, 100.0],
+                    [0.0, 0.01],
+                    [-100.0, -100.0],
+                    [-0.01, -0.01],
+                ]
+            )
+        ],
+        ["id", "features"],
+    )
+    model = _estimator()(k=3, seed=42, distanceMeasure="cosine").fit(training)
+    _assert_partition(_predictions(model, held_out), [0, 0, 1, 1, 2, 2])
+
+
+def test_bisecting_kmeans_instance_weights_move_a_cluster_boundary(session):
+    frame = _vectors(
+        session,
+        "SELECT array(x) xs, weight FROM VALUES "
+        "(-10.0D,1.0D),(-9.0D,1.0D),(-8.0D,1.0D),(2.0D,100.0D),"
+        "(3.0D,1.0D),(4.0D,1.0D),(10.0D,1.0D),(11.0D,1.0D) AS t(x,weight)",
+    )
+    held_out = _vectors(
+        session,
+        "SELECT id, array(x) xs FROM VALUES 
(0,-9.0D),(1,-2.0D),(2,2.0D),(3,11.0D) AS t(id,x)",
+    )
+    plain = _estimator()(k=2, seed=42).fit(frame)
+    weighted = _estimator()(k=2, seed=42, weightCol="weight").fit(frame)
+    _assert_partition(_predictions(plain, held_out), [0, 0, 1, 1])
+    _assert_partition(_predictions(weighted, held_out), [0, 1, 1, 1])
+
+
+def test_bisecting_kmeans_seeded_fits_are_reproducible(session):
+    frame = _quadrants(session)
+    estimator = _estimator()(k=3, seed=2**33)
+    assert _predictions(estimator.fit(frame), frame) == 
_predictions(estimator.fit(frame), frame)
+
+
[email protected](
+    "case", ["k", "iterations", "size", "distance", "weight", "nonvector", 
"zero", "empty"]
+)
+def test_bisecting_kmeans_rejects_invalid_parameters_and_data(session, case):
+    estimator = _estimator()(k=2, seed=42)
+    frame = _quadrants(session)
+    if case == "k":
+        estimator.setK(1)
+    elif case == "iterations":
+        estimator.setMaxIter(-1)
+    elif case == "size":
+        estimator.setMinDivisibleClusterSize(-1.0)
+    elif case == "distance":
+        estimator.setDistanceMeasure("unknown")
+    elif case == "weight":
+        estimator.setWeightCol("weight")
+        frame = frame.withColumn("weight", F.lit(-1.0))
+    elif case == "nonvector":
+        frame = frame.withColumn("features", F.lit(1.0))
+    elif case == "zero":
+        estimator.setDistanceMeasure("cosine")
+        frame = frame.withColumn("features", 
array_to_vector(F.array(F.lit(0.0), F.lit(0.0))))
+    else:
+        frame = frame.filter("false")
+    with pytest.raises(Exception):
+        estimator.fit(frame).transform(frame).collect()
diff --git a/python/tests/test_ml_e2e.py b/python/tests/test_ml_e2e.py
index c709678d..8d3338ac 100644
--- a/python/tests/test_ml_e2e.py
+++ b/python/tests/test_ml_e2e.py
@@ -246,6 +246,7 @@ def _native_estimators():
     # Every native pyspark.ml.connect estimator, with the class of the model 
that the server
     # caches for its fit, and data that it fits.
     from pyspark.ml.connect import (
+        BisectingKMeans,
         DecisionTreeClassifier,
         DecisionTreeRegressor,
         GBTClassifier,
@@ -264,6 +265,7 @@ def _native_estimators():
 
     ml = "org.apache.spark.ml."
     return [
+        (BisectingKMeans(k=2, seed=1), ml + "clustering.BisectingKMeansModel"),
         (NaiveBayes(), ml + "classification.NaiveBayesModel"),
         (GBTRegressor(maxIter=2), ml + "regression.GBTRegressionModel"),
         (GBTClassifier(maxIter=2), ml + 
"classification.GBTClassificationModel"),
diff --git a/python/tests/test_ml_offline.py b/python/tests/test_ml_offline.py
index 68292648..4b4d04ee 100644
--- a/python/tests/test_ml_offline.py
+++ b/python/tests/test_ml_offline.py
@@ -534,6 +534,10 @@ _NATIVE_PARAMS = {
         seed="int", numTrees="int", featureSubsetStrategy="str", leafCol="str",
         minWeightFractionPerNode="float", weightCol="str", bootstrap="bool",
     ),
+    "BisectingKMeans": dict(
+        featuresCol="str", predictionCol="str", maxIter="int", seed="int", 
k="int",
+        minDivisibleClusterSize="float", distanceMeasure="str", 
weightCol="str",
+    ),
     "KMeans": dict(
         featuresCol="str", predictionCol="str", k="int", initMode="str", 
initSteps="int",
         tol="float", maxIter="int", seed="int", distanceMeasure="str", 
weightCol="str",
@@ -2746,6 +2750,62 @@ def 
test_decision_tree_regressor_native_parameters_match_official_fixture(ml_moc
         assert params == 
pb2.MlParams.FromString(base64.b64decode(case["params_b64"]))
 
 
[email protected]("use_setters", [False, True], ids=["constructor", 
"setters"])
+def test_bisecting_kmeans_native_parameters_match_official_fixture(ml_mock, 
use_setters):
+    import base64
+    import inspect
+    import json
+    from pathlib import Path
+
+    from pyspark import _pyspark as native
+    from pyspark.ml.connect import BisectingKMeans as exported
+    from pyspark.ml.connect.clustering import BisectingKMeans
+
+    assert exported is BisectingKMeans is native.BisectingKMeans
+    defaults = dict(
+        featuresCol="features",
+        predictionCol="prediction",
+        maxIter=20,
+        seed=None,
+        k=4,
+        minDivisibleClusterSize=1.0,
+        distanceMeasure="euclidean",
+        weightCol=None,
+    )
+    signature = inspect.signature(BisectingKMeans)
+    assert list(signature.parameters) == list(defaults)
+    for name, value in defaults.items():
+        assert signature.parameters[name].kind == 
inspect.Parameter.KEYWORD_ONLY
+        assert signature.parameters[name].default == value
+    fixture = json.loads(
+        (Path(__file__).resolve().parents[2] / 
"tests/golden/bisecting_kmeans.json").read_text()
+    )
+    spark, service = ml_mock
+    models = []
+    _, params = _native_request(spark, service, BisectingKMeans(), models)
+    assert params == pb2.MlParams()
+    for case in fixture["cases"]:
+        values = dict(
+            featuresCol="input",
+            predictionCol="cluster",
+            maxIter=50,
+            seed=case["seed"],
+            k=3,
+            minDivisibleClusterSize=0.25,
+            distanceMeasure="cosine",
+            weightCol="weight",
+        )
+        if use_setters:
+            estimator = BisectingKMeans()
+            for name, value in values.items():
+                assert getattr(estimator, "set" + name[0].upper() + 
name[1:])(value) is estimator
+        else:
+            estimator = BisectingKMeans(**values)
+        operator, params = _native_request(spark, service, estimator, models)
+        assert operator.name == 
"org.apache.spark.ml.clustering.BisectingKMeans"
+        assert params == 
pb2.MlParams.FromString(base64.b64decode(case["params_b64"]))
+
+
 @pytest.mark.parametrize("use_setters", [False, True], ids=["constructor", 
"setters"])
 def test_naive_bayes_native_parameters_match_official_fixture(ml_mock, 
use_setters):
     import base64
diff --git a/scripts/capture_bisecting_kmeans_golden.py 
b/scripts/capture_bisecting_kmeans_golden.py
new file mode 100644
index 00000000..2ce5c977
--- /dev/null
+++ b/scripts/capture_bisecting_kmeans_golden.py
@@ -0,0 +1,58 @@
+#!/usr/bin/env python3
+"""Capture BisectingKMeans parameter wire goldens using official PySpark 
4.3.0."""
+
+import argparse
+import base64
+import json
+from pathlib import Path
+
+from pyspark.ml.clustering import BisectingKMeans
+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/bisecting_kmeans.json"))
+    args = parser.parse_args()
+    spark = SparkSession.builder.remote(args.remote).getOrCreate()
+    spark.release_session_on_close = False
+    try:
+        cases = []
+        for seed in [42, -42, 2**31 - 1, 2**31, -(2**31), -(2**31) - 1]:
+            estimator = BisectingKMeans(
+                featuresCol="input",
+                predictionCol="cluster",
+                k=3,
+                maxIter=50,
+                seed=seed,
+                minDivisibleClusterSize=0.25,
+                distanceMeasure="cosine",
+                weightCol="weight",
+            )
+            params = serialize_ml_params(estimator, spark.client)
+            cases.append(
+                {
+                    "seed": seed,
+                    "params_b64": base64.b64encode(
+                        params.SerializeToString(deterministic=True)
+                    ).decode(),
+                }
+            )
+        args.out.write_text(
+            json.dumps(
+                {
+                    "source": "apache/spark v4.3.0 
pyspark.ml.clustering.BisectingKMeans",
+                    "cases": cases,
+                },
+                indent=2,
+            )
+            + "\n"
+        )
+    finally:
+        spark.stop()
+
+
+if __name__ == "__main__":
+    main()
diff --git a/tests/golden/bisecting_kmeans.json 
b/tests/golden/bisecting_kmeans.json
new file mode 100644
index 00000000..9d8869eb
--- /dev/null
+++ b/tests/golden/bisecting_kmeans.json
@@ -0,0 +1,29 @@
+{
+  "source": "apache/spark v4.3.0 pyspark.ml.clustering.BisectingKMeans",
+  "cases": [
+    {
+      "seed": 42,
+      "params_b64": 
"ChsKD2Rpc3RhbmNlTWVhc3VyZRIIagZjb3NpbmUKFgoLZmVhdHVyZXNDb2wSB2oFaW5wdXQKBwoBaxICMAMKDQoHbWF4SXRlchICMDIKJAoXbWluRGl2aXNpYmxlQ2x1c3RlclNpemUSCVkAAAAAAADQPwoaCg1wcmVkaWN0aW9uQ29sEglqB2NsdXN0ZXIKCgoEc2VlZBICMCoKFQoJd2VpZ2h0Q29sEghqBndlaWdodA=="
+    },
+    {
+      "seed": -42,
+      "params_b64": 
"ChsKD2Rpc3RhbmNlTWVhc3VyZRIIagZjb3NpbmUKFgoLZmVhdHVyZXNDb2wSB2oFaW5wdXQKBwoBaxICMAMKDQoHbWF4SXRlchICMDIKJAoXbWluRGl2aXNpYmxlQ2x1c3RlclNpemUSCVkAAAAAAADQPwoaCg1wcmVkaWN0aW9uQ29sEglqB2NsdXN0ZXIKEwoEc2VlZBILMNb//////////wEKFQoJd2VpZ2h0Q29sEghqBndlaWdodA=="
+    },
+    {
+      "seed": 2147483647,
+      "params_b64": 
"ChsKD2Rpc3RhbmNlTWVhc3VyZRIIagZjb3NpbmUKFgoLZmVhdHVyZXNDb2wSB2oFaW5wdXQKBwoBaxICMAMKDQoHbWF4SXRlchICMDIKJAoXbWluRGl2aXNpYmxlQ2x1c3RlclNpemUSCVkAAAAAAADQPwoaCg1wcmVkaWN0aW9uQ29sEglqB2NsdXN0ZXIKDgoEc2VlZBIGMP////8HChUKCXdlaWdodENvbBIIagZ3ZWlnaHQ="
+    },
+    {
+      "seed": 2147483648,
+      "params_b64": 
"ChsKD2Rpc3RhbmNlTWVhc3VyZRIIagZjb3NpbmUKFgoLZmVhdHVyZXNDb2wSB2oFaW5wdXQKBwoBaxICMAMKDQoHbWF4SXRlchICMDIKJAoXbWluRGl2aXNpYmxlQ2x1c3RlclNpemUSCVkAAAAAAADQPwoaCg1wcmVkaWN0aW9uQ29sEglqB2NsdXN0ZXIKDgoEc2VlZBIGOICAgIAIChUKCXdlaWdodENvbBIIagZ3ZWlnaHQ="
+    },
+    {
+      "seed": -2147483648,
+      "params_b64": 
"ChsKD2Rpc3RhbmNlTWVhc3VyZRIIagZjb3NpbmUKFgoLZmVhdHVyZXNDb2wSB2oFaW5wdXQKBwoBaxICMAMKDQoHbWF4SXRlchICMDIKJAoXbWluRGl2aXNpYmxlQ2x1c3RlclNpemUSCVkAAAAAAADQPwoaCg1wcmVkaWN0aW9uQ29sEglqB2NsdXN0ZXIKEwoEc2VlZBILMICAgID4/////wEKFQoJd2VpZ2h0Q29sEghqBndlaWdodA=="
+    },
+    {
+      "seed": -2147483649,
+      "params_b64": 
"ChsKD2Rpc3RhbmNlTWVhc3VyZRIIagZjb3NpbmUKFgoLZmVhdHVyZXNDb2wSB2oFaW5wdXQKBwoBaxICMAMKDQoHbWF4SXRlchICMDIKJAoXbWluRGl2aXNpYmxlQ2x1c3RlclNpemUSCVkAAAAAAADQPwoaCg1wcmVkaWN0aW9uQ29sEglqB2NsdXN0ZXIKEwoEc2VlZBILOP/////3/////wEKFQoJd2VpZ2h0Q29sEghqBndlaWdodA=="
+    }
+  ]
+}


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

Reply via email to