This is an automated email from the ASF dual-hosted git repository.
zhengruifeng pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/spark-connect-rust.git
The following commit(s) were added to refs/heads/master by this push:
new 9ecc955a [SPARK-61633][CONNECT] Support native LDA and
PowerIterationClustering
9ecc955a is described below
commit 9ecc955a65090aebfbdb520827b1793bb21b6df3
Author: Ruifeng Zheng <[email protected]>
AuthorDate: Fri Nov 13 18:40:42 2026 +0800
[SPARK-61633][CONNECT] Support native LDA and PowerIterationClustering
### What changes were proposed in this pull request?
Implement the two remaining native clustering algorithms from PySpark 4.3.0
in the Rust API and Python bindings:
- `LDA`: online and EM training, all 14 constructor parameters with
setters, and cached-model DataFrame transforms.
- `PowerIterationClustering`: all six parameters and `assign_clusters` /
`assignClusters`, using Spark Connect's
`powerIterationClusteringAssignClusters` helper. The lazy result retains any
cached models used by its input.
Add official PySpark parameter, helper-request and inference fixtures,
Rust/Python tests, CI integration, and compatibility documentation.
### Why are the changes needed?
KMeans, BisectingKMeans and GaussianMixture already have native
implementations. Adding LDA and PowerIterationClustering completes execution
support for all five clustering algorithms in standard `pyspark.ml.clustering`.
### Does this PR introduce _any_ user-facing change?
Yes. Rust exposes `ml::LDA`, `ml::LDAModel` and
`ml::PowerIterationClustering`. Python exposes the two algorithms through
`pyspark.ml.connect.clustering` and `pyspark.ml.connect`. All methods require
Spark DataFrames; pandas inputs are rejected consistently. LDA returns the
shared native `MLModel`; PIC returns an `id: bigint, cluster: int` DataFrame
and has no fit/transform API.
This completes algorithm execution coverage. Rich LDA model inspection,
likelihood/perplexity methods, topic descriptions, model conversion and
persistence remain outside this native surface, as documented.
### How was this patch tested?
- 28 new native Python live tests passed against Spark 4.3.0; 26 shared
cases also passed with official PySpark. Two native-only cases cover
numeric-array features and retaining a cached input model after garbage
collection. The latter raises `CONNECT_ML.CACHE_INVALID` with the official PIC
helper; the native relation retains the input owner.
- All 190 existing Python ML live tests passed, including the other
clustering algorithms.
- 3,688 Python offline/Arrow handoff tests passed (8 skipped), including
315 ML tests and new signature, parameter-conversion, pandas-rejection and
helper-request checks.
- 682 Rust unit tests passed, plus new clustering protocol/live tests and
existing clustering integration tests. All integration tests compiled with and
without `wasm-udf`; rustfmt, workspace Clippy with `-D warnings`, and Ruff
passed.
- API introspection found all five clustering algorithms exposed natively,
and zero Connect-only SQL API gaps after the documented transport-only
exclusions.
- Official Spark 4.3.0 Connect suite through the Rust transport: 2,638
passed, 589 skipped across 87 files with zero unexpected failures. Three
artifact/local-cluster test files requiring a separate cluster environment were
excluded.
### 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 #637 from zhengruifeng/add-remaining-clustering.
Authored-by: Ruifeng Zheng <[email protected]>
Signed-off-by: Ruifeng Zheng <[email protected]>
---
.github/workflows/build_python_connect.yml | 2 +-
crates/pyspark-rs/src/lib.rs | 2 +
crates/pyspark-rs/src/ml.rs | 249 +++++++-
crates/spark-connect/src/ml.rs | 475 ++++++++++++++
.../tests/e2e_remaining_clustering.rs | 172 +++++
.../tests/remaining_clustering_golden.rs | 138 ++++
docs/compatibility.md | 32 +
python/pyspark/ml/connect/__init__.py | 6 +-
python/pyspark/ml/connect/clustering.py | 6 +-
python/tests/test_ml_offline.py | 80 ++-
python/tests/test_remaining_clustering_e2e.py | 200 ++++++
scripts/capture_remaining_clustering_golden.py | 152 +++++
tests/golden/remaining_clustering.json | 696 +++++++++++++++++++++
13 files changed, 2200 insertions(+), 10 deletions(-)
diff --git a/.github/workflows/build_python_connect.yml
b/.github/workflows/build_python_connect.yml
index 76cd0dd9..942336df 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 tests/test_gaussian_mixture_e2e.py
tests/test_generalized_linear_regression_e2e.py
tests/test_remaining_classifiers_e2e.py tests/test_remaining_regressors_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
tests/test_generalized_linear_regression_e2e.py
tests/test_remaining_classifiers_e2e.py tests/test_remaining_regressors_e2e.py
tests/test_remaining_clustering_e2e.py -q
- name: Restart Connect server in local-cluster mode
# Resource profiles and artifact distribution across executors can
only be
diff --git a/crates/pyspark-rs/src/lib.rs b/crates/pyspark-rs/src/lib.rs
index e466d1be..ae1699cc 100644
--- a/crates/pyspark-rs/src/lib.rs
+++ b/crates/pyspark-rs/src/lib.rs
@@ -264,6 +264,8 @@ fn _pyspark(_py: Python<'_>, m: &Bound<'_, PyModule>) ->
PyResult<()> {
m.add_class::<ml::PyRandomForestClassifier>()?;
m.add_class::<ml::PyDecisionTreeRegressor>()?;
m.add_class::<ml::PyRandomForestRegressor>()?;
+ m.add_class::<ml::PyLDA>()?;
+ m.add_class::<ml::PyPowerIterationClustering>()?;
m.add_class::<ml::PyKMeans>()?;
m.add_class::<ml::PyGaussianMixture>()?;
m.add_class::<ml::PyBisectingKMeans>()?;
diff --git a/crates/pyspark-rs/src/ml.rs b/crates/pyspark-rs/src/ml.rs
index ce3c7730..0407e94a 100644
--- a/crates/pyspark-rs/src/ml.rs
+++ b/crates/pyspark-rs/src/ml.rs
@@ -22,8 +22,8 @@ use spark_connect::ml::{
GeneralizedLinearRegression, IsotonicRegression, KMeans, LinearRegression,
LinearSVC,
LogisticRegression, MlOperator, MlVector, Model,
MulticlassClassificationEvaluator,
MultilayerPerceptronClassifier, NaiveBayes, OneVsRest, Params, Pipeline,
- RandomForestClassifier, RandomForestRegressor, RegressionEvaluator,
StringIndexer, Transformer,
- VectorAssembler,
+ PowerIterationClustering, RandomForestClassifier, RandomForestRegressor,
RegressionEvaluator,
+ StringIndexer, Transformer, VectorAssembler, LDA,
};
use spark_connect::types::StructField;
use spark_connect::DataFrame;
@@ -4344,6 +4344,249 @@ impl PyBinaryClassificationEvaluator {
}
}
+/// Native LDA backed by Spark Connect's JVM ML API.
+#[pyclass(name = "LDA", module = "pyspark.ml.connect.clustering")]
+pub struct PyLDA {
+ inner: LDA,
+ unsendable: Vec<&'static str>,
+}
+
+const LDA_PARAMS: &[(&str, Kind)] = &[
+ ("featuresCol", Kind::Str),
+ ("maxIter", Kind::Int),
+ ("seed", Kind::Int),
+ ("checkpointInterval", Kind::Int),
+ ("k", Kind::Int),
+ ("optimizer", Kind::Str),
+ ("learningOffset", Kind::Float),
+ ("learningDecay", Kind::Float),
+ ("subsamplingRate", Kind::Float),
+ ("optimizeDocConcentration", Kind::Bool),
+ ("docConcentration", Kind::FloatList),
+ ("topicConcentration", Kind::Float),
+ ("topicDistributionCol", Kind::Str),
+ ("keepLastCheckpoint", Kind::Bool),
+];
+
+#[pymethods]
+impl PyLDA {
+ #[new]
+ #[pyo3(signature = (*args, **kwargs), text_signature = "(*,
featuresCol='features', maxIter=20, seed=None, checkpointInterval=10, k=10,
optimizer='online', learningOffset=1024.0, learningDecay=0.51,
subsamplingRate=0.05, optimizeDocConcentration=True, docConcentration=None,
topicConcentration=None, topicDistributionCol='topicDistribution',
keepLastCheckpoint=True)")]
+ fn new(args: &Bound<'_, PyTuple>, kwargs: Option<&Bound<'_, PyDict>>) ->
PyResult<Self> {
+ let mut this = Self {
+ inner: LDA::new(),
+ unsendable: Vec::new(),
+ };
+ init_params(&mut this, "LDA", &[], LDA_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 = "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 = "setCheckpointInterval")]
+ fn set_checkpoint_interval<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "checkpointInterval", Kind::Int, value)
+ }
+
+ #[pyo3(name = "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 = "setOptimizer")]
+ fn set_optimizer<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "optimizer", Kind::Str, value)
+ }
+
+ #[pyo3(name = "setLearningOffset")]
+ fn set_learning_offset<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "learningOffset", Kind::Float, value)
+ }
+
+ #[pyo3(name = "setLearningDecay")]
+ fn set_learning_decay<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "learningDecay", Kind::Float, value)
+ }
+
+ #[pyo3(name = "setSubsamplingRate")]
+ fn set_subsampling_rate<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "subsamplingRate", Kind::Float, value)
+ }
+
+ #[pyo3(name = "setOptimizeDocConcentration")]
+ fn set_optimize_doc_concentration<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "optimizeDocConcentration", Kind::Bool, value)
+ }
+
+ #[pyo3(name = "setDocConcentration")]
+ fn set_doc_concentration<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "docConcentration", Kind::FloatList, value)
+ }
+
+ #[pyo3(name = "setTopicConcentration")]
+ fn set_topic_concentration<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "topicConcentration", Kind::Float, value)
+ }
+
+ #[pyo3(name = "setTopicDistributionCol")]
+ fn set_topic_distribution_col<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "topicDistributionCol", Kind::Str, value)
+ }
+
+ #[pyo3(name = "setKeepLastCheckpoint")]
+ fn set_keep_last_checkpoint<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "keepLastCheckpoint", Kind::Bool, value)
+ }
+
+ fn fit(slf: &Bound<'_, Self>, dataset: &Bound<'_, PyAny>) ->
PyResult<PyMLModel> {
+ fit_native(slf, dataset, None)
+ }
+}
+
+/// Native PowerIterationClustering backed by Spark Connect's JVM ML API.
+#[pyclass(
+ name = "PowerIterationClustering",
+ module = "pyspark.ml.connect.clustering"
+)]
+pub struct PyPowerIterationClustering {
+ inner: PowerIterationClustering,
+ unsendable: Vec<&'static str>,
+}
+
+const POWER_ITERATION_CLUSTERING_PARAMS: &[(&str, Kind)] = &[
+ ("k", Kind::Int),
+ ("maxIter", Kind::Int),
+ ("initMode", Kind::Str),
+ ("srcCol", Kind::Str),
+ ("dstCol", Kind::Str),
+ ("weightCol", Kind::Str),
+];
+
+#[pymethods]
+impl PyPowerIterationClustering {
+ #[new]
+ #[pyo3(signature = (*args, **kwargs), text_signature = "(*, k=2,
maxIter=20, initMode='random', srcCol='src', dstCol='dst', weightCol=None)")]
+ fn new(args: &Bound<'_, PyTuple>, kwargs: Option<&Bound<'_, PyDict>>) ->
PyResult<Self> {
+ let mut this = Self {
+ inner: PowerIterationClustering::new(),
+ unsendable: Vec::new(),
+ };
+ init_params(
+ &mut this,
+ "PowerIterationClustering",
+ &[],
+ POWER_ITERATION_CLUSTERING_PARAMS,
+ args,
+ kwargs,
+ )?;
+ Ok(this)
+ }
+
+ #[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 = "setInitMode")]
+ fn set_init_mode<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "initMode", Kind::Str, value)
+ }
+
+ #[pyo3(name = "setSrcCol")]
+ fn set_src_col<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "srcCol", Kind::Str, value)
+ }
+
+ #[pyo3(name = "setDstCol")]
+ fn set_dst_col<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "dstCol", 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 = "assignClusters")]
+ fn assign_clusters(slf: &Bound<'_, Self>, dataset: &Bound<'_, PyAny>) ->
PyResult<PyDataFrame> {
+ let df = dataset_of(dataset, "assignClusters", "select")?;
+ let algorithm = snapshot(slf)?;
+ Ok(PyDataFrame::new(algorithm.assign_clusters(&df).to_pyerr()?))
+ }
+}
+
/// Gaussian mixture estimator fitted and cached by Spark Connect.
#[pyclass(name = "GaussianMixture", module = "pyspark.ml.connect.clustering")]
pub struct PyGaussianMixture {
@@ -4744,6 +4987,8 @@ native!(
PyRandomForestClassifier => RandomForestClassifier,
PyDecisionTreeRegressor => DecisionTreeRegressor,
PyRandomForestRegressor => RandomForestRegressor,
+ PyLDA => LDA,
+ PyPowerIterationClustering => PowerIterationClustering,
PyGaussianMixture => GaussianMixture,
PyKMeans => KMeans,
PyBisectingKMeans => BisectingKMeans,
diff --git a/crates/spark-connect/src/ml.rs b/crates/spark-connect/src/ml.rs
index 89402384..9e53b20a 100644
--- a/crates/spark-connect/src/ml.rs
+++ b/crates/spark-connect/src/ml.rs
@@ -6953,6 +6953,430 @@ impl Model for GaussianMixtureModel {
}
}
+/// Latent Dirichlet Allocation, fitted by Spark Connect using the online or
EM optimizer.
+#[derive(Debug, Clone)]
+pub struct LDA {
+ operator: MlOperator,
+ params: Params,
+}
+
+impl LDA {
+ pub fn new() -> Self {
+ Self {
+ operator: MlOperator::new(
+ "org.apache.spark.ml.clustering.LDA",
+ OperatorType::Estimator,
+ ),
+ params: Params::new(),
+ }
+ }
+
+ /// Set `featuresCol`; Spark validates its value when the algorithm runs.
+ pub fn set_feature_col(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("featuresCol", value);
+ self
+ }
+
+ /// Read `featuresCol` from the current parameters; unset values use Spark
defaults.
+ pub fn feature_col(&self) -> &str {
+ self.params.string_or("featuresCol", "features")
+ }
+
+ /// Set `maxIter`; Spark validates its value when the algorithm runs.
+ pub fn set_max_iter(mut self, value: i32) -> Self {
+ self.params = self.params.set_param_int32("maxIter", value);
+ self
+ }
+
+ /// Read `maxIter` from the current parameters; unset values use Spark
defaults.
+ pub fn max_iter(&self) -> i32 {
+ self.params.int_or("maxIter", 20)
+ }
+
+ /// Set `seed`; Spark validates its value when the algorithm runs.
+ pub fn set_seed(mut self, value: i64) -> Self {
+ self.params = self.params.set_param_int_narrow("seed", value);
+ self
+ }
+
+ /// Read `seed` from the current parameters, if explicitly set.
+ pub fn seed(&self) -> Option<i64> {
+ self.params.long_opt("seed")
+ }
+
+ /// Set `checkpointInterval`; Spark validates its value when the algorithm
runs.
+ pub fn set_checkpoint_interval(mut self, value: i32) -> Self {
+ self.params = self.params.set_param_int32("checkpointInterval", value);
+ self
+ }
+
+ /// Read `checkpointInterval` from the current parameters; unset values
use Spark defaults.
+ pub fn checkpoint_interval(&self) -> i32 {
+ self.params.int_or("checkpointInterval", 10)
+ }
+
+ /// Set `k`; Spark validates its value when the algorithm runs.
+ pub fn set_k(mut self, value: i32) -> Self {
+ self.params = self.params.set_param_int32("k", value);
+ self
+ }
+
+ /// Read `k` from the current parameters; unset values use Spark defaults.
+ pub fn k(&self) -> i32 {
+ self.params.int_or("k", 10)
+ }
+
+ /// Set `optimizer`; Spark validates its value when the algorithm runs.
+ pub fn set_optimizer(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("optimizer", value);
+ self
+ }
+
+ /// Read `optimizer` from the current parameters; unset values use Spark
defaults.
+ pub fn optimizer(&self) -> &str {
+ self.params.string_or("optimizer", "online")
+ }
+
+ /// Set `learningOffset`; Spark validates its value when the algorithm
runs.
+ pub fn set_learning_offset(mut self, value: f64) -> Self {
+ self.params = self.params.set_param_double("learningOffset", value);
+ self
+ }
+
+ /// Read `learningOffset` from the current parameters; unset values use
Spark defaults.
+ pub fn learning_offset(&self) -> f64 {
+ self.params.double_or("learningOffset", 1024.0)
+ }
+
+ /// Set `learningDecay`; Spark validates its value when the algorithm runs.
+ pub fn set_learning_decay(mut self, value: f64) -> Self {
+ self.params = self.params.set_param_double("learningDecay", value);
+ self
+ }
+
+ /// Read `learningDecay` from the current parameters; unset values use
Spark defaults.
+ pub fn learning_decay(&self) -> f64 {
+ self.params.double_or("learningDecay", 0.51)
+ }
+
+ /// Set `subsamplingRate`; Spark validates its value when the algorithm
runs.
+ pub fn set_subsampling_rate(mut self, value: f64) -> Self {
+ self.params = self.params.set_param_double("subsamplingRate", value);
+ self
+ }
+
+ /// Read `subsamplingRate` from the current parameters; unset values use
Spark defaults.
+ pub fn subsampling_rate(&self) -> f64 {
+ self.params.double_or("subsamplingRate", 0.05)
+ }
+
+ /// Set `optimizeDocConcentration`; Spark validates its value when the
algorithm runs.
+ pub fn set_optimize_doc_concentration(mut self, value: bool) -> Self {
+ self.params = self
+ .params
+ .set_param_bool("optimizeDocConcentration", value);
+ self
+ }
+
+ /// Read `optimizeDocConcentration` from the current parameters; unset
values use Spark defaults.
+ pub fn optimize_doc_concentration(&self) -> bool {
+ self.params.bool_or("optimizeDocConcentration", true)
+ }
+
+ /// Set `docConcentration`; Spark validates its value when the algorithm
runs.
+ pub fn set_doc_concentration(mut self, value: impl IntoIterator<Item =
f64>) -> Self {
+ self.params = self
+ .params
+ .set_param_double_array("docConcentration", value);
+ self
+ }
+
+ /// Read `docConcentration` from the current parameters, if explicitly set.
+ pub fn doc_concentration(&self) -> Option<Vec<f64>> {
+ self.params.double_array_opt("docConcentration")
+ }
+
+ /// Set `topicConcentration`; Spark validates its value when the algorithm
runs.
+ pub fn set_topic_concentration(mut self, value: f64) -> Self {
+ self.params = self.params.set_param_double("topicConcentration",
value);
+ self
+ }
+
+ /// Read `topicConcentration` from the current parameters, if explicitly
set.
+ pub fn topic_concentration(&self) -> Option<f64> {
+ use proto::expression::literal::LiteralType as L;
+ match self.params.literal("topicConcentration") {
+ Some(L::Double(value)) => Some(*value),
+ Some(L::Integer(value)) => Some(f64::from(*value)),
+ Some(L::Long(value)) => Some(*value as f64),
+ _ => None,
+ }
+ }
+
+ /// Set `topicDistributionCol`; Spark validates its value when the
algorithm runs.
+ pub fn set_topic_distribution_col(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("topicDistributionCol",
value);
+ self
+ }
+
+ /// Read `topicDistributionCol` from the current parameters; unset values
use Spark defaults.
+ pub fn topic_distribution_col(&self) -> &str {
+ self.params
+ .string_or("topicDistributionCol", "topicDistribution")
+ }
+
+ /// Set `keepLastCheckpoint`; Spark validates its value when the algorithm
runs.
+ pub fn set_keep_last_checkpoint(mut self, value: bool) -> Self {
+ self.params = self.params.set_param_bool("keepLastCheckpoint", value);
+ self
+ }
+
+ /// Read `keepLastCheckpoint` from the current parameters; unset values
use Spark defaults.
+ pub fn keep_last_checkpoint(&self) -> bool {
+ self.params.bool_or("keepLastCheckpoint", true)
+ }
+
+ fn model_from_info(
+ &self,
+ info: proto::ml_command_result::MlOperatorInfo,
+ session: &SparkSession,
+ ) -> spark_connect_core::error::Result<LDAModel> {
+ let cached = CachedModel::from_info(&info, session, "LDA")?;
+ let name = if self.optimizer() == "em" {
+ "org.apache.spark.ml.clustering.DistributedLDAModel"
+ } else {
+ "org.apache.spark.ml.clustering.LocalLDAModel"
+ };
+ Ok(LDAModel {
+ operator: MlOperator::with_uid(
+ name,
+ info.uid.as_deref().unwrap_or(&self.operator.uid),
+ OperatorType::Model,
+ ),
+ params: self.params.clone(),
+ cached,
+ })
+ }
+}
+
+impl Default for LDA {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl Estimator for LDA {
+ 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 LDA 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 LDAModel {
+ operator: MlOperator,
+ params: Params,
+ cached: CachedModel,
+}
+
+impl Transformer for LDAModel {
+ 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 LDAModel {
+ fn clone_box(&self) -> Box<dyn Model> {
+ Box::new(self.clone())
+ }
+}
+
+/// Power Iteration Clustering of a graph's nonnegative edge similarities.
+///
+/// Like PySpark's class, this is not an estimator or transformer. Use
+/// [`PowerIterationClustering::assign_clusters`] to obtain `(id, cluster)`
assignments.
+#[derive(Debug, Clone, Default)]
+pub struct PowerIterationClustering {
+ params: Params,
+}
+
+impl PowerIterationClustering {
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ pub fn params(&self) -> &Params {
+ &self.params
+ }
+
+ pub fn params_mut(&mut self) -> &mut Params {
+ &mut self.params
+ }
+
+ /// Set `k`; Spark validates its value when the algorithm runs.
+ pub fn set_k(mut self, value: i32) -> Self {
+ self.params = self.params.set_param_int32("k", value);
+ self
+ }
+
+ /// Read `k` from the current parameters; unset values use Spark defaults.
+ pub fn k(&self) -> i32 {
+ self.params.int_or("k", 2)
+ }
+
+ /// Set `maxIter`; Spark validates its value when the algorithm runs.
+ pub fn set_max_iter(mut self, value: i32) -> Self {
+ self.params = self.params.set_param_int32("maxIter", value);
+ self
+ }
+
+ /// Read `maxIter` from the current parameters; unset values use Spark
defaults.
+ pub fn max_iter(&self) -> i32 {
+ self.params.int_or("maxIter", 20)
+ }
+
+ /// Set `initMode`; Spark validates its value when the algorithm runs.
+ pub fn set_init_mode(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("initMode", value);
+ self
+ }
+
+ /// Read `initMode` from the current parameters; unset values use Spark
defaults.
+ pub fn init_mode(&self) -> &str {
+ self.params.string_or("initMode", "random")
+ }
+
+ /// Set `srcCol`; Spark validates its value when the algorithm runs.
+ pub fn set_src_col(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("srcCol", value);
+ self
+ }
+
+ /// Read `srcCol` from the current parameters; unset values use Spark
defaults.
+ pub fn src_col(&self) -> &str {
+ self.params.string_or("srcCol", "src")
+ }
+
+ /// Set `dstCol`; Spark validates its value when the algorithm runs.
+ pub fn set_dst_col(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("dstCol", value);
+ self
+ }
+
+ /// Read `dstCol` from the current parameters; unset values use Spark
defaults.
+ pub fn dst_col(&self) -> &str {
+ self.params.string_or("dstCol", "dst")
+ }
+
+ /// Set `weightCol`; Spark validates its value when the algorithm runs.
+ pub fn set_weight_col(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("weightCol", value);
+ self
+ }
+
+ /// Read `weightCol` from the current parameters, if explicitly set.
+ pub fn weight_col(&self) -> Option<&str> {
+ self.params.string_opt("weightCol")
+ }
+
+ /// Build the lazy assignment relation using Spark Connect's ML helper.
The input plan
+ /// is retained so cached models or other resources used by the graph
remain alive.
+ pub fn assign_clusters(
+ &self,
+ dataset: &DataFrame,
+ ) -> spark_connect_core::error::Result<DataFrame> {
+ use proto::expression::literal::LiteralType as L;
+ use proto::fetch::method::args::ArgsType;
+
+ let mut params = self.params.to_proto().params;
+ let defaults = [
+ ("k", L::Integer(2)),
+ ("maxIter", L::Integer(20)),
+ ("initMode", L::String("random".into())),
+ ("srcCol", L::String("src".into())),
+ ("dstCol", L::String("dst".into())),
+ ("weightCol", L::String(String::new())),
+ ];
+ let mut args = vec![proto::fetch::method::Args {
+ args_type: Some(ArgsType::Input(dataset.relation()?)),
+ }];
+ for (name, default) in defaults {
+ // Preserve explicit nulls and integer widths, just as PySpark's
helper call does.
+ let literal = params
+ .remove(name)
+ .unwrap_or_else(|| proto::expression::Literal {
+ literal_type: Some(default),
+ ..Default::default()
+ });
+ args.push(proto::fetch::method::Args {
+ args_type: Some(ArgsType::Param(literal)),
+ });
+ }
+ let relation = proto::Relation {
+ rel_type: Some(proto::relation::RelType::MlRelation(Box::new(
+ proto::MlRelation {
+ ml_type:
Some(proto::ml_relation::MlType::Fetch(proto::Fetch {
+ obj_ref: Some(proto::ObjectRef {
+ id: "______ML_CONNECT_HELPER______".into(),
+ }),
+ methods: vec![proto::fetch::Method {
+ method:
"powerIterationClusteringAssignClusters".into(),
+ args,
+ }],
+ })),
+ ..Default::default()
+ },
+ ))),
+ ..Default::default()
+ };
+ Ok(DataFrame::new(
+ dataset.session.clone(),
+ LogicalPlan::MlTransform {
+ ml_relation: relation,
+ input: dataset.plan.clone(),
+ owner: None,
+ },
+ ))
+ }
+}
+
/// RegressionEvaluator: evaluates regression models.
#[derive(Debug, Clone)]
pub struct RegressionEvaluator {
@@ -10588,4 +11012,55 @@ mod tests {
);
assert_eq!(model.operator().uid, "operator-uid");
}
+
+ #[test]
+ fn lda_selects_the_fitted_model_kind_and_pic_retains_its_input_owner() {
+ let session = offline_session();
+ for (optimizer, model_name) in [("online", "LocalLDAModel"), ("em",
"DistributedLDAModel")]
+ {
+ let mut estimator = LDA::new()
+ .set_optimizer(optimizer)
+ .set_topic_distribution_col("topics");
+ assert!(estimator
+ .model_from_info(
+ proto::ml_command_result::MlOperatorInfo::default(),
+ &session
+ )
+ .is_err());
+ let info = proto::ml_command_result::MlOperatorInfo {
+ r#type:
Some(proto::ml_command_result::ml_operator_info::Type::ObjRef(
+ proto::ObjectRef {
+ id: format!("{optimizer}-model"),
+ },
+ )),
+ uid: Some("fitted-uid".into()),
+ ..Default::default()
+ };
+ let mut model = estimator.model_from_info(info, &session).unwrap();
+ assert_eq!(
+ model.operator().name,
+ format!("org.apache.spark.ml.clustering.{model_name}")
+ );
+ assert_eq!(model.operator().uid, "fitted-uid");
+ assert_eq!(model.operator().op_type, OperatorType::Model);
+ *estimator.params_mut() = estimator
+ .params()
+ .clone()
+ .set_param_string("topicDistributionCol", "changed");
+ assert_eq!(
+ model.params().string_or("topicDistributionCol", ""),
+ "topics"
+ );
+ let weak = Arc::downgrade(&model.cached.0);
+ let transformed =
model.transform(&session.range(2).unwrap()).unwrap();
+ let assignments = PowerIterationClustering::new()
+ .assign_clusters(&transformed)
+ .unwrap();
+ drop(model);
+ drop(transformed);
+ assert!(weak.upgrade().is_some());
+ drop(assignments);
+ assert!(weak.upgrade().is_none());
+ }
+ }
}
diff --git a/crates/spark-connect/tests/e2e_remaining_clustering.rs
b/crates/spark-connect/tests/e2e_remaining_clustering.rs
new file mode 100644
index 00000000..77a9d6f9
--- /dev/null
+++ b/crates/spark-connect/tests/e2e_remaining_clustering.rs
@@ -0,0 +1,172 @@
+//! Native clustering execution. Set SPARK_REMOTE to use a live Spark Connect
server.
+mod common;
+
+use common::live_session;
+use serde_json::Value as Json;
+use spark_connect::column::{col, lit_string};
+use spark_connect::expression::Expression;
+use spark_connect::ml::{Estimator, PowerIterationClustering, LDA};
+use spark_connect::row::Value;
+use spark_connect::{Column, DataFrame, SparkSession};
+
+fn fixture() -> Json {
+ serde_json::from_str(include_str!(
+ "../../../tests/golden/remaining_clustering.json"
+ ))
+ .unwrap()
+}
+
+fn documents(s: &SparkSession, rows: &Json) -> DataFrame {
+ let rows = rows
+ .as_array()
+ .unwrap()
+ .iter()
+ .enumerate()
+ .map(|(i, row)| {
+ let values = row
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|v| format!("{}D", v.as_f64().unwrap()))
+ .collect::<Vec<_>>()
+ .join(",");
+ format!("({i}, array({values}))")
+ })
+ .collect::<Vec<_>>()
+ .join(",");
+ s.sql(&format!("SELECT * FROM VALUES {rows} AS t(id, xs)"))
+ .unwrap()
+ .with_column(
+ "input",
+ Column::new(Expression::function(
+ "array_to_vector",
+ vec![col("xs").expression().clone()],
+ )),
+ )
+ .coalesce(1)
+}
+
+fn topics(df: DataFrame) -> Vec<Vec<f64>> {
+ let vector = Column::new(Expression::function(
+ "vector_to_array",
+ vec![
+ col("topics").expression().clone(),
+ lit_string("float64").expression().clone(),
+ ],
+ ));
+ df.order_by(vec![col("id").asc().expression().clone()])
+ .select([vector])
+ .collect()
+ .unwrap()
+ .into_iter()
+ .map(|r| {
+ let Value::List(values) = r.get(0).unwrap() else {
+ panic!("topic vector")
+ };
+ values.iter().map(|v| v.as_f64().unwrap()).collect()
+ })
+ .collect()
+}
+
+#[test]
+fn lda_online_and_em_match_official_and_retain_lazy_predictions() {
+ let Some(s) = live_session() else { return };
+ let golden = fixture();
+ let train = documents(&s, &golden["documents"]);
+ let held = documents(&s, &golden["held_out"]);
+ for case in golden["lda"].as_array().unwrap() {
+ let values = &case["values"];
+ let mut estimator = LDA::new()
+ .set_feature_col("input")
+ .set_topic_distribution_col("topics")
+ .set_k(2)
+ .set_max_iter(10)
+ .set_seed(42)
+ .set_checkpoint_interval(-1)
+ .set_optimizer(values["optimizer"].as_str().unwrap())
+ .set_learning_offset(16.0)
+ .set_learning_decay(0.7)
+ .set_subsampling_rate(1.0)
+ .set_optimize_doc_concentration(false)
+ .set_doc_concentration(
+ values["docConcentration"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|v| v.as_f64().unwrap()),
+ )
+
.set_topic_concentration(values["topicConcentration"].as_f64().unwrap())
+ .set_keep_last_checkpoint(false);
+ let mut model = estimator.fit(&train).unwrap();
+ assert!(model.transform(&s.new_session().range(1).unwrap()).is_err());
+ let mut clone = model.clone_box();
+ let result = clone.transform(&held).unwrap();
+ drop(model);
+ drop(clone);
+ let actual = topics(result);
+ let expected = case["topics"].as_array().unwrap();
+ assert_eq!(actual.len(), expected.len());
+ for (actual, expected) in actual.iter().zip(expected) {
+ assert_eq!(actual.len(), 2);
+ for (actual, expected) in
actual.iter().zip(expected.as_array().unwrap()) {
+ assert!(actual.is_finite() && *actual >= 0.0);
+ assert!((actual - expected.as_f64().unwrap()).abs() < 1e-6);
+ }
+ }
+ }
+}
+
+#[test]
+fn
power_iteration_clustering_matches_official_weighted_and_unweighted_graphs() {
+ let Some(s) = live_session() else { return };
+ let golden = fixture();
+ let rows = golden["edges"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|r| {
+ format!(
+ "({}L, {}L, {}D)",
+ r[0].as_i64().unwrap(),
+ r[1].as_i64().unwrap(),
+ r[2].as_f64().unwrap()
+ )
+ })
+ .collect::<Vec<_>>()
+ .join(",");
+ let graph = s
+ .sql(&format!(
+ "SELECT * FROM VALUES {rows} AS t(source, target, affinity)"
+ ))
+ .unwrap()
+ .repartition(1);
+ for case in golden["pic"].as_array().unwrap() {
+ let values = &case["values"];
+ let mut algorithm = PowerIterationClustering::new()
+ .set_k(2)
+ .set_max_iter(40)
+ .set_init_mode(values["initMode"].as_str().unwrap())
+ .set_src_col("source")
+ .set_dst_col("target");
+ if values.get("weightCol").is_some() {
+ algorithm = algorithm.set_weight_col("affinity");
+ }
+ let result = algorithm.assign_clusters(&graph).unwrap();
+ drop(algorithm);
+ let rows = result
+ .order_by(vec![col("id").asc().expression().clone()])
+ .collect()
+ .unwrap();
+ let expected = case["assignments"].as_array().unwrap();
+ assert_eq!(rows.len(), expected.len());
+ for i in 0..rows.len() {
+ assert_eq!(rows[i].get(0).unwrap().as_i64(),
expected[i][0].as_i64());
+ for j in 0..rows.len() {
+ assert_eq!(
+ rows[i].get(1) == rows[j].get(1),
+ expected[i][1] == expected[j][1]
+ );
+ }
+ }
+ }
+}
diff --git a/crates/spark-connect/tests/remaining_clustering_golden.rs
b/crates/spark-connect/tests/remaining_clustering_golden.rs
new file mode 100644
index 00000000..0810fb05
--- /dev/null
+++ b/crates/spark-connect/tests/remaining_clustering_golden.rs
@@ -0,0 +1,138 @@
+//! Request and parameter parity with the official PySpark clustering client.
+use base64::{engine::general_purpose::STANDARD, Engine};
+use prost::Message;
+use serde_json::{json, Value};
+use spark_connect::ml::{Estimator, PowerIterationClustering, LDA};
+use spark_connect::SparkSession;
+use spark_connect_proto as proto;
+
+fn fixture() -> Value {
+ serde_json::from_str(include_str!(
+ "../../../tests/golden/remaining_clustering.json"
+ ))
+ .unwrap()
+}
+
+fn lda(values: &Value) -> LDA {
+ if values.as_object().unwrap().is_empty() {
+ return LDA::new();
+ }
+ LDA::new()
+ .set_feature_col("input")
+ .set_max_iter(10)
+ .set_seed(values["seed"].as_i64().unwrap())
+ .set_checkpoint_interval(-1)
+ .set_k(2)
+ .set_optimizer("online")
+ .set_learning_offset(16.0)
+ .set_learning_decay(0.7)
+ .set_subsampling_rate(1.0)
+ .set_optimize_doc_concentration(false)
+ .set_doc_concentration([0.5, 0.5])
+ .set_topic_concentration(0.5)
+ .set_topic_distribution_col("topics")
+ .set_keep_last_checkpoint(false)
+}
+
+fn pic(values: &Value) -> PowerIterationClustering {
+ let mut result = if values.get("srcCol").is_some() {
+ PowerIterationClustering::new()
+ .set_k(3)
+ .set_max_iter(40)
+ .set_init_mode("degree")
+ .set_src_col("source")
+ .set_dst_col("target")
+ .set_weight_col("affinity")
+ } else {
+ PowerIterationClustering::new()
+ };
+ if let Some(k) = values.get("k") {
+ *result.params_mut() = if k.is_null() {
+ result.params().clone().set_param_null("k")
+ } else {
+ result
+ .params()
+ .clone()
+ .set_param_int_narrow("k", k.as_i64().unwrap())
+ };
+ }
+ if values.get("weightCol").is_some_and(Value::is_null) {
+ *result.params_mut() =
result.params().clone().set_param_null("weightCol");
+ }
+ result
+}
+
+fn lda_getters(estimator: &LDA) -> Value {
+ json!({
+ "featuresCol": estimator.feature_col(), "maxIter":
estimator.max_iter(),
+ "seed": estimator.seed(), "checkpointInterval":
estimator.checkpoint_interval(),
+ "k": estimator.k(), "optimizer": estimator.optimizer(),
+ "learningOffset": estimator.learning_offset(), "learningDecay":
estimator.learning_decay(),
+ "subsamplingRate": estimator.subsampling_rate(),
+ "optimizeDocConcentration": estimator.optimize_doc_concentration(),
+ "docConcentration": estimator.doc_concentration(),
+ "topicConcentration": estimator.topic_concentration(),
+ "topicDistributionCol": estimator.topic_distribution_col(),
+ "keepLastCheckpoint": estimator.keep_last_checkpoint(),
+ })
+}
+
+#[test]
+fn clustering_parameters_and_defaults_match_official_pyspark() {
+ let golden = fixture();
+ assert_eq!(lda_getters(&LDA::default()), golden["defaults"]["LDA"]);
+ for case in golden["params"].as_array().unwrap() {
+ let bytes = STANDARD
+ .decode(case["params_b64"].as_str().unwrap())
+ .unwrap();
+ let expected = proto::MlParams::decode(bytes.as_slice()).unwrap();
+ if case["class"] == "LDA" {
+ let estimator = lda(&case["values"]);
+ assert_eq!(estimator.params().to_proto(), expected);
+ let mut getters = golden["defaults"]["LDA"].clone();
+ getters
+ .as_object_mut()
+ .unwrap()
+ .extend(case["values"].as_object().unwrap().clone());
+ assert_eq!(lda_getters(&estimator), getters);
+ } else {
+ assert_eq!(pic(&case["values"]).params().to_proto(), expected);
+ }
+ }
+ let default = PowerIterationClustering::default();
+ assert_eq!(
+ json!({"k":default.k(), "maxIter":default.max_iter(),
"initMode":default.init_mode(),
+ "srcCol":default.src_col(), "dstCol":default.dst_col(),
"weightCol":default.weight_col()}),
+ golden["defaults"]["PowerIterationClustering"]
+ );
+}
+
+#[test]
+fn power_iteration_helper_relation_matches_official_pyspark() {
+ let session = SparkSession::builder()
+ .remote("sc://localhost:1")
+ .get_or_create()
+ .unwrap();
+ let input = session.range(1).unwrap();
+ for case in fixture()["pic_fetch"].as_array().unwrap() {
+ let output = pic(&case["values"]).assign_clusters(&input).unwrap();
+ assert_eq!(output.spark_session().session_id(), session.session_id());
+ let Some(proto::relation::RelType::MlRelation(ml)) =
output.to_relation().unwrap().rel_type
+ else {
+ panic!("ML relation")
+ };
+ let Some(proto::ml_relation::MlType::Fetch(mut actual)) = ml.ml_type
else {
+ panic!("helper Fetch")
+ };
+ use proto::fetch::method::args::ArgsType;
+ assert_eq!(
+ actual.methods[0].args[0].args_type,
+ Some(ArgsType::Input(input.to_relation().unwrap()))
+ );
+ actual.methods[0].args[0].args_type =
Some(ArgsType::Input(proto::Relation::default()));
+ let bytes = STANDARD
+ .decode(case["fetch_b64"].as_str().unwrap())
+ .unwrap();
+ assert_eq!(actual, proto::Fetch::decode(bytes.as_slice()).unwrap());
+ }
+}
diff --git a/docs/compatibility.md b/docs/compatibility.md
index fc8cd320..6fc296b3 100644
--- a/docs/compatibility.md
+++ b/docs/compatibility.md
@@ -786,3 +786,35 @@ Parameter goldens come from official PySpark 4.3.0. Native
Rust and Python tests
exercise censoring and quantiles, weighted isotonic interpolation, both FM
solvers, validation errors and cached-model lifetimes. The Python behavior
tests
also run unchanged against the official client.
+
+
+## Native LDA and PowerIterationClustering
+
+The native Rust and Python APIs now implement all five clustering algorithms in
+PySpark 4.3.0: KMeans, BisectingKMeans, GaussianMixture, LDA and
PowerIterationClustering.
+This describes algorithm execution, not complete model-inspection or
persistence parity.
+
+Rust `ml::LDA` supports online and EM training and cached-model DataFrame
transforms.
+Python exposes `LDA` through `pyspark.ml.connect` and
`pyspark.ml.connect.clustering`;
+`fit` returns the shared native `MLModel`. All 14 constructor parameters have
Python
+setters and Rust builder setters/getters, including document/topic
concentrations,
+learning settings, checkpoint settings, seed and topic-distribution output
column.
+Both optimizers return a vector of topic probabilities per document; empty
documents
+produce zero vectors. Python also accepts numeric array feature columns on
Spark
+DataFrames and preserves those arrays in the transformed output.
+
+`ml::PowerIterationClustering::assign_clusters` and Python `assignClusters`
build
+Spark Connect's `powerIterationClusteringAssignClusters` helper relation. This
algorithm
+has no fit/transform API or fitted model. It accepts source/destination vertex
columns
+and optional nonnegative edge weights, with `k`, `maxIter` and `initMode`
settings, and
+returns a Spark DataFrame with `id: bigint` and `cluster: int`. Parameter
values are
+captured when the relation is built. Omitting `weightCol` uses unweighted
edges; an
+explicit null remains distinct from an omitted parameter and is validated by
Spark.
+The lazy relation retains any cached models used by its input DataFrame.
+
+Both APIs require Spark DataFrames and reject pandas inputs. Reference-derived
golden
+fixtures and live tests cover both LDA optimizers, dense/sparse inputs, graph
initialization
+modes, weighted/unweighted graphs, custom columns, setters, validation and
model lifetime.
+LDA topic matrices, likelihood/perplexity methods, topic descriptions,
distributed-model
+inspection/conversion and persistence are outside this native 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 4a610ba9..dd7d1598 100644
--- a/python/pyspark/ml/connect/__init__.py
+++ b/python/pyspark/ml/connect/__init__.py
@@ -31,7 +31,9 @@ from pyspark.ml.connect.regression import (
LinearRegression,
RandomForestRegressor,
)
-from pyspark.ml.connect.clustering import BisectingKMeans, GaussianMixture,
KMeans
+from pyspark.ml.connect.clustering import (
+ LDA, BisectingKMeans, GaussianMixture, KMeans, PowerIterationClustering,
+)
from pyspark.ml.connect.evaluation import (
RegressionEvaluator,
BinaryClassificationEvaluator,
@@ -88,6 +90,8 @@ __all__ = [
"DecisionTreeRegressor",
"RandomForestRegressor",
"KMeans",
+ "LDA",
+ "PowerIterationClustering",
"GaussianMixture",
"BisectingKMeans",
"RegressionEvaluator",
diff --git a/python/pyspark/ml/connect/clustering.py
b/python/pyspark/ml/connect/clustering.py
index 33748e0a..703890e5 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, GaussianMixture, KMeans
+"""Native clustering algorithms backed by Spark Connect's JVM ML API."""
+from pyspark._pyspark import LDA, BisectingKMeans, GaussianMixture, KMeans,
PowerIterationClustering
-__all__ = ["GaussianMixture", "BisectingKMeans", "KMeans"]
+__all__ = ["BisectingKMeans", "GaussianMixture", "KMeans", "LDA",
"PowerIterationClustering"]
diff --git a/python/tests/test_ml_offline.py b/python/tests/test_ml_offline.py
index d809da11..6a3ae33b 100644
--- a/python/tests/test_ml_offline.py
+++ b/python/tests/test_ml_offline.py
@@ -815,6 +815,7 @@ def
test_ml_pipeline_and_cross_validator_fit_is_not_implemented(ml_mock):
# param in PySpark. Their constructors take them all but thresholds, which
PySpark's
# RandomForestClassifier takes by its setter only.
_NATIVE_PARAMS = {
+ "LDA": {'featuresCol': 'str', 'maxIter': 'int', 'seed': 'int',
'checkpointInterval': 'int', 'k': 'int', 'optimizer': 'str', 'learningOffset':
'float', 'learningDecay': 'float', 'subsamplingRate': 'float',
'optimizeDocConcentration': 'bool', 'docConcentration': 'float_list',
'topicConcentration': 'float', 'topicDistributionCol': 'str',
'keepLastCheckpoint': 'bool'},
'AFTSurvivalRegression': {'featuresCol': 'str', 'labelCol': 'str',
'predictionCol': 'str', 'fitIntercept': 'bool', 'maxIter': 'int', 'tol':
'float', 'censorCol': 'str', 'quantileProbabilities': 'float_list',
'quantilesCol': 'str', 'aggregationDepth': 'int', 'maxBlockSizeInMB': 'float'},
'IsotonicRegression': {'featuresCol': 'str', 'labelCol': 'str',
'predictionCol': 'str', 'weightCol': 'str', 'isotonic': 'bool', 'featureIndex':
'int'},
'FMRegressor': {'featuresCol': 'str', 'labelCol': 'str', 'predictionCol':
'str', 'factorSize': 'int', 'fitIntercept': 'bool', 'fitLinear': 'bool',
'regParam': 'float', 'miniBatchFraction': 'float', 'initStd': 'float',
'maxIter': 'int', 'stepSize': 'float', 'tol': 'float', 'solver': 'str', 'seed':
'int'},
@@ -3736,12 +3737,13 @@ def _native_ml_method(name):
import pyspark.ml.connect as connect
instance = getattr(connect, name)()
- method = ("evaluate" if name.endswith("Evaluator") else
+ method = ("assignClusters" if name == "PowerIterationClustering" else
+ "evaluate" if name.endswith("Evaluator") else
"transform" if name == "VectorAssembler" else "fit")
return getattr(instance, method)
[email protected]("name", [*_NATIVE_PARAMS, "OneVsRest"])
[email protected]("name", [*_NATIVE_PARAMS, "OneVsRest",
"PowerIterationClustering"])
def test_native_ml_rejects_pandas_without_active_session(name,
pandas_ml_input):
assert SparkSession.getActiveSession() is None
method = _native_ml_method(name)
@@ -3769,7 +3771,7 @@ def
test_native_ml_rejects_pandas_before_any_requests(ml_mock, pandas_ml_input,
len(service.config_requests))
sent = requests()
- methods = [_native_ml_method(name) for name in [*_NATIVE_PARAMS,
"OneVsRest"]]
+ methods = [_native_ml_method(name) for name in [*_NATIVE_PARAMS,
"OneVsRest", "PowerIterationClustering"]]
methods += [model.transform, connect.OneVsRest(parallelism=0).fit,
connect.LogisticRegression(maxIter=2**100).fit,
connect.VectorAssembler(inputCols=[]).transform]
@@ -3777,3 +3779,75 @@ def
test_native_ml_rejects_pandas_before_any_requests(ml_mock, pandas_ml_input,
with pytest.raises(TypeError, match="requires a Spark DataFrame"):
method(pandas_ml_input)
assert requests() == sent
+
+
[email protected]("name", ["LDA", "PowerIterationClustering"])
+def test_remaining_clustering_signatures_and_native_exports(name):
+ import inspect
+ import json
+ from pathlib import Path
+
+ import pyspark.ml.connect as connect
+ from pyspark import _pyspark
+ from pyspark.ml.connect import clustering
+
+ cls = getattr(clustering, name)
+ assert cls is getattr(_pyspark, name) is getattr(connect, name)
+ fixture = json.loads((Path(__file__).parents[2] /
"tests/golden/remaining_clustering.json").read_text())
+ parameters = inspect.signature(cls).parameters
+ assert list(parameters) == list(fixture["defaults"][name])
+ for param, default in fixture["defaults"][name].items():
+ assert parameters[param].kind == inspect.Parameter.KEYWORD_ONLY
+ assert parameters[param].default == default
+ assert hasattr(cls, "set" + param[0].upper() + param[1:])
+
+
+def test_pic_helper_request_matches_official_and_is_lazy(ml_mock):
+ import base64
+ import json
+ from pathlib import Path
+
+ from pyspark.ml.connect import PowerIterationClustering
+
+ spark, service = ml_mock
+ fixture = json.loads((Path(__file__).parents[2] /
"tests/golden/remaining_clustering.json").read_text())
+ df = spark.range(1)
+ sent = (_requests_but_deletes(service), len(service.analyze_requests),
len(service.config_requests))
+ for case in fixture["pic_fetch"]:
+ result =
PowerIterationClustering(**case["values"]).assignClusters(dataset=df)
+ actual = _relation(result).ml_relation.fetch
+ assert actual.methods[0].args[0].input == _relation(df)
+ actual.methods[0].args[0].input.Clear()
+ assert actual ==
pb2.Fetch.FromString(base64.b64decode(case["fetch_b64"]))
+ assert (_requests_but_deletes(service), len(service.analyze_requests),
len(service.config_requests)) == sent
+
+
+def test_pic_parameter_converters_and_deferred_overflow(ml_mock):
+ from pyspark.ml.connect import PowerIterationClustering
+
+ spark, service = ml_mock
+ names = ["k", "maxIter", "initMode", "srcCol", "dstCol", "weightCol"]
+ for index, name in enumerate(names):
+ setter = "set" + name[0].upper() + name[1:]
+ kind = "int" if index < 2 else "str"
+ for value, expected in _NATIVE_CONVERTED[kind]:
+ original = PowerIterationClustering()
+ configured = getattr(original, setter)(value)
+ assert configured is original
+ for instance in [configured, PowerIterationClustering(**{name:
value})]:
+ fetch =
_relation(instance.assignClusters(spark.range(1))).ml_relation.fetch
+ assert _literal_value(fetch.methods[0].args[index + 1].param)
== expected
+ for value, _ in _NATIVE_REJECTED[kind]:
+ with pytest.raises(TypeError):
+ getattr(PowerIterationClustering(), setter)(value)
+ with pytest.raises(TypeError):
+ PowerIterationClustering(**{name: value})
+ with pytest.raises(TypeError, match="keyword arguments"):
+ PowerIterationClustering(2)
+ with pytest.raises(TypeError, match="unexpected keyword argument"):
+ PowerIterationClustering(seed=42)
+ for name in ["k", "maxIter"]:
+ with pytest.raises(PySparkValueError) as error:
+ PowerIterationClustering(**{name:
2**100}).assignClusters(spark.range(1))
+ assert error.value.getCondition() == "VALUE_NOT_BETWEEN"
+ assert _requests_but_deletes(service) == 0
diff --git a/python/tests/test_remaining_clustering_e2e.py
b/python/tests/test_remaining_clustering_e2e.py
new file mode 100644
index 00000000..3bc9a8da
--- /dev/null
+++ b/python/tests/test_remaining_clustering_e2e.py
@@ -0,0 +1,200 @@
+#
+# 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.
+#
+"""Remaining native clustering algorithms, with an explicit official-reference
mode."""
+
+import gc
+import json
+import math
+import os
+from pathlib import Path
+
+import pytest
+from pyspark.errors import PySparkException
+from pyspark.ml.functions import vector_to_array
+from pyspark.ml.linalg import Vectors
+from pyspark.sql import SparkSession
+from pyspark.sql import functions as F
+
+GOLDEN = json.loads((Path(__file__).parents[2] /
"tests/golden/remaining_clustering.json").read_text())
+REFERENCE = os.environ.get("CLUSTERING_REFERENCE") == "1"
+
+
[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 _algorithm(name):
+ if REFERENCE:
+ from pyspark.ml import clustering
+ return getattr(clustering, name)
+ from pyspark import _pyspark
+ from pyspark.ml.connect import clustering
+ cls = getattr(clustering, name)
+ assert cls is getattr(_pyspark, name), "The native tests must exercise the
Rust bindings"
+ return cls
+
+
+def _configured(name, values, setters):
+ cls = _algorithm(name)
+ if not setters:
+ return cls(**values)
+ instance = cls()
+ for key, value in values.items():
+ assert getattr(instance, "set" + key[0].upper() + key[1:])(value) is
instance
+ return instance
+
+
+def _documents(session, rows, arrays=False):
+ def vector(i, values):
+ if arrays:
+ return values
+ if i % 2:
+ return Vectors.sparse(len(values), {j: x for j, x in
enumerate(values) if x})
+ return Vectors.dense(values)
+ return session.createDataFrame([(i, vector(i, x)) for i, x in
enumerate(rows)], ["id", "input"]).coalesce(1)
+
+
+def _topics(model, frame):
+ return
model.transform(frame).orderBy("id").select(vector_to_array("topics").alias("p"))
+
+
[email protected]("case", GOLDEN["lda"], ids=lambda c:
c["values"]["optimizer"])
[email protected]("setters", [False, True], ids=["constructor",
"setters"])
+def
test_lda_matches_official_dense_sparse_inference_and_retains_model(session,
case, setters):
+ train = _documents(session, GOLDEN["documents"])
+ held = _documents(session, GOLDEN["held_out"])
+ estimator = _configured("LDA", case["values"], setters)
+ model = estimator.fit(train)
+ predictions = _topics(model, held)
+ estimator.setTopicDistributionCol("changed")
+ del model, estimator
+ gc.collect()
+ rows = predictions.collect()
+ assert len(rows) == len(case["topics"])
+ for row, expected in zip(rows, case["topics"]):
+ assert list(row.p) == pytest.approx(expected, rel=1e-6, abs=1e-8)
+ assert all(math.isfinite(x) and x >= 0 for x in row.p)
+ assert list(rows[-1].p) == [0.0, 0.0]
+ for row in rows[:-1]:
+ assert sum(row.p) == pytest.approx(1.0)
+ labels = [max(range(2), key=row.p.__getitem__) for row in rows[:-1]]
+ assert labels[0] == labels[1] and labels[2] == labels[3] and labels[0] !=
labels[2]
+
+
[email protected]("optimizer", ["online", "em"])
+def test_lda_repeated_fits_keep_independent_topic_counts(session, optimizer):
+ train = _documents(session, GOLDEN["documents"])
+ estimator = _algorithm("LDA")(featuresCol="input",
topicDistributionCol="topics", k=2,
+ maxIter=3, seed=2**33, optimizer=optimizer,
+ subsamplingRate=1.0, checkpointInterval=-1)
+ first = estimator.fit(train)
+ second = estimator.setK(3).fit(train)
+ assert all(len(r.p) == 2 for r in _topics(first, train).collect())
+ assert all(len(r.p) == 3 for r in _topics(second, train).collect())
+
+
[email protected](REFERENCE, reason="Numeric array features are a native
client extension")
+def test_lda_native_array_features_are_preserved(session):
+ train = _documents(session, GOLDEN["documents"], arrays=True)
+ model = _algorithm("LDA")(**GOLDEN["lda"][0]["values"]).fit(train)
+ out = model.transform(train).orderBy("id").select("input",
vector_to_array("topics").alias("p")).collect()
+ for row, features in zip(out, GOLDEN["documents"]):
+ assert list(row.input) == features
+ assert sum(row.p) == pytest.approx(1.0)
+
+
[email protected]("options", [{"k": 1}, {"maxIter": -1}, {"optimizer":
"unknown"}, {"learningDecay": 0.0}])
+def test_lda_rejects_invalid_configuration(session, options):
+ with pytest.raises(PySparkException):
+ _algorithm("LDA")(featuresCol="input",
**options).fit(_documents(session, GOLDEN["documents"]))
+
+
[email protected]("kind", ["empty", "nonvector"])
+def test_lda_rejects_invalid_training_data(session, kind):
+ train = _documents(session, GOLDEN["documents"])
+ if kind == "empty":
+ train = train.limit(0)
+ else:
+ train = train.withColumn("input", F.lit(1.0))
+ with pytest.raises(PySparkException):
+ _algorithm("LDA")(featuresCol="input", k=2, maxIter=2).fit(train)
+
+
+def _graph(session):
+ return session.createDataFrame([tuple(x) for x in GOLDEN["edges"]],
["source", "target", "affinity"]).repartition(1)
+
+
+def _assert_partition(actual, expected):
+ assert [r.id for r in actual] == [r[0] for r in expected]
+ for i in range(len(actual)):
+ for j in range(len(actual)):
+ assert (actual[i].cluster == actual[j].cluster) == (expected[i][1]
== expected[j][1])
+
+
[email protected]("case", GOLDEN["pic"], ids=lambda c:
c["values"]["initMode"] + ("-weighted" if "weightCol" in c["values"] else
"-unweighted"))
[email protected]("setters", [False, True], ids=["constructor",
"setters"])
+def test_pic_matches_official_assignments_and_snapshots_parameters(session,
case, setters):
+ algorithm = _configured("PowerIterationClustering", case["values"],
setters)
+ result = algorithm.assignClusters(_graph(session))
+ algorithm.setK(1) # An invalid later mutation cannot change the
already-built relation.
+ del algorithm
+ gc.collect()
+ assert [(f.name, f.dataType.simpleString()) for f in result.schema.fields]
== [("id", "bigint"), ("cluster", "int")]
+ _assert_partition(result.orderBy("id").collect(), case["assignments"])
+
+
+def test_pic_default_columns_and_empty_weight_column(session):
+ graph = _graph(session).selectExpr("source AS src", "target AS dst",
"affinity AS weight")
+ cls = _algorithm("PowerIterationClustering")
+ default = cls().assignClusters(graph).orderBy("id").collect()
+ empty_weight =
cls(weightCol="").assignClusters(graph).orderBy("id").collect()
+ _assert_partition(default, [[r.id, r.cluster] for r in empty_weight])
+ assert [r.id for r in default] == list(range(6))
+
+
[email protected]("options", [{"k": 1}, {"maxIter": -1}, {"initMode":
"unknown"}, {"weightCol": "missing"}])
+def test_pic_rejects_invalid_configuration(session, options):
+ values = dict(srcCol="source", dstCol="target", **options)
+ with pytest.raises(PySparkException):
+
_algorithm("PowerIterationClustering")(**values).assignClusters(_graph(session)).collect()
+
+
+def test_pic_rejects_negative_edge_weights(session):
+ graph = _graph(session).withColumn("affinity", -F.col("affinity"))
+ with pytest.raises(PySparkException):
+ _algorithm("PowerIterationClustering")(srcCol="source",
dstCol="target", weightCol="affinity").assignClusters(graph).collect()
+
+
[email protected](REFERENCE, reason="Official PIC loses the cached input
model after GC; native plans retain it")
+def test_pic_retains_cached_models_in_its_input_plan(session):
+ lda =
_algorithm("LDA")(**GOLDEN["lda"][0]["values"]).fit(_documents(session,
GOLDEN["documents"]))
+ from pyspark.ml.functions import array_to_vector
+ graph = _graph(session).withColumn("input",
array_to_vector(F.array(*[F.lit(x) for x in GOLDEN["documents"][0]])))
+ transformed = lda.transform(graph).select("source", "target", "affinity")
+ case = GOLDEN["pic"][-1]
+ result =
_algorithm("PowerIterationClustering")(**case["values"]).assignClusters(transformed)
+ del lda, graph, transformed
+ gc.collect()
+ _assert_partition(result.orderBy("id").collect(), case["assignments"])
diff --git a/scripts/capture_remaining_clustering_golden.py
b/scripts/capture_remaining_clustering_golden.py
new file mode 100644
index 00000000..33056745
--- /dev/null
+++ b/scripts/capture_remaining_clustering_golden.py
@@ -0,0 +1,152 @@
+#!/usr/bin/env python3
+"""Capture LDA and PowerIterationClustering goldens with official PySpark
4.3.0."""
+
+import argparse
+import base64
+import inspect
+import json
+from pathlib import Path
+
+import pyspark
+from pyspark.ml import clustering
+from pyspark.ml.connect.serialize import serialize_ml_params
+from pyspark.ml.functions import vector_to_array
+from pyspark.ml.linalg import Vectors
+from pyspark.sql import SparkSession
+
+LDA_VALUES = dict(
+ featuresCol="input",
+ maxIter=10,
+ seed=42,
+ checkpointInterval=-1,
+ k=2,
+ optimizer="online",
+ learningOffset=16.0,
+ learningDecay=0.7,
+ subsamplingRate=1.0,
+ optimizeDocConcentration=False,
+ docConcentration=[0.5, 0.5],
+ topicConcentration=0.5,
+ topicDistributionCol="topics",
+ keepLastCheckpoint=False,
+)
+PIC_VALUES = dict(
+ k=3, maxIter=40, initMode="degree", srcCol="source", dstCol="target",
weightCol="affinity"
+)
+DOCUMENTS = [
+ [10.0, 8.0, 2.0, 0.0, 0.0, 0.0],
+ [8.0, 10.0, 1.0, 0.0, 0.0, 0.0],
+ [9.0, 7.0, 3.0, 0.0, 0.0, 0.0],
+ [12.0, 6.0, 2.0, 0.0, 0.0, 0.0],
+ [7.0, 9.0, 3.0, 0.0, 0.0, 0.0],
+ [11.0, 8.0, 1.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 10.0, 8.0, 2.0],
+ [0.0, 0.0, 0.0, 8.0, 10.0, 1.0],
+ [0.0, 0.0, 0.0, 9.0, 7.0, 3.0],
+ [0.0, 0.0, 0.0, 12.0, 6.0, 2.0],
+ [0.0, 0.0, 0.0, 7.0, 9.0, 3.0],
+ [0.0, 0.0, 0.0, 11.0, 8.0, 1.0],
+]
+HELD_OUT = [
+ [8.0, 6.0, 1.0, 0.0, 0.0, 0.0],
+ [10.0, 9.0, 2.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 8.0, 6.0, 1.0],
+ [0.0, 0.0, 0.0, 10.0, 9.0, 2.0],
+ [0.0] * 6,
+]
+EDGES = [(i, j, 0.5 + j * 0.2) for i in range(1, 6) for j in range(i)]
+
+
+def encoded(message):
+ return
base64.b64encode(message.SerializeToString(deterministic=True)).decode()
+
+
+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/remaining_clustering.json"))
+ args = parser.parse_args()
+ assert pyspark.__version__ == "4.3.0", pyspark.__version__
+ spark = SparkSession.builder.remote(args.remote).getOrCreate()
+ result = {
+ "spark_version": pyspark.__version__,
+ "defaults": {},
+ "params": [],
+ "pic_fetch": [],
+ "documents": DOCUMENTS,
+ "held_out": HELD_OUT,
+ "edges": EDGES,
+ "lda": [],
+ "pic": [],
+ }
+ try:
+ for name, values in [("LDA", LDA_VALUES), ("PowerIterationClustering",
PIC_VALUES)]:
+ cls = getattr(clustering, name)
+ result["defaults"][name] = {
+ k: v.default for k, v in
inspect.signature(cls).parameters.items()
+ }
+ variants = [{}, values]
+ if name == "LDA":
+ variants += [
+ dict(values, seed=seed)
+ for seed in [2**31 - 1, 2**31, -(2**31) - 1, 2**63 - 1,
-(2**63)]
+ ]
+ else:
+ variants += [{"weightCol": None}, {"k": 2**31}, {"k": None}]
+ for variant in variants:
+ instance = cls(**variant)
+ result["params"].append(
+ {
+ "class": name,
+ "values": variant,
+ "params_b64": encoded(serialize_ml_params(instance,
spark.client)),
+ }
+ )
+ if name == "PowerIterationClustering":
+ fetch = (
+ instance.assignClusters(spark.range(1))
+ ._plan.plan(spark.client)
+ .ml_relation.fetch
+ )
+ fetch.methods[0].args[0].input.Clear()
+ result["pic_fetch"].append({"values": variant,
"fetch_b64": encoded(fetch)})
+ train = spark.createDataFrame(
+ [(i, Vectors.dense(x)) for i, x in enumerate(DOCUMENTS)], ["id",
"input"]
+ ).coalesce(1)
+ held = spark.createDataFrame(
+ [(i, Vectors.dense(x)) for i, x in enumerate(HELD_OUT)], ["id",
"input"]
+ )
+ for optimizer in ["online", "em"]:
+ values = dict(LDA_VALUES, optimizer=optimizer)
+ if optimizer == "em":
+ values.update(docConcentration=[2.0, 2.0],
topicConcentration=2.0)
+ model = clustering.LDA(**values).fit(train)
+ rows = (
+ model.transform(held)
+ .orderBy("id")
+ .select(vector_to_array("topics").alias("topics"))
+ .collect()
+ )
+ result["lda"].append({"values": values, "topics": [r.topics for r
in rows]})
+ graph = spark.createDataFrame(EDGES, ["source", "target",
"affinity"]).repartition(1)
+ for init_mode in ["random", "degree"]:
+ for weighted in [False, True]:
+ values = dict(PIC_VALUES, k=2, initMode=init_mode)
+ if not weighted:
+ values.pop("weightCol")
+ rows = (
+ clustering.PowerIterationClustering(**values)
+ .assignClusters(graph)
+ .orderBy("id")
+ .collect()
+ )
+ result["pic"].append(
+ {"values": values, "assignments": [[r.id, r.cluster] for r
in rows]}
+ )
+ args.out.write_text(json.dumps(result, indent=2) + "\n")
+ finally:
+ spark.stop()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/golden/remaining_clustering.json
b/tests/golden/remaining_clustering.json
new file mode 100644
index 00000000..35410f0a
--- /dev/null
+++ b/tests/golden/remaining_clustering.json
@@ -0,0 +1,696 @@
+{
+ "spark_version": "4.3.0",
+ "defaults": {
+ "LDA": {
+ "featuresCol": "features",
+ "maxIter": 20,
+ "seed": null,
+ "checkpointInterval": 10,
+ "k": 10,
+ "optimizer": "online",
+ "learningOffset": 1024.0,
+ "learningDecay": 0.51,
+ "subsamplingRate": 0.05,
+ "optimizeDocConcentration": true,
+ "docConcentration": null,
+ "topicConcentration": null,
+ "topicDistributionCol": "topicDistribution",
+ "keepLastCheckpoint": true
+ },
+ "PowerIterationClustering": {
+ "k": 2,
+ "maxIter": 20,
+ "initMode": "random",
+ "srcCol": "src",
+ "dstCol": "dst",
+ "weightCol": null
+ }
+ },
+ "params": [
+ {
+ "class": "LDA",
+ "values": {},
+ "params_b64": ""
+ },
+ {
+ "class": "LDA",
+ "values": {
+ "featuresCol": "input",
+ "maxIter": 10,
+ "seed": 42,
+ "checkpointInterval": -1,
+ "k": 2,
+ "optimizer": "online",
+ "learningOffset": 16.0,
+ "learningDecay": 0.7,
+ "subsamplingRate": 1.0,
+ "optimizeDocConcentration": false,
+ "docConcentration": [
+ 0.5,
+ 0.5
+ ],
+ "topicConcentration": 0.5,
+ "topicDistributionCol": "topics",
+ "keepLastCheckpoint": false
+ },
+ "params_b64":
"CiEKEmNoZWNrcG9pbnRJbnRlcnZhbBILMP///////////wEKMQoQZG9jQ29uY2VudHJhdGlvbhIdsgEaCgJKABIJWQAAAAAAAOA/EglZAAAAAAAA4D8KFgoLZmVhdHVyZXNDb2wSB2oFaW5wdXQKGAoSa2VlcExhc3RDaGVja3BvaW50EgIYAAoHCgFrEgIwAgoaCg1sZWFybmluZ0RlY2F5EglZZmZmZmZm5j8KGwoObGVhcm5pbmdPZmZzZXQSCVkAAAAAAAAwQAoNCgdtYXhJdGVyEgIwCgoeChhvcHRpbWl6ZURvY0NvbmNlbnRyYXRpb24SAhgAChUKCW9wdGltaXplchIIagZvbmxpbmUKCgoEc2VlZBICMCoKHAoPc3Vic2FtcGxpbmdSYXRlEglZAAAAAAAA8D8KHwoSdG9waWNDb25jZW50cmF0aW9uEglZAAAAAAAA4D8KIAoUdG9
[...]
+ },
+ {
+ "class": "LDA",
+ "values": {
+ "featuresCol": "input",
+ "maxIter": 10,
+ "seed": 2147483647,
+ "checkpointInterval": -1,
+ "k": 2,
+ "optimizer": "online",
+ "learningOffset": 16.0,
+ "learningDecay": 0.7,
+ "subsamplingRate": 1.0,
+ "optimizeDocConcentration": false,
+ "docConcentration": [
+ 0.5,
+ 0.5
+ ],
+ "topicConcentration": 0.5,
+ "topicDistributionCol": "topics",
+ "keepLastCheckpoint": false
+ },
+ "params_b64":
"CiEKEmNoZWNrcG9pbnRJbnRlcnZhbBILMP///////////wEKMQoQZG9jQ29uY2VudHJhdGlvbhIdsgEaCgJKABIJWQAAAAAAAOA/EglZAAAAAAAA4D8KFgoLZmVhdHVyZXNDb2wSB2oFaW5wdXQKGAoSa2VlcExhc3RDaGVja3BvaW50EgIYAAoHCgFrEgIwAgoaCg1sZWFybmluZ0RlY2F5EglZZmZmZmZm5j8KGwoObGVhcm5pbmdPZmZzZXQSCVkAAAAAAAAwQAoNCgdtYXhJdGVyEgIwCgoeChhvcHRpbWl6ZURvY0NvbmNlbnRyYXRpb24SAhgAChUKCW9wdGltaXplchIIagZvbmxpbmUKDgoEc2VlZBIGMP////8HChwKD3N1YnNhbXBsaW5nUmF0ZRIJWQAAAAAAAPA/Ch8KEnRvcGljQ29uY2VudHJhdGlvbhIJWQAAAAAAAOA/CiA
[...]
+ },
+ {
+ "class": "LDA",
+ "values": {
+ "featuresCol": "input",
+ "maxIter": 10,
+ "seed": 2147483648,
+ "checkpointInterval": -1,
+ "k": 2,
+ "optimizer": "online",
+ "learningOffset": 16.0,
+ "learningDecay": 0.7,
+ "subsamplingRate": 1.0,
+ "optimizeDocConcentration": false,
+ "docConcentration": [
+ 0.5,
+ 0.5
+ ],
+ "topicConcentration": 0.5,
+ "topicDistributionCol": "topics",
+ "keepLastCheckpoint": false
+ },
+ "params_b64":
"CiEKEmNoZWNrcG9pbnRJbnRlcnZhbBILMP///////////wEKMQoQZG9jQ29uY2VudHJhdGlvbhIdsgEaCgJKABIJWQAAAAAAAOA/EglZAAAAAAAA4D8KFgoLZmVhdHVyZXNDb2wSB2oFaW5wdXQKGAoSa2VlcExhc3RDaGVja3BvaW50EgIYAAoHCgFrEgIwAgoaCg1sZWFybmluZ0RlY2F5EglZZmZmZmZm5j8KGwoObGVhcm5pbmdPZmZzZXQSCVkAAAAAAAAwQAoNCgdtYXhJdGVyEgIwCgoeChhvcHRpbWl6ZURvY0NvbmNlbnRyYXRpb24SAhgAChUKCW9wdGltaXplchIIagZvbmxpbmUKDgoEc2VlZBIGOICAgIAIChwKD3N1YnNhbXBsaW5nUmF0ZRIJWQAAAAAAAPA/Ch8KEnRvcGljQ29uY2VudHJhdGlvbhIJWQAAAAAAAOA/CiA
[...]
+ },
+ {
+ "class": "LDA",
+ "values": {
+ "featuresCol": "input",
+ "maxIter": 10,
+ "seed": -2147483649,
+ "checkpointInterval": -1,
+ "k": 2,
+ "optimizer": "online",
+ "learningOffset": 16.0,
+ "learningDecay": 0.7,
+ "subsamplingRate": 1.0,
+ "optimizeDocConcentration": false,
+ "docConcentration": [
+ 0.5,
+ 0.5
+ ],
+ "topicConcentration": 0.5,
+ "topicDistributionCol": "topics",
+ "keepLastCheckpoint": false
+ },
+ "params_b64":
"CiEKEmNoZWNrcG9pbnRJbnRlcnZhbBILMP///////////wEKMQoQZG9jQ29uY2VudHJhdGlvbhIdsgEaCgJKABIJWQAAAAAAAOA/EglZAAAAAAAA4D8KFgoLZmVhdHVyZXNDb2wSB2oFaW5wdXQKGAoSa2VlcExhc3RDaGVja3BvaW50EgIYAAoHCgFrEgIwAgoaCg1sZWFybmluZ0RlY2F5EglZZmZmZmZm5j8KGwoObGVhcm5pbmdPZmZzZXQSCVkAAAAAAAAwQAoNCgdtYXhJdGVyEgIwCgoeChhvcHRpbWl6ZURvY0NvbmNlbnRyYXRpb24SAhgAChUKCW9wdGltaXplchIIagZvbmxpbmUKEwoEc2VlZBILOP/////3/////wEKHAoPc3Vic2FtcGxpbmdSYXRlEglZAAAAAAAA8D8KHwoSdG9waWNDb25jZW50cmF0aW9uEglZAAAAAAA
[...]
+ },
+ {
+ "class": "LDA",
+ "values": {
+ "featuresCol": "input",
+ "maxIter": 10,
+ "seed": 9223372036854775807,
+ "checkpointInterval": -1,
+ "k": 2,
+ "optimizer": "online",
+ "learningOffset": 16.0,
+ "learningDecay": 0.7,
+ "subsamplingRate": 1.0,
+ "optimizeDocConcentration": false,
+ "docConcentration": [
+ 0.5,
+ 0.5
+ ],
+ "topicConcentration": 0.5,
+ "topicDistributionCol": "topics",
+ "keepLastCheckpoint": false
+ },
+ "params_b64":
"CiEKEmNoZWNrcG9pbnRJbnRlcnZhbBILMP///////////wEKMQoQZG9jQ29uY2VudHJhdGlvbhIdsgEaCgJKABIJWQAAAAAAAOA/EglZAAAAAAAA4D8KFgoLZmVhdHVyZXNDb2wSB2oFaW5wdXQKGAoSa2VlcExhc3RDaGVja3BvaW50EgIYAAoHCgFrEgIwAgoaCg1sZWFybmluZ0RlY2F5EglZZmZmZmZm5j8KGwoObGVhcm5pbmdPZmZzZXQSCVkAAAAAAAAwQAoNCgdtYXhJdGVyEgIwCgoeChhvcHRpbWl6ZURvY0NvbmNlbnRyYXRpb24SAhgAChUKCW9wdGltaXplchIIagZvbmxpbmUKEgoEc2VlZBIKOP//////////fwocCg9zdWJzYW1wbGluZ1JhdGUSCVkAAAAAAADwPwofChJ0b3BpY0NvbmNlbnRyYXRpb24SCVkAAAAAAAD
[...]
+ },
+ {
+ "class": "LDA",
+ "values": {
+ "featuresCol": "input",
+ "maxIter": 10,
+ "seed": -9223372036854775808,
+ "checkpointInterval": -1,
+ "k": 2,
+ "optimizer": "online",
+ "learningOffset": 16.0,
+ "learningDecay": 0.7,
+ "subsamplingRate": 1.0,
+ "optimizeDocConcentration": false,
+ "docConcentration": [
+ 0.5,
+ 0.5
+ ],
+ "topicConcentration": 0.5,
+ "topicDistributionCol": "topics",
+ "keepLastCheckpoint": false
+ },
+ "params_b64":
"CiEKEmNoZWNrcG9pbnRJbnRlcnZhbBILMP///////////wEKMQoQZG9jQ29uY2VudHJhdGlvbhIdsgEaCgJKABIJWQAAAAAAAOA/EglZAAAAAAAA4D8KFgoLZmVhdHVyZXNDb2wSB2oFaW5wdXQKGAoSa2VlcExhc3RDaGVja3BvaW50EgIYAAoHCgFrEgIwAgoaCg1sZWFybmluZ0RlY2F5EglZZmZmZmZm5j8KGwoObGVhcm5pbmdPZmZzZXQSCVkAAAAAAAAwQAoNCgdtYXhJdGVyEgIwCgoeChhvcHRpbWl6ZURvY0NvbmNlbnRyYXRpb24SAhgAChUKCW9wdGltaXplchIIagZvbmxpbmUKEwoEc2VlZBILOICAgICAgICAgAEKHAoPc3Vic2FtcGxpbmdSYXRlEglZAAAAAAAA8D8KHwoSdG9waWNDb25jZW50cmF0aW9uEglZAAAAAAA
[...]
+ },
+ {
+ "class": "PowerIterationClustering",
+ "values": {},
+ "params_b64": ""
+ },
+ {
+ "class": "PowerIterationClustering",
+ "values": {
+ "k": 3,
+ "maxIter": 40,
+ "initMode": "degree",
+ "srcCol": "source",
+ "dstCol": "target",
+ "weightCol": "affinity"
+ },
+ "params_b64":
"ChIKBmRzdENvbBIIagZ0YXJnZXQKFAoIaW5pdE1vZGUSCGoGZGVncmVlCgcKAWsSAjADCg0KB21heEl0ZXISAjAoChIKBnNyY0NvbBIIagZzb3VyY2UKFwoJd2VpZ2h0Q29sEgpqCGFmZmluaXR5"
+ },
+ {
+ "class": "PowerIterationClustering",
+ "values": {
+ "weightCol": null
+ },
+ "params_b64": "ChEKCXdlaWdodENvbBIECgIKAA=="
+ },
+ {
+ "class": "PowerIterationClustering",
+ "values": {
+ "k": 2147483648
+ },
+ "params_b64": "CgsKAWsSBjiAgICACA=="
+ },
+ {
+ "class": "PowerIterationClustering",
+ "values": {
+ "k": null
+ },
+ "params_b64": "CgkKAWsSBAoCCgA="
+ }
+ ],
+ "pic_fetch": [
+ {
+ "values": {},
+ "fetch_b64":
"Ch8KHV9fX19fX01MX0NPTk5FQ1RfSEVMUEVSX19fX19fElwKJnBvd2VySXRlcmF0aW9uQ2x1c3RlcmluZ0Fzc2lnbkNsdXN0ZXJzEgISABIECgIwAhIECgIwFBIKCghqBnJhbmRvbRIHCgVqA3NyYxIHCgVqA2RzdBIECgJqAA=="
+ },
+ {
+ "values": {
+ "k": 3,
+ "maxIter": 40,
+ "initMode": "degree",
+ "srcCol": "source",
+ "dstCol": "target",
+ "weightCol": "affinity"
+ },
+ "fetch_b64":
"Ch8KHV9fX19fX01MX0NPTk5FQ1RfSEVMUEVSX19fX19fEmoKJnBvd2VySXRlcmF0aW9uQ2x1c3RlcmluZ0Fzc2lnbkNsdXN0ZXJzEgISABIECgIwAxIECgIwKBIKCghqBmRlZ3JlZRIKCghqBnNvdXJjZRIKCghqBnRhcmdldBIMCgpqCGFmZmluaXR5"
+ },
+ {
+ "values": {
+ "weightCol": null
+ },
+ "fetch_b64":
"Ch8KHV9fX19fX01MX0NPTk5FQ1RfSEVMUEVSX19fX19fEl4KJnBvd2VySXRlcmF0aW9uQ2x1c3RlcmluZ0Fzc2lnbkNsdXN0ZXJzEgISABIECgIwAhIECgIwFBIKCghqBnJhbmRvbRIHCgVqA3NyYxIHCgVqA2RzdBIGCgQKAgoA"
+ },
+ {
+ "values": {
+ "k": 2147483648
+ },
+ "fetch_b64":
"Ch8KHV9fX19fX01MX0NPTk5FQ1RfSEVMUEVSX19fX19fEmAKJnBvd2VySXRlcmF0aW9uQ2x1c3RlcmluZ0Fzc2lnbkNsdXN0ZXJzEgISABIICgY4gICAgAgSBAoCMBQSCgoIagZyYW5kb20SBwoFagNzcmMSBwoFagNkc3QSBAoCagA="
+ },
+ {
+ "values": {
+ "k": null
+ },
+ "fetch_b64":
"Ch8KHV9fX19fX01MX0NPTk5FQ1RfSEVMUEVSX19fX19fEl4KJnBvd2VySXRlcmF0aW9uQ2x1c3RlcmluZ0Fzc2lnbkNsdXN0ZXJzEgISABIGCgQKAgoAEgQKAjAUEgoKCGoGcmFuZG9tEgcKBWoDc3JjEgcKBWoDZHN0EgQKAmoA"
+ }
+ ],
+ "documents": [
+ [
+ 10.0,
+ 8.0,
+ 2.0,
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ [
+ 8.0,
+ 10.0,
+ 1.0,
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ [
+ 9.0,
+ 7.0,
+ 3.0,
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ [
+ 12.0,
+ 6.0,
+ 2.0,
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ [
+ 7.0,
+ 9.0,
+ 3.0,
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ [
+ 11.0,
+ 8.0,
+ 1.0,
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ [
+ 0.0,
+ 0.0,
+ 0.0,
+ 10.0,
+ 8.0,
+ 2.0
+ ],
+ [
+ 0.0,
+ 0.0,
+ 0.0,
+ 8.0,
+ 10.0,
+ 1.0
+ ],
+ [
+ 0.0,
+ 0.0,
+ 0.0,
+ 9.0,
+ 7.0,
+ 3.0
+ ],
+ [
+ 0.0,
+ 0.0,
+ 0.0,
+ 12.0,
+ 6.0,
+ 2.0
+ ],
+ [
+ 0.0,
+ 0.0,
+ 0.0,
+ 7.0,
+ 9.0,
+ 3.0
+ ],
+ [
+ 0.0,
+ 0.0,
+ 0.0,
+ 11.0,
+ 8.0,
+ 1.0
+ ]
+ ],
+ "held_out": [
+ [
+ 8.0,
+ 6.0,
+ 1.0,
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ [
+ 10.0,
+ 9.0,
+ 2.0,
+ 0.0,
+ 0.0,
+ 0.0
+ ],
+ [
+ 0.0,
+ 0.0,
+ 0.0,
+ 8.0,
+ 6.0,
+ 1.0
+ ],
+ [
+ 0.0,
+ 0.0,
+ 0.0,
+ 10.0,
+ 9.0,
+ 2.0
+ ],
+ [
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0,
+ 0.0
+ ]
+ ],
+ "edges": [
+ [
+ 1,
+ 0,
+ 0.5
+ ],
+ [
+ 2,
+ 0,
+ 0.5
+ ],
+ [
+ 2,
+ 1,
+ 0.7
+ ],
+ [
+ 3,
+ 0,
+ 0.5
+ ],
+ [
+ 3,
+ 1,
+ 0.7
+ ],
+ [
+ 3,
+ 2,
+ 0.9
+ ],
+ [
+ 4,
+ 0,
+ 0.5
+ ],
+ [
+ 4,
+ 1,
+ 0.7
+ ],
+ [
+ 4,
+ 2,
+ 0.9
+ ],
+ [
+ 4,
+ 3,
+ 1.1
+ ],
+ [
+ 5,
+ 0,
+ 0.5
+ ],
+ [
+ 5,
+ 1,
+ 0.7
+ ],
+ [
+ 5,
+ 2,
+ 0.9
+ ],
+ [
+ 5,
+ 3,
+ 1.1
+ ],
+ [
+ 5,
+ 4,
+ 1.3
+ ]
+ ],
+ "lda": [
+ {
+ "values": {
+ "featuresCol": "input",
+ "maxIter": 10,
+ "seed": 42,
+ "checkpointInterval": -1,
+ "k": 2,
+ "optimizer": "online",
+ "learningOffset": 16.0,
+ "learningDecay": 0.7,
+ "subsamplingRate": 1.0,
+ "optimizeDocConcentration": false,
+ "docConcentration": [
+ 0.5,
+ 0.5
+ ],
+ "topicConcentration": 0.5,
+ "topicDistributionCol": "topics",
+ "keepLastCheckpoint": false
+ },
+ "topics": [
+ [
+ 0.9686723238078985,
+ 0.03132767619210143
+ ],
+ [
+ 0.9772109110415493,
+ 0.02278908895845055
+ ],
+ [
+ 0.031342638228196364,
+ 0.9686573617718036
+ ],
+ [
+ 0.022799305031864447,
+ 0.9772006949681356
+ ],
+ [
+ 0.0,
+ 0.0
+ ]
+ ]
+ },
+ {
+ "values": {
+ "featuresCol": "input",
+ "maxIter": 10,
+ "seed": 42,
+ "checkpointInterval": -1,
+ "k": 2,
+ "optimizer": "em",
+ "learningOffset": 16.0,
+ "learningDecay": 0.7,
+ "subsamplingRate": 1.0,
+ "optimizeDocConcentration": false,
+ "docConcentration": [
+ 2.0,
+ 2.0
+ ],
+ "topicConcentration": 2.0,
+ "topicDistributionCol": "topics",
+ "keepLastCheckpoint": false
+ },
+ "topics": [
+ [
+ 0.10526315789918282,
+ 0.8947368421008172
+ ],
+ [
+ 0.08000000000353698,
+ 0.9199999999964631
+ ],
+ [
+ 0.8947368421005992,
+ 0.10526315789940072
+ ],
+ [
+ 0.9199999999962896,
+ 0.08000000000371045
+ ],
+ [
+ 0.0,
+ 0.0
+ ]
+ ]
+ }
+ ],
+ "pic": [
+ {
+ "values": {
+ "k": 2,
+ "maxIter": 40,
+ "initMode": "random",
+ "srcCol": "source",
+ "dstCol": "target"
+ },
+ "assignments": [
+ [
+ 0,
+ 1
+ ],
+ [
+ 1,
+ 0
+ ],
+ [
+ 2,
+ 0
+ ],
+ [
+ 3,
+ 0
+ ],
+ [
+ 4,
+ 1
+ ],
+ [
+ 5,
+ 1
+ ]
+ ]
+ },
+ {
+ "values": {
+ "k": 2,
+ "maxIter": 40,
+ "initMode": "random",
+ "srcCol": "source",
+ "dstCol": "target",
+ "weightCol": "affinity"
+ },
+ "assignments": [
+ [
+ 0,
+ 0
+ ],
+ [
+ 1,
+ 0
+ ],
+ [
+ 2,
+ 0
+ ],
+ [
+ 3,
+ 0
+ ],
+ [
+ 4,
+ 0
+ ],
+ [
+ 5,
+ 1
+ ]
+ ]
+ },
+ {
+ "values": {
+ "k": 2,
+ "maxIter": 40,
+ "initMode": "degree",
+ "srcCol": "source",
+ "dstCol": "target"
+ },
+ "assignments": [
+ [
+ 0,
+ 0
+ ],
+ [
+ 1,
+ 0
+ ],
+ [
+ 2,
+ 0
+ ],
+ [
+ 3,
+ 0
+ ],
+ [
+ 4,
+ 0
+ ],
+ [
+ 5,
+ 0
+ ]
+ ]
+ },
+ {
+ "values": {
+ "k": 2,
+ "maxIter": 40,
+ "initMode": "degree",
+ "srcCol": "source",
+ "dstCol": "target",
+ "weightCol": "affinity"
+ },
+ "assignments": [
+ [
+ 0,
+ 0
+ ],
+ [
+ 1,
+ 1
+ ],
+ [
+ 2,
+ 0
+ ],
+ [
+ 3,
+ 0
+ ],
+ [
+ 4,
+ 1
+ ],
+ [
+ 5,
+ 1
+ ]
+ ]
+ }
+ ]
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]