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 5a933f60 [SPARK-61597][CONNECT] Support native GaussianMixture
training and prediction
5a933f60 is described below
commit 5a933f60af7a0506350b089fc2b10a9fdf6f2a5d
Author: Ruifeng Zheng <[email protected]>
AuthorDate: Fri Nov 13 10:18:47 2026 +0900
[SPARK-61597][CONNECT] Support native GaussianMixture training and
prediction
### What changes were proposed in this pull request?
Add native Rust `GaussianMixture` / `GaussianMixtureModel` training and
DataFrame prediction, and expose `GaussianMixture` through the Rust-backed
Python Connect API. Support all nine constructor parameters and named setters,
with corresponding Rust getters, through the existing cached-model protocol.
Add official-PySpark parameter fixtures at six signed seed/integer-width
boundaries, live Rust and Python tests, CI registration and compatibility
documentation.
### Why are the changes needed?
Extend native clustering support to expectation-maximization Gaussian
mixtures, including soft component probabilities and instance weights.
### Does this PR introduce _any_ user-facing change?
Yes. Rust and Rust-backed Python users can fit GaussianMixture and
transform dense/sparse-vector DataFrames into cluster IDs and component
probability vectors. The keyword-only constructor matches official PySpark's
parameter order/defaults and conversions. Unset values remain omitted so the
server uses its defaults.
The native surface covers construction, setters, fit and DataFrame
transform. Component means/covariances/weights, training summaries,
single-vector prediction and persistence are outside its scope.
### How was this patch tested?
- All 642 Rust library tests pass; every integration test compiles with
default features and `wasm-udf`.
- Five Rust live tests pass, including multivariate probabilities,
independent fitted references, clones/lazy lifetime, session rejection, weights
and server validation.
- Golden comparison matches all nine parameters with official PySpark at
six signed seed/integer-width boundaries.
- All 14 behavior cases pass with official PySpark, including one- and
two-dimensional mixtures, sparse/dense inputs, two/three components, normalized
probabilities, weights, seeded reproducibility, independent fits, disabled
probabilities and invalid inputs. The native extension passes those same cases
and two shared ownership/session tests (16 passed).
- Native Python offline suites: 2,085 passed, 8 skipped and 14 subtests
passed.
- The constructor and nine 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 #588 from zhengruifeng/add-gaussian-mixture.
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 | 118 ++++++-
crates/spark-connect/src/ml.rs | 349 +++++++++++++++++++++
crates/spark-connect/tests/e2e_gaussian_mixture.rs | 245 +++++++++++++++
.../spark-connect/tests/gaussian_mixture_golden.rs | 33 ++
docs/compatibility.md | 26 ++
python/pyspark/ml/connect/__init__.py | 3 +-
python/pyspark/ml/connect/clustering.py | 4 +-
python/tests/test_gaussian_mixture_e2e.py | 233 ++++++++++++++
python/tests/test_ml_e2e.py | 2 +
python/tests/test_ml_offline.py | 62 ++++
scripts/capture_gaussian_mixture_golden.py | 59 ++++
tests/golden/gaussian_mixture.json | 29 ++
14 files changed, 1161 insertions(+), 7 deletions(-)
diff --git a/.github/workflows/build_python_connect.yml
b/.github/workflows/build_python_connect.yml
index 8d5af740..8e592076 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
tests/test_bisecting_kmeans_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 tests/test_gaussian_mixture_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_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 e2e_coverage --test e2e_linear_svc --test
e2e_linear_regression --test e2e_kmeans --test e2e_bisecting_kmeans --test
e2e_gaussian_mixture --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 63b4b4b4..cad4db41 100644
--- a/crates/pyspark-rs/src/lib.rs
+++ b/crates/pyspark-rs/src/lib.rs
@@ -253,6 +253,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::PyGaussianMixture>()?;
m.add_class::<ml::PyBisectingKMeans>()?;
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 50e076aa..2889b0fb 100644
--- a/crates/pyspark-rs/src/ml.rs
+++ b/crates/pyspark-rs/src/ml.rs
@@ -17,8 +17,8 @@ use pyo3::types::{PyDict, PyList, PyTuple, PyType};
use pyo3::PyClass;
use spark_connect::ml::{
BinaryClassificationEvaluator, BisectingKMeans, CrossValidator,
DecisionTreeClassifier,
- DecisionTreeRegressor, Estimator, Evaluator, GBTClassifier, GBTRegressor,
KMeans,
- LinearRegression, LinearSVC, LogisticRegression, MaxAbsScaler, MlOperator,
Model,
+ DecisionTreeRegressor, Estimator, Evaluator, GBTClassifier, GBTRegressor,
GaussianMixture,
+ KMeans, LinearRegression, LinearSVC, LogisticRegression, MaxAbsScaler,
MlOperator, Model,
MulticlassClassificationEvaluator, NaiveBayes, Params, Pipeline,
RandomForestClassifier,
RandomForestRegressor, RegressionEvaluator, StandardScaler, StringIndexer,
Transformer,
VectorAssembler,
@@ -3269,6 +3269,119 @@ impl PyBinaryClassificationEvaluator {
}
}
+/// Gaussian mixture estimator fitted and cached by Spark Connect.
+#[pyclass(name = "GaussianMixture", module = "pyspark.ml.connect.clustering")]
+pub struct PyGaussianMixture {
+ inner: GaussianMixture,
+ unsendable: Vec<&'static str>,
+}
+
+const GAUSSIAN_MIXTURE_PARAMS: &[(&str, Kind)] = &[
+ ("featuresCol", Kind::Str),
+ ("predictionCol", Kind::Str),
+ ("k", Kind::Int),
+ ("probabilityCol", Kind::Str),
+ ("tol", Kind::Float),
+ ("maxIter", Kind::Int),
+ ("seed", Kind::Int),
+ ("aggregationDepth", Kind::Int),
+ ("weightCol", Kind::Str),
+];
+
+#[pymethods]
+impl PyGaussianMixture {
+ #[new]
+ #[pyo3(signature = (*args, **kwargs), text_signature = "(*,
featuresCol='features', predictionCol='prediction', k=2,
probabilityCol='probability', tol=0.01, maxIter=100, seed=None,
aggregationDepth=2, weightCol=None)")]
+ fn new(args: &Bound<'_, PyTuple>, kwargs: Option<&Bound<'_, PyDict>>) ->
PyResult<Self> {
+ let mut this = Self {
+ inner: GaussianMixture::new(),
+ unsendable: Vec::new(),
+ };
+ init_params(
+ &mut this,
+ "GaussianMixture",
+ &[],
+ GAUSSIAN_MIXTURE_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 = "setProbabilityCol")]
+ fn set_probability_col<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "probabilityCol", Kind::Str, value)
+ }
+
+ #[pyo3(name = "setTol")]
+ fn set_tol<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "tol", Kind::Float, 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 = "setAggregationDepth")]
+ fn set_aggregation_depth<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "aggregationDepth", Kind::Int, 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)
+ }
+
+ fn fit(slf: &Bound<'_, Self>, dataset: &Bound<'_, PyAny>) ->
PyResult<PyMLModel> {
+ fit_native(slf, dataset, None)
+ }
+}
+
/// Bisecting K-means fitted and cached by Spark Connect.
#[pyclass(name = "BisectingKMeans", module = "pyspark.ml.connect.clustering")]
pub struct PyBisectingKMeans {
@@ -3551,6 +3664,7 @@ native!(
PyRandomForestClassifier => RandomForestClassifier,
PyDecisionTreeRegressor => DecisionTreeRegressor,
PyRandomForestRegressor => RandomForestRegressor,
+ PyGaussianMixture => GaussianMixture,
PyKMeans => KMeans,
PyBisectingKMeans => BisectingKMeans,
PyRegressionEvaluator => RegressionEvaluator,
diff --git a/crates/spark-connect/src/ml.rs b/crates/spark-connect/src/ml.rs
index dd893521..0835c973 100644
--- a/crates/spark-connect/src/ml.rs
+++ b/crates/spark-connect/src/ml.rs
@@ -4563,6 +4563,213 @@ impl Model for BisectingKMeansModel {
}
}
+/// Gaussian mixture clustering fitted by Spark's JVM implementation using ML
vectors.
+///
+/// Learns k multivariate Gaussian components with expectation maximization.
Transforms
+/// produce cluster assignments and component probabilities. Unset parameters
use Spark's defaults.
+#[derive(Debug, Clone)]
+pub struct GaussianMixture {
+ operator: MlOperator,
+ params: Params,
+}
+
+impl GaussianMixture {
+ pub fn new() -> Self {
+ Self {
+ operator: MlOperator::new(
+ "org.apache.spark.ml.clustering.GaussianMixture",
+ 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 Gaussian components; must be greater than 1.
+ pub fn set_k(mut self, value: i32) -> Self {
+ self.params = self.params.set_param_int32("k", value);
+ self
+ }
+
+ /// Component probability output column; empty disables it.
+ pub fn set_probability_col(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("probabilityCol", value);
+ self
+ }
+
+ /// Convergence tolerance for the change in log likelihood; must be
nonnegative.
+ pub fn set_tol(mut self, value: f64) -> Self {
+ self.params = self.params.set_param_double("tol", value);
+ self
+ }
+
+ /// Maximum number of expectation maximization 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
+ }
+
+ /// Depth of the aggregation tree; must be at least 2.
+ pub fn set_aggregation_depth(mut self, value: i32) -> Self {
+ self.params = self.params.set_param_int32("aggregationDepth", 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 featuresCol value (default: "features").
+ pub fn feature_col(&self) -> &str {
+ self.params.string_or("featuresCol", "features")
+ }
+
+ /// The predictionCol value (default: "prediction").
+ pub fn prediction_col(&self) -> &str {
+ self.params.string_or("predictionCol", "prediction")
+ }
+
+ /// The k value (default: 2).
+ pub fn k(&self) -> i32 {
+ self.params.int_or("k", 2)
+ }
+
+ /// The probabilityCol value (default: "probability").
+ pub fn probability_col(&self) -> &str {
+ self.params.string_or("probabilityCol", "probability")
+ }
+
+ /// The tol value (default: 0.01).
+ pub fn tol(&self) -> f64 {
+ self.params.double_or("tol", 0.01)
+ }
+
+ /// The maxIter value (default: 100).
+ pub fn max_iter(&self) -> i32 {
+ self.params.int_or("maxIter", 100)
+ }
+
+ /// The seed value, if set.
+ pub fn seed(&self) -> Option<i64> {
+ self.params.long_opt("seed")
+ }
+
+ /// The aggregationDepth value (default: 2).
+ pub fn aggregation_depth(&self) -> i32 {
+ self.params.int_or("aggregationDepth", 2)
+ }
+
+ /// The weightCol value, if 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<GaussianMixtureModel> {
+ let cached = CachedModel::from_info(&info, session,
"GaussianMixture")?;
+ Ok(GaussianMixtureModel {
+ operator: MlOperator::with_uid(
+ "org.apache.spark.ml.clustering.GaussianMixtureModel",
+ info.uid.as_deref().unwrap_or(&self.operator.uid),
+ OperatorType::Model,
+ ),
+ params: self.params.clone(),
+ cached,
+ })
+ }
+}
+
+impl Default for GaussianMixture {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl Estimator for GaussianMixture {
+ 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 Gaussian mixture 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 GaussianMixtureModel {
+ operator: MlOperator,
+ params: Params,
+ cached: CachedModel,
+}
+
+impl Transformer for GaussianMixtureModel {
+ 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 GaussianMixtureModel {
+ fn clone_box(&self) -> Box<dyn Model> {
+ Box::new(self.clone())
+ }
+}
+
/// RegressionEvaluator: evaluates regression models.
#[derive(Debug, Clone)]
pub struct RegressionEvaluator {
@@ -5841,6 +6048,146 @@ mod tests {
assert!(estimator.operator_mut().uid.starts_with("BisectingKMeans_"));
}
+ #[test]
+ fn gaussian_mixture_getters_follow_defaults_builders_and_mutable_params() {
+ let mut estimator = GaussianMixture::default();
+ assert_eq!(estimator.feature_col(), "features");
+ assert_eq!(estimator.prediction_col(), "prediction");
+ assert_eq!(estimator.k(), 2);
+ assert_eq!(estimator.probability_col(), "probability");
+ assert_eq!(estimator.tol(), 0.01);
+ assert_eq!(estimator.max_iter(), 100);
+ assert_eq!(estimator.seed(), None);
+ assert_eq!(estimator.aggregation_depth(), 2);
+ assert_eq!(estimator.weight_col(), None);
+ let built = GaussianMixture::new()
+ .set_feature_col("input")
+ .set_prediction_col("cluster")
+ .set_k(3)
+ .set_probability_col("probs")
+ .set_tol(1e-5)
+ .set_max_iter(50)
+ .set_seed(1_i64 << 33)
+ .set_aggregation_depth(3)
+ .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("k", 3);
+ assert_eq!(estimator.k(), 3);
+ assert_eq!(built.k(), estimator.k());
+ *estimator.params_mut() = estimator
+ .params()
+ .clone()
+ .set_param_string("probabilityCol", "probs");
+ assert_eq!(estimator.probability_col(), "probs");
+ assert_eq!(built.probability_col(), estimator.probability_col());
+ *estimator.params_mut() =
estimator.params().clone().set_param_double("tol", 1e-5);
+ assert_eq!(estimator.tol(), 1e-5);
+ assert_eq!(built.tol(), estimator.tol());
+ *estimator.params_mut() =
estimator.params().clone().set_param_int32("maxIter", 50);
+ assert_eq!(estimator.max_iter(), 50);
+ 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("aggregationDepth", 3);
+ assert_eq!(estimator.aggregation_depth(), 3);
+ assert_eq!(built.aggregation_depth(), estimator.aggregation_depth());
+ *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!(estimator.params().to_proto(), built.params().to_proto());
+ assert!(estimator.operator_mut().uid.starts_with("GaussianMixture_"));
+ }
+
+ #[test]
+ fn gaussian_mixture_validates_fitted_references_and_model_metadata() {
+ let session = offline_session();
+ let estimator =
GaussianMixture::default().set_prediction_col("cluster");
+ assert_eq!(
+ estimator.operator().name,
+ "org.apache.spark.ml.clustering.GaussianMixture"
+ );
+ 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-gaussian-mixture".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.GaussianMixtureModel"
+ );
+ 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-gaussian-mixture".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 bisecting_kmeans_validates_fitted_references_and_model_metadata() {
let session = offline_session();
@@ -7213,6 +7560,8 @@ mod tests {
] {
let kmeans = KMeans::new().set_seed(seed);
assert_eq!(sent(kmeans.params()), Some(expected.clone()));
+ let gm = GaussianMixture::new().set_seed(seed);
+ assert_eq!(sent(gm.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);
diff --git a/crates/spark-connect/tests/e2e_gaussian_mixture.rs
b/crates/spark-connect/tests/e2e_gaussian_mixture.rs
new file mode 100644
index 00000000..87c7ee4e
--- /dev/null
+++ b/crates/spark-connect/tests/e2e_gaussian_mixture.rs
@@ -0,0 +1,245 @@
+//! Native GaussianMixture tests. Set SPARK_REMOTE to use a live Connect
server.
+mod common;
+
+use common::live_session;
+use spark_connect::column::{col, lit_double, lit_string};
+use spark_connect::expression::Expression;
+use spark_connect::ml::{Estimator, GaussianMixture};
+use spark_connect::row::Value;
+use spark_connect::{Column, DataFrame, SparkSession};
+
+fn vectors(s: &SparkSession, sql: &str, name: &str) -> DataFrame {
+ s.sql(sql).unwrap().with_column(
+ name,
+ Column::new(Expression::function(
+ "array_to_vector",
+ vec![col("xs").expression().clone()],
+ )),
+ )
+}
+
+fn training(s: &SparkSession, shift: i32, name: &str) -> DataFrame {
+ vectors(s,&format!("SELECT array(CASE WHEN id<40 THEN -5.0D ELSE 5.0D END
+ {shift} + sin(id)*0.5D) xs, 1.0D weight FROM range(80)"),name)
+}
+
+fn vector_array(name: &str) -> Column {
+ Column::new(Expression::function(
+ "vector_to_array",
+ vec![
+ col(name).expression().clone(),
+ lit_string("float64").expression().clone(),
+ ],
+ ))
+}
+
+fn outputs(df: DataFrame, prediction: &str, probability: &str) -> Vec<(i64,
Vec<f64>)> {
+ df.order_by(vec![col("id").asc().expression().clone()])
+ .select([col(prediction), vector_array(probability)])
+ .collect()
+ .unwrap()
+ .into_iter()
+ .map(|r| {
+ let label = r.get(0).unwrap().as_i64().unwrap();
+ let Value::List(p) = r.get(1).unwrap() else {
+ panic!("probability array")
+ };
+ (label, p.iter().map(|v| v.as_f64().unwrap()).collect())
+ })
+ .collect()
+}
+
+fn assert_partition(rows: &[(i64, Vec<f64>)], expected: &[i64]) {
+ assert_eq!(rows.len(), expected.len());
+ for i in 0..rows.len() {
+ for j in 0..rows.len() {
+ assert_eq!(
+ rows[i].0 == rows[j].0,
+ expected[i] == expected[j],
+ "{rows:?}"
+ );
+ }
+ }
+}
+
+#[test]
+fn gaussian_mixture_fits_independent_models_and_retains_lazy_predictions() {
+ let Some(s) = live_session() else {
+ return;
+ };
+ let data = training(&s, 0, "input");
+ let held = vectors(
+ &s,
+ "SELECT id,array(x) xs FROM VALUES
(0,-5.0D),(1,4.5D),(2,5.5D),(3,15.0D) AS t(id,x)",
+ "input",
+ );
+ let mut estimator = GaussianMixture::new()
+ .set_feature_col("input")
+ .set_prediction_col("cluster")
+ .set_probability_col("probs")
+ .set_k(2)
+ .set_tol(1e-5)
+ .set_max_iter(100)
+ .set_seed(42)
+ .set_aggregation_depth(3)
+ .set_weight_col("weight");
+ let mut first = estimator.fit(&data).unwrap();
+ let mut second = estimator.fit(&training(&s, 10, "input")).unwrap();
+ let object_id = |model: &dyn spark_connect::ml::Model| {
+ let spark_connect_proto::ml_relation::MlType::Transform(t) =
+ model.build_ml_relation(&held).unwrap().ml_type.unwrap()
+ else {
+ panic!("transform")
+ };
+ let
Some(spark_connect_proto::ml_relation::transform::Operator::ObjRef(r)) =
t.operator
+ else {
+ panic!("cached reference")
+ };
+ r.id
+ };
+ assert_ne!(object_id(first.as_ref()), object_id(second.as_ref()));
+ assert!(first.transform(&s.new_session().range(1).unwrap()).is_err());
+ let mut cloned = first.clone_box();
+ let lazy = cloned.transform(&held).unwrap();
+ drop(first);
+ drop(cloned);
+ assert_partition(&outputs(lazy, "cluster", "probs"), &[0, 1, 1, 1]);
+ assert_partition(
+ &outputs(second.transform(&held).unwrap(), "cluster", "probs"),
+ &[0, 0, 0, 1],
+ );
+}
+
+#[test]
+fn gaussian_mixture_multivariate_predictions_have_normalized_probabilities() {
+ let Some(s) = live_session() else {
+ return;
+ };
+ let data=vectors(&s,"SELECT array(CASE WHEN id<40 THEN -5.0D ELSE 5.0D END
+ sin(id)*0.5D, CASE WHEN id<40 THEN -3.0D ELSE 3.0D END + cos(id)*0.7D) xs
FROM range(80)","features");
+ let held=vectors(&s,"SELECT id,array(x,y) xs FROM VALUES
(0,-5.0D,-3.0D),(1,-4.5D,-3.5D),(2,5.0D,3.0D),(3,4.5D,3.5D) AS
t(id,x,y)","features");
+ let mut model = GaussianMixture::new()
+ .set_seed(42)
+ .set_tol(1e-5)
+ .fit(&data)
+ .unwrap();
+ let rows = outputs(model.transform(&held).unwrap(), "prediction",
"probability");
+ assert_partition(&rows, &[0, 0, 1, 1]);
+ for (label, p) in rows {
+ assert_eq!(p.len(), 2);
+ assert!(p.iter().all(|x| x.is_finite() && (0.0..=1.0).contains(x)));
+ assert!((p.iter().sum::<f64>() - 1.0).abs() < 1e-10);
+ let best = p
+ .iter()
+ .enumerate()
+ .max_by(|a, b| a.1.total_cmp(b.1))
+ .unwrap()
+ .0;
+ assert_eq!(label, best as i64);
+ }
+}
+
+#[test]
+fn gaussian_mixture_three_components_are_reproducible_with_a_wide_seed() {
+ let Some(s) = live_session() else {
+ return;
+ };
+ let data=vectors(&s,"SELECT array(CASE WHEN id<40 THEN -8.0D WHEN id<80
THEN 0.0D ELSE 8.0D END + sin(id)*0.5D) xs FROM range(120)","features");
+ let held=vectors(&s,"SELECT id,array(x) xs FROM VALUES
(0,-8.0D),(1,-7.5D),(2,-0.2D),(3,0.2D),(4,7.5D),(5,8.0D) AS
t(id,x)","features");
+ let mut estimator = GaussianMixture::new()
+ .set_k(3)
+ .set_seed(1_i64 << 33)
+ .set_tol(1e-6)
+ .set_max_iter(100);
+ let a = outputs(
+ estimator.fit(&data).unwrap().transform(&held).unwrap(),
+ "prediction",
+ "probability",
+ );
+ let b = outputs(
+ estimator.fit(&data).unwrap().transform(&held).unwrap(),
+ "prediction",
+ "probability",
+ );
+ assert_partition(&a, &[0, 0, 1, 1, 2, 2]);
+ for ((label, p), (other, q)) in a.into_iter().zip(b) {
+ assert_eq!(label, other);
+ assert_eq!(p.len(), 3);
+ assert_eq!(q.len(), 3);
+ assert!((p.iter().sum::<f64>() - 1.0).abs() < 1e-10);
+ for (x, y) in p.into_iter().zip(q) {
+ assert!((x - y).abs() < 1e-10);
+ }
+ }
+}
+
+#[test]
+fn gaussian_mixture_weights_change_component_probabilities() {
+ let Some(s) = live_session() else {
+ return;
+ };
+ let data=vectors(&s,"SELECT array(x) xs,CASE WHEN x<0 THEN 9.0D ELSE 1.0D
END weight FROM VALUES
(-5.0D),(-4.5D),(-4.0D),(-3.5D),(-3.0D),(3.0D),(3.5D),(4.0D),(4.5D),(5.0D) AS
t(x)","features");
+ let held = vectors(
+ &s,
+ "SELECT id,array(x) xs FROM VALUES (0,-4.0D),(1,0.0D),(2,4.0D) AS
t(id,x)",
+ "features",
+ );
+ for weighted in [false, true] {
+ let mut estimator = GaussianMixture::new().set_seed(42).set_tol(1e-8);
+ if weighted {
+ estimator = estimator.set_weight_col("weight");
+ }
+ let rows = outputs(
+ estimator.fit(&data).unwrap().transform(&held).unwrap(),
+ "prediction",
+ "probability",
+ );
+ assert_ne!(rows[0].0, rows[2].0);
+ let left = rows[0].0 as usize;
+ let expected = if weighted { 0.9 } else { 0.5 };
+ assert!((rows[1].1[left] - expected).abs() < 0.002);
+ }
+}
+
+#[test]
+fn
gaussian_mixture_supports_disabled_probabilities_and_rejects_invalid_inputs() {
+ let Some(s) = live_session() else {
+ return;
+ };
+ let data = training(&s, 0, "features");
+ let mut model = GaussianMixture::new()
+ .set_seed(42)
+ .set_probability_col("")
+ .set_prediction_col("cluster")
+ .fit(&data)
+ .unwrap();
+ let transformed = model.transform(&data).unwrap();
+ assert!(!transformed
+ .columns()
+ .unwrap()
+ .iter()
+ .any(|name| name == "probability"));
+ assert_eq!(
+ transformed
+ .select([col("cluster")])
+ .collect()
+ .unwrap()
+ .len(),
+ 80
+ );
+ for mut estimator in [
+ GaussianMixture::new().set_k(1),
+ GaussianMixture::new().set_max_iter(-1),
+ GaussianMixture::new().set_tol(-1.0),
+ GaussianMixture::new().set_aggregation_depth(1),
+ ] {
+ assert!(estimator.fit(&data).is_err());
+ }
+ assert!(GaussianMixture::new()
+ .set_weight_col("weight")
+ .fit(&data.with_column("weight", lit_double(-1.0)))
+ .is_err());
+ assert!(GaussianMixture::new()
+ .fit(&data.with_column("features", lit_double(1.0)))
+ .is_err());
+ let empty = vectors(&s, "SELECT array(1.0D) xs WHERE false", "features");
+ assert!(GaussianMixture::new().fit(&empty).is_err());
+}
diff --git a/crates/spark-connect/tests/gaussian_mixture_golden.rs
b/crates/spark-connect/tests/gaussian_mixture_golden.rs
new file mode 100644
index 00000000..5c4dc78a
--- /dev/null
+++ b/crates/spark-connect/tests/gaussian_mixture_golden.rs
@@ -0,0 +1,33 @@
+//! Match all GaussianMixture parameter encodings and integer seed boundaries
to PySpark.
+use base64::{engine::general_purpose::STANDARD, Engine};
+use prost::Message;
+use spark_connect::ml::{Estimator, GaussianMixture};
+
+#[test]
+fn gaussian_mixture_parameters_match_official_pyspark() {
+ let fixture: serde_json::Value =
+
serde_json::from_str(include_str!("../../../tests/golden/gaussian_mixture.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 = GaussianMixture::new()
+ .set_feature_col("input")
+ .set_prediction_col("cluster")
+ .set_k(3)
+ .set_max_iter(50)
+ .set_seed(seed)
+ .set_probability_col("probs")
+ .set_tol(1e-5)
+ .set_aggregation_depth(3)
+ .set_weight_col("weight");
+ assert_eq!(estimator.params().to_proto(), expected, "seed {seed}");
+ }
+ assert!(GaussianMixture::default()
+ .params()
+ .to_proto()
+ .params
+ .is_empty());
+}
diff --git a/docs/compatibility.md b/docs/compatibility.md
index b9b9c065..56d02633 100644
--- a/docs/compatibility.md
+++ b/docs/compatibility.md
@@ -594,3 +594,29 @@ 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.
+
+
+## Native GaussianMixture
+
+Rust `ml::GaussianMixture` and `ml::GaussianMixtureModel` train Gaussian
mixture
+models and produce cluster assignments and component probabilities 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 nine constructor parameters and named setters are supported: `featuresCol`,
+`predictionCol`, `k`, `probabilityCol`, `tol`, `maxIter`, `seed`,
`aggregationDepth`
+and `weightCol`. Rust also provides corresponding getters. The keyword-only
+Python constructor matches official PySpark's order/defaults and conversions.
+Unset values are omitted so the server uses its defaults.
+
+Live tests cover one- and two-dimensional mixtures, two/three components,
+normalized probabilities and assignments, dense/sparse vectors, weights, seeded
+reproducibility, independent fits, disabled probability output, server
validation,
+session isolation and lazy model lifetime. Golden fixtures compare all nine
+parameters at six signed seed/integer-width boundaries with official PySpark.
+
+The native surface covers construction, parameter setters, fit and DataFrame
+transform. Component/weight/covariance inspection, training summaries,
+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 7acf6aa3..b8b6d778 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 BisectingKMeans, KMeans
+from pyspark.ml.connect.clustering import BisectingKMeans, GaussianMixture,
KMeans
from pyspark.ml.connect.evaluation import (
RegressionEvaluator,
BinaryClassificationEvaluator,
@@ -67,6 +67,7 @@ __all__ = [
"DecisionTreeRegressor",
"RandomForestRegressor",
"KMeans",
+ "GaussianMixture",
"BisectingKMeans",
"RegressionEvaluator",
"BinaryClassificationEvaluator",
diff --git a/python/pyspark/ml/connect/clustering.py
b/python/pyspark/ml/connect/clustering.py
index b2ca6c17..33748e0a 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 BisectingKMeans, KMeans
+from pyspark._pyspark import BisectingKMeans, GaussianMixture, KMeans
-__all__ = ["BisectingKMeans", "KMeans"]
+__all__ = ["GaussianMixture", "BisectingKMeans", "KMeans"]
diff --git a/python/tests/test_gaussian_mixture_e2e.py
b/python/tests/test_gaussian_mixture_e2e.py
new file mode 100644
index 00000000..b21fd536
--- /dev/null
+++ b/python/tests/test_gaussian_mixture_e2e.py
@@ -0,0 +1,233 @@
+#
+# 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 GaussianMixture behaviors, also run with official PySpark."""
+
+import gc
+import math
+import os
+
+import pytest
+from pyspark.ml.connect.functions import array_to_vector, vector_to_array
+from pyspark.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 GaussianMixture
+ except ImportError:
+ from pyspark.ml.clustering import GaussianMixture
+ return GaussianMixture
+
+
+def _vectors(session, sql, name="features"):
+ return session.sql(sql).withColumn(name, array_to_vector("xs"))
+
+
+def _training(session, shift=0, name="features"):
+ return _vectors(
+ session,
+ f"SELECT array(CASE WHEN id<40 THEN -5.0D ELSE 5.0D END + "
+ f"{shift} + sin(id)*0.5D) xs, 1.0D weight FROM range(80)",
+ name,
+ )
+
+
+def _outputs(model, frame, prediction="prediction", probability="probability"):
+ return (
+ model.transform(frame)
+ .orderBy("id")
+ .select(prediction, vector_to_array(probability).alias("p"))
+ .collect()
+ )
+
+
+def _assert_partition(values, expected):
+ assert len(values) == len(expected)
+ for i in range(len(values)):
+ for j in range(len(values)):
+ assert (values[i] == values[j]) == (expected[i] == expected[j]),
values
+
+
[email protected]("use_setters", [False, True], ids=["constructor",
"setters"])
+def
test_gaussian_mixture_learns_dense_sparse_inputs_and_retains_lazy_predictions(
+ session, use_setters
+):
+ GaussianMixture = _estimator()
+ training = _training(session, name="input")
+ held_out = session.createDataFrame(
+ [
+ (0, Vectors.dense([-5.0])),
+ (1, Vectors.sparse(1, {0: -4.5})),
+ (2, Vectors.dense([4.5])),
+ (3, Vectors.sparse(1, {0: 5.0})),
+ ],
+ ["id", "input"],
+ )
+ values = dict(
+ featuresCol="input",
+ predictionCol="cluster",
+ k=2,
+ probabilityCol="probs",
+ tol=1e-5,
+ maxIter=100,
+ seed=42,
+ aggregationDepth=3,
+ weightCol="weight",
+ )
+ if use_setters:
+ estimator = GaussianMixture()
+ for name, value in values.items():
+ assert getattr(estimator, "set" + name[0].upper() +
name[1:])(value) is estimator
+ else:
+ estimator = GaussianMixture(**values)
+ model = estimator.fit(training)
+ lazy = (
+ model.transform(held_out)
+ .orderBy("id")
+ .select("cluster", vector_to_array("probs").alias("p"))
+ )
+ estimator.setPredictionCol("changed")
+ del model, estimator
+ gc.collect()
+ rows = lazy.collect()
+ _assert_partition([r[0] for r in rows], [0, 0, 1, 1])
+ for row in rows:
+ assert len(row.p) == 2 and sum(row.p) == pytest.approx(1.0)
+ assert all(math.isfinite(x) and 0 <= x <= 1 for x in row.p)
+ assert max(range(2), key=row.p.__getitem__) == row[0]
+
+
+def test_gaussian_mixture_multivariate_probabilities(session):
+ training = _vectors(
+ session,
+ "SELECT array(CASE WHEN id<40 THEN -5.0D ELSE 5.0D END + sin(id)*0.5D,
"
+ "CASE WHEN id<40 THEN -3.0D ELSE 3.0D END + cos(id)*0.7D) xs FROM
range(80)",
+ )
+ points = [[-5.0, -3.0], [-4.5, -3.5], [5.0, 3.0], [4.5, 3.5]]
+ held = session.createDataFrame(
+ [
+ (i, Vectors.sparse(2, {j: v for j, v in enumerate(x)}))
+ if i % 2
+ else (i, Vectors.dense(x))
+ for i, x in enumerate(points)
+ ],
+ ["id", "features"],
+ )
+ rows = _outputs(_estimator()(seed=42, tol=1e-5).fit(training), held)
+ _assert_partition([r[0] for r in rows], [0, 0, 1, 1])
+ for row in rows:
+ assert len(row.p) == 2 and sum(row.p) == pytest.approx(1.0)
+ assert all(math.isfinite(p) and 0 <= p <= 1 for p in row.p)
+ assert max(range(2), key=row.p.__getitem__) == row[0]
+
+
+def test_gaussian_mixture_repeated_fits_retain_independent_models(session):
+ estimator = _estimator()(k=2, seed=42, tol=1e-5)
+ first = estimator.fit(_training(session))
+ second = estimator.fit(_training(session, shift=10))
+ held = _vectors(
+ session,
+ "SELECT id,array(x) xs FROM VALUES
(0,-5.0D),(1,4.5D),(2,5.5D),(3,15.0D) AS t(id,x)",
+ )
+ _assert_partition([r[0] for r in _outputs(first, held)], [0, 1, 1, 1])
+ _assert_partition([r[0] for r in _outputs(second, held)], [0, 0, 0, 1])
+
+
+def test_gaussian_mixture_three_components_and_seed_reproducibility(session):
+ training = _vectors(
+ session,
+ "SELECT array(CASE WHEN id<40 THEN -8.0D WHEN id<80 THEN 0.0D ELSE
8.0D END + sin(id)*0.5D) xs FROM range(120)",
+ )
+ held = _vectors(
+ session,
+ "SELECT id,array(x) xs FROM VALUES
(0,-8.0D),(1,-7.5D),(2,-0.2D),(3,0.2D),(4,7.5D),(5,8.0D) AS t(id,x)",
+ )
+ estimator = _estimator()(k=3, seed=2**33, tol=1e-6, maxIter=100)
+ first = _outputs(estimator.fit(training), held)
+ second = _outputs(estimator.fit(training), held)
+ _assert_partition([r[0] for r in first], [0, 0, 1, 1, 2, 2])
+ assert [r[0] for r in first] == [r[0] for r in second]
+ for a, b in zip(first, second):
+ assert a.p == pytest.approx(b.p)
+ assert len(a.p) == 3 and sum(a.p) == pytest.approx(1.0)
+
+
+def
test_gaussian_mixture_instance_weights_change_component_probabilities(session):
+ training = _vectors(
+ session,
+ "SELECT array(x) xs,CASE WHEN x<0 THEN 9.0D ELSE 1.0D END weight "
+ "FROM VALUES
(-5.0D),(-4.5D),(-4.0D),(-3.5D),(-3.0D),(3.0D),(3.5D),(4.0D),(4.5D),(5.0D) AS
t(x)",
+ )
+ held = _vectors(
+ session, "SELECT id,array(x) xs FROM VALUES
(0,-4.0D),(1,0.0D),(2,4.0D) AS t(id,x)"
+ )
+ plain = _outputs(_estimator()(k=2, seed=42, tol=1e-8).fit(training), held)
+ weighted = _outputs(
+ _estimator()(k=2, seed=42, tol=1e-8,
weightCol="weight").fit(training), held
+ )
+ _assert_partition([plain[0][0], plain[2][0]], [0, 1])
+ _assert_partition([weighted[0][0], weighted[2][0]], [0, 1])
+ assert plain[1].p[plain[0][0]] == pytest.approx(0.5, abs=0.002)
+ assert weighted[1].p[weighted[0][0]] == pytest.approx(0.9, abs=0.002)
+
+
+def test_gaussian_mixture_can_disable_probability_output(session):
+ model = _estimator()(k=2, seed=42, probabilityCol="",
predictionCol="cluster").fit(
+ _training(session)
+ )
+ transformed = model.transform(_training(session))
+ assert "probability" not in transformed.columns
+ assert len(transformed.select("cluster").collect()) == 80
+
+
[email protected](
+ "case", ["k", "iterations", "tol", "aggregation", "weight", "nonvector",
"empty"]
+)
+def test_gaussian_mixture_rejects_invalid_parameters_and_data(session, case):
+ estimator = _estimator()(k=2, seed=42)
+ frame = _training(session)
+ if case == "k":
+ estimator.setK(1)
+ elif case == "iterations":
+ estimator.setMaxIter(-1)
+ elif case == "tol":
+ estimator.setTol(-1.0)
+ elif case == "aggregation":
+ estimator.setAggregationDepth(1)
+ 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))
+ 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 c90bdd1d..9943bc86 100644
--- a/python/tests/test_ml_e2e.py
+++ b/python/tests/test_ml_e2e.py
@@ -249,6 +249,7 @@ def _native_estimators():
BisectingKMeans,
DecisionTreeClassifier,
DecisionTreeRegressor,
+ GaussianMixture,
GBTClassifier,
GBTRegressor,
KMeans,
@@ -265,6 +266,7 @@ def _native_estimators():
ml = "org.apache.spark.ml."
return [
+ (GaussianMixture(k=2, seed=1, maxIter=2), ml +
"clustering.GaussianMixtureModel"),
(BisectingKMeans(k=2, seed=1), ml + "clustering.BisectingKMeansModel"),
(NaiveBayes(), ml + "classification.NaiveBayesModel"),
(GBTRegressor(maxIter=2), ml + "regression.GBTRegressionModel"),
diff --git a/python/tests/test_ml_offline.py b/python/tests/test_ml_offline.py
index b738fe4c..e0068868 100644
--- a/python/tests/test_ml_offline.py
+++ b/python/tests/test_ml_offline.py
@@ -856,6 +856,10 @@ _NATIVE_PARAMS = {
featuresCol="str", predictionCol="str", maxIter="int", seed="int",
k="int",
minDivisibleClusterSize="float", distanceMeasure="str",
weightCol="str",
),
+ "GaussianMixture": dict(
+ featuresCol="str", predictionCol="str", k="int", probabilityCol="str",
tol="float",
+ maxIter="int", seed="int", aggregationDepth="int", weightCol="str",
+ ),
"KMeans": dict(
featuresCol="str", predictionCol="str", k="int", initMode="str",
initSteps="int",
tol="float", maxIter="int", seed="int", distanceMeasure="str",
weightCol="str",
@@ -3071,6 +3075,64 @@ 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_gaussian_mixture_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 GaussianMixture as exported
+ from pyspark.ml.connect.clustering import GaussianMixture
+
+ assert exported is GaussianMixture is native.GaussianMixture
+ defaults = dict(
+ featuresCol="features",
+ predictionCol="prediction",
+ k=2,
+ probabilityCol="probability",
+ tol=0.01,
+ maxIter=100,
+ seed=None,
+ aggregationDepth=2,
+ weightCol=None,
+ )
+ signature = inspect.signature(GaussianMixture)
+ 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/gaussian_mixture.json").read_text()
+ )
+ spark, service = ml_mock
+ models = []
+ _, params = _native_request(spark, service, GaussianMixture(), models)
+ assert params == pb2.MlParams()
+ for case in fixture["cases"]:
+ values = dict(
+ featuresCol="input",
+ predictionCol="cluster",
+ k=3,
+ probabilityCol="probs",
+ tol=1e-5,
+ maxIter=50,
+ seed=case["seed"],
+ aggregationDepth=3,
+ weightCol="weight",
+ )
+ if use_setters:
+ estimator = GaussianMixture()
+ for name, value in values.items():
+ assert getattr(estimator, "set" + name[0].upper() +
name[1:])(value) is estimator
+ else:
+ estimator = GaussianMixture(**values)
+ operator, params = _native_request(spark, service, estimator, models)
+ assert operator.name ==
"org.apache.spark.ml.clustering.GaussianMixture"
+ assert params ==
pb2.MlParams.FromString(base64.b64decode(case["params_b64"]))
+
+
@pytest.mark.parametrize("use_setters", [False, True], ids=["constructor",
"setters"])
def test_bisecting_kmeans_native_parameters_match_official_fixture(ml_mock,
use_setters):
import base64
diff --git a/scripts/capture_gaussian_mixture_golden.py
b/scripts/capture_gaussian_mixture_golden.py
new file mode 100644
index 00000000..69e70f9a
--- /dev/null
+++ b/scripts/capture_gaussian_mixture_golden.py
@@ -0,0 +1,59 @@
+#!/usr/bin/env python3
+"""Capture GaussianMixture parameter wire goldens using official PySpark
4.3.0."""
+
+import argparse
+import base64
+import json
+from pathlib import Path
+
+from pyspark.ml.clustering import GaussianMixture
+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/gaussian_mixture.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 = GaussianMixture(
+ featuresCol="input",
+ predictionCol="cluster",
+ k=3,
+ maxIter=50,
+ seed=seed,
+ probabilityCol="probs",
+ tol=1e-5,
+ aggregationDepth=3,
+ 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.GaussianMixture",
+ "cases": cases,
+ },
+ indent=2,
+ )
+ + "\n"
+ )
+ finally:
+ spark.stop()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/golden/gaussian_mixture.json
b/tests/golden/gaussian_mixture.json
new file mode 100644
index 00000000..d4f353e1
--- /dev/null
+++ b/tests/golden/gaussian_mixture.json
@@ -0,0 +1,29 @@
+{
+ "source": "apache/spark v4.3.0 pyspark.ml.clustering.GaussianMixture",
+ "cases": [
+ {
+ "seed": 42,
+ "params_b64":
"ChYKEGFnZ3JlZ2F0aW9uRGVwdGgSAjADChYKC2ZlYXR1cmVzQ29sEgdqBWlucHV0CgcKAWsSAjADCg0KB21heEl0ZXISAjAyChoKDXByZWRpY3Rpb25Db2wSCWoHY2x1c3RlcgoZCg5wcm9iYWJpbGl0eUNvbBIHagVwcm9icwoKCgRzZWVkEgIwKgoQCgN0b2wSCVnxaOOItfjkPgoVCgl3ZWlnaHRDb2wSCGoGd2VpZ2h0"
+ },
+ {
+ "seed": -42,
+ "params_b64":
"ChYKEGFnZ3JlZ2F0aW9uRGVwdGgSAjADChYKC2ZlYXR1cmVzQ29sEgdqBWlucHV0CgcKAWsSAjADCg0KB21heEl0ZXISAjAyChoKDXByZWRpY3Rpb25Db2wSCWoHY2x1c3RlcgoZCg5wcm9iYWJpbGl0eUNvbBIHagVwcm9icwoTCgRzZWVkEgsw1v//////////AQoQCgN0b2wSCVnxaOOItfjkPgoVCgl3ZWlnaHRDb2wSCGoGd2VpZ2h0"
+ },
+ {
+ "seed": 2147483647,
+ "params_b64":
"ChYKEGFnZ3JlZ2F0aW9uRGVwdGgSAjADChYKC2ZlYXR1cmVzQ29sEgdqBWlucHV0CgcKAWsSAjADCg0KB21heEl0ZXISAjAyChoKDXByZWRpY3Rpb25Db2wSCWoHY2x1c3RlcgoZCg5wcm9iYWJpbGl0eUNvbBIHagVwcm9icwoOCgRzZWVkEgYw/////wcKEAoDdG9sEglZ8WjjiLX45D4KFQoJd2VpZ2h0Q29sEghqBndlaWdodA=="
+ },
+ {
+ "seed": 2147483648,
+ "params_b64":
"ChYKEGFnZ3JlZ2F0aW9uRGVwdGgSAjADChYKC2ZlYXR1cmVzQ29sEgdqBWlucHV0CgcKAWsSAjADCg0KB21heEl0ZXISAjAyChoKDXByZWRpY3Rpb25Db2wSCWoHY2x1c3RlcgoZCg5wcm9iYWJpbGl0eUNvbBIHagVwcm9icwoOCgRzZWVkEgY4gICAgAgKEAoDdG9sEglZ8WjjiLX45D4KFQoJd2VpZ2h0Q29sEghqBndlaWdodA=="
+ },
+ {
+ "seed": -2147483648,
+ "params_b64":
"ChYKEGFnZ3JlZ2F0aW9uRGVwdGgSAjADChYKC2ZlYXR1cmVzQ29sEgdqBWlucHV0CgcKAWsSAjADCg0KB21heEl0ZXISAjAyChoKDXByZWRpY3Rpb25Db2wSCWoHY2x1c3RlcgoZCg5wcm9iYWJpbGl0eUNvbBIHagVwcm9icwoTCgRzZWVkEgswgICAgPj/////AQoQCgN0b2wSCVnxaOOItfjkPgoVCgl3ZWlnaHRDb2wSCGoGd2VpZ2h0"
+ },
+ {
+ "seed": -2147483649,
+ "params_b64":
"ChYKEGFnZ3JlZ2F0aW9uRGVwdGgSAjADChYKC2ZlYXR1cmVzQ29sEgdqBWlucHV0CgcKAWsSAjADCg0KB21heEl0ZXISAjAyChoKDXByZWRpY3Rpb25Db2wSCWoHY2x1c3RlcgoZCg5wcm9iYWJpbGl0eUNvbBIHagVwcm9icwoTCgRzZWVkEgs4//////f/////AQoQCgN0b2wSCVnxaOOItfjkPgoVCgl3ZWlnaHRDb2wSCGoGd2VpZ2h0"
+ }
+ ]
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]