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 c9afb48f [SPARK-61636][CONNECT][RUST] Add native FPGrowth and
PrefixSpan
c9afb48f is described below
commit c9afb48f9e19a7ce5b721dda39692235686bdfac
Author: Ruifeng Zheng <[email protected]>
AuthorDate: Fri Nov 13 20:09:43 2026 +0800
[SPARK-61636][CONNECT][RUST] Add native FPGrowth and PrefixSpan
### What changes were proposed in this pull request?
Add native Rust FPGrowth/FPGrowthModel and PrefixSpan APIs, with PyO3
bindings and exports from `pyspark.ml.connect.fpm` and `pyspark.ml.connect`.
FPGrowth exposes fit/transform, frequent itemsets and association rules;
PrefixSpan exposes frequent sequential patterns. All official parameters have
typed Rust accessors and Python setters. Lazy result tables retain their fitted
model and upstream input plans.
### Why are the changes needed?
The native client lacks frequent-pattern mining APIs. These implementations
run the standard Spark ML algorithms through Connect and match official PySpark
4.3.0 results and parameter encoding.
### Does this PR introduce _any_ user-facing change?
Yes. Native Rust and Rust-backed Python callers can train FPGrowth, inspect
itemsets/rules, predict missing items, and mine sequential patterns with
PrefixSpan. ML dataset arguments accept Spark DataFrames and reject pandas
DataFrames before RPC. Vendored `pyspark.ml.fpm` remains unchanged; persistence
is outside this patch.
Spark 4.3.0's PrefixSpan helper rejects Long literals, including
`maxLocalProjDBSize >= 2**31`, in both the official and native clients.
Normal/default sizes work; a reference-backed regression test and the
compatibility docs record this server limitation.
### How was this patch tested?
- Captured official PySpark 4.3.0 parameter protobufs and numeric outputs
for string/integer transactions, itemsets, association rules, predictions,
sequential patterns, and model parameter changes.
- 4,201 offline Python tests passed (8 skipped); 158 live native ML/feature
tests passed. Official-reference mining tests: 18 passed, 1 native-only test
skipped.
- Rust: 2 golden and 2 live mining tests, 682 library tests, compilation of
all integration tests with and without `wasm-udf`, workspace formatting, Clippy
with warnings denied, and release extension build passed.
- Official Connect regression gate: all 87 selected files passed, 2,638
tests passed and 589 skipped. The three existing artifact/local-cluster
exclusions were retained.
- Public SQL API comparison found zero gaps after the two documented
transport exclusions. Ruff lint and format checks passed.
### 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 #642 from zhengruifeng/add-native-frequent-patterns.
Authored-by: Ruifeng Zheng <[email protected]>
Signed-off-by: Ruifeng Zheng <[email protected]>
---
.github/workflows/build_python_connect.yml | 2 +-
.github/workflows/coverage.yml | 2 +-
crates/pyspark-rs/src/lib.rs | 1 +
crates/pyspark-rs/src/ml.rs | 1 +
crates/pyspark-rs/src/ml/fpm.rs | 261 +++++
crates/spark-connect/src/ml.rs | 2 +
crates/spark-connect/src/ml/fpm.rs | 321 ++++++
.../spark-connect/tests/e2e_frequent_patterns.rs | 122 ++
.../tests/frequent_patterns_golden.rs | 107 ++
docs/compatibility.md | 31 +
python/pyspark/ml/connect/__init__.py | 4 +
python/pyspark/ml/connect/fpm.py | 5 +
python/tests/_frequent_patterns.py | 45 +
python/tests/test_frequent_patterns_e2e.py | 133 +++
python/tests/test_frequent_patterns_offline.py | 149 +++
scripts/capture_frequent_patterns_golden.py | 141 +++
tests/golden/frequent_patterns.json | 1178 ++++++++++++++++++++
17 files changed, 2503 insertions(+), 2 deletions(-)
diff --git a/.github/workflows/build_python_connect.yml
b/.github/workflows/build_python_connect.yml
index 1cfd0b67..321f742e 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
tests/test_remaining_clustering_e2e.py tests/test_ml_features_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 tests/test_ml_features_e2e.py
tests/test_frequent_patterns_e2e.py -q
- name: Restart Connect server in local-cluster mode
# Resource profiles and artifact distribution across executors can
only be
diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml
index 7a030274..b505bc97 100644
--- a/.github/workflows/coverage.yml
+++ b/.github/workflows/coverage.yml
@@ -248,7 +248,7 @@ jobs:
run: |
cd python
PYTHONPATH=$(pwd) python -m coverage run --rcfile=.coveragerc -m
pytest -rs \
- tests/test_dropin_offline.py tests/test_arrow_handoff.py
tests/test_ml_offline.py tests/test_ml_features_offline.py
+ tests/test_dropin_offline.py tests/test_arrow_handoff.py
tests/test_ml_offline.py tests/test_ml_features_offline.py
tests/test_frequent_patterns_offline.py
PYTHONPATH=$(pwd) python -m coverage json --rcfile=.coveragerc -o
coverage-python.json
- name: Parse Python coverage and create badge JSON
diff --git a/crates/pyspark-rs/src/lib.rs b/crates/pyspark-rs/src/lib.rs
index 46f40b39..1d092722 100644
--- a/crates/pyspark-rs/src/lib.rs
+++ b/crates/pyspark-rs/src/lib.rs
@@ -245,6 +245,7 @@ fn _pyspark(_py: Python<'_>, m: &Bound<'_, PyModule>) ->
PyResult<()> {
// Register ML classes (pyspark.ml.connect)
m.add_class::<ml::PyMLModel>()?;
ml::feature::register(m)?;
+ ml::fpm::register(m)?;
m.add_class::<ml::PyLogisticRegression>()?;
m.add_class::<ml::PyLinearSVC>()?;
m.add_class::<ml::PyFMClassifier>()?;
diff --git a/crates/pyspark-rs/src/ml.rs b/crates/pyspark-rs/src/ml.rs
index 94823988..5b3de76f 100644
--- a/crates/pyspark-rs/src/ml.rs
+++ b/crates/pyspark-rs/src/ml.rs
@@ -29,6 +29,7 @@ use spark_connect::types::StructField;
use spark_connect::DataFrame;
pub(crate) mod feature;
+pub(crate) mod fpm;
use crate::dataframe::PyDataFrame;
use crate::errors::ResultExt;
diff --git a/crates/pyspark-rs/src/ml/fpm.rs b/crates/pyspark-rs/src/ml/fpm.rs
new file mode 100644
index 00000000..96878622
--- /dev/null
+++ b/crates/pyspark-rs/src/ml/fpm.rs
@@ -0,0 +1,261 @@
+// SPDX-License-Identifier: Apache-2.0
+//! Native Python frequent-pattern mining APIs.
+use super::*;
+use spark_connect::ml::{FPGrowth, FPGrowthModel, PrefixSpan};
+
+#[pyclass(name = "FPGrowth", module = "pyspark.ml.connect.fpm")]
+pub struct PyFPGrowth {
+ inner: FPGrowth,
+ unsendable: Vec<&'static str>,
+}
+impl Native for PyFPGrowth {
+ type Core = FPGrowth;
+ fn inner(&self) -> &Self::Core {
+ &self.inner
+ }
+ fn params(&self) -> &Params {
+ self.inner.params()
+ }
+ fn params_mut(&mut self) -> &mut Params {
+ self.inner.params_mut()
+ }
+ fn unsendable(&self) -> &[&'static str] {
+ &self.unsendable
+ }
+ fn unsendable_mut(&mut self) -> &mut Vec<&'static str> {
+ &mut self.unsendable
+ }
+}
+#[pymethods]
+impl PyFPGrowth {
+ #[new]
+ #[pyo3(signature = (*args, **kwargs), text_signature = "(*,
minSupport=0.3, minConfidence=0.8, itemsCol='items',
predictionCol='prediction', numPartitions=None)")]
+ fn new(args: &Bound<'_, PyTuple>, kwargs: Option<&Bound<'_, PyDict>>) ->
PyResult<Self> {
+ let mut this = Self {
+ inner: FPGrowth::new(),
+ unsendable: Vec::new(),
+ };
+ init_params(
+ &mut this,
+ "FPGrowth",
+ &[],
+ &[
+ ("itemsCol", Kind::Str),
+ ("minConfidence", Kind::Float),
+ ("minSupport", Kind::Float),
+ ("numPartitions", Kind::Int),
+ ("predictionCol", Kind::Str),
+ ],
+ args,
+ kwargs,
+ )?;
+ Ok(this)
+ }
+ #[pyo3(name = "setItemsCol")]
+ fn set_items_col<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "itemsCol", Kind::Str, value)
+ }
+ #[pyo3(name = "setMinConfidence")]
+ fn set_min_confidence<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "minConfidence", Kind::Float, value)
+ }
+ #[pyo3(name = "setMinSupport")]
+ fn set_min_support<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "minSupport", Kind::Float, value)
+ }
+ #[pyo3(name = "setNumPartitions")]
+ fn set_num_partitions<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "numPartitions", Kind::Int, 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)
+ }
+ fn fit(slf: &Bound<'_, Self>, dataset: &Bound<'_, PyAny>) ->
PyResult<PyFPGrowthModel> {
+ let input = dataset_of(dataset, "fit", "select")?;
+ let mut estimator = snapshot(slf)?;
+ let session = input.spark_session();
+ let model = interruptible(slf.py(), &session, || {
+ estimator.fit(&input).map_err(Box::new)
+ })?;
+ Ok(PyFPGrowthModel {
+ inner: model,
+ unsendable: Vec::new(),
+ })
+ }
+}
+
+#[pyclass(name = "FPGrowthModel", module = "pyspark.ml.connect.fpm")]
+pub struct PyFPGrowthModel {
+ inner: FPGrowthModel,
+ unsendable: Vec<&'static str>,
+}
+impl Native for PyFPGrowthModel {
+ type Core = FPGrowthModel;
+ fn inner(&self) -> &Self::Core {
+ &self.inner
+ }
+ fn params(&self) -> &Params {
+ self.inner.params()
+ }
+ fn params_mut(&mut self) -> &mut Params {
+ self.inner.params_mut()
+ }
+ fn unsendable(&self) -> &[&'static str] {
+ &self.unsendable
+ }
+ fn unsendable_mut(&mut self) -> &mut Vec<&'static str> {
+ &mut self.unsendable
+ }
+}
+#[pymethods]
+impl PyFPGrowthModel {
+ #[pyo3(name = "setItemsCol")]
+ fn set_items_col<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "itemsCol", Kind::Str, value)
+ }
+ #[pyo3(name = "setMinConfidence")]
+ fn set_min_confidence<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "minConfidence", Kind::Float, 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)
+ }
+ fn transform(slf: &Bound<'_, Self>, dataset: &Bound<'_, PyAny>) ->
PyResult<PyDataFrame> {
+ let input = dataset_of(dataset, "transform", "columns")?;
+ let mut model = snapshot(slf)?;
+ Ok(PyDataFrame::new(model.transform(&input).to_pyerr()?))
+ }
+ #[getter]
+ #[pyo3(name = "freqItemsets")]
+ fn freq_itemsets(&self) -> PyResult<PyDataFrame> {
+ Ok(PyDataFrame::new(self.inner.freq_itemsets().to_pyerr()?))
+ }
+ #[getter]
+ #[pyo3(name = "associationRules")]
+ fn association_rules(&self) -> PyResult<PyDataFrame> {
+ Ok(PyDataFrame::new(self.inner.association_rules().to_pyerr()?))
+ }
+}
+
+#[pyclass(name = "PrefixSpan", module = "pyspark.ml.connect.fpm")]
+pub struct PyPrefixSpan {
+ inner: PrefixSpan,
+ unsendable: Vec<&'static str>,
+}
+impl Native for PyPrefixSpan {
+ type Core = PrefixSpan;
+ fn inner(&self) -> &Self::Core {
+ &self.inner
+ }
+ fn params(&self) -> &Params {
+ self.inner.params()
+ }
+ fn params_mut(&mut self) -> &mut Params {
+ self.inner.params_mut()
+ }
+ fn unsendable(&self) -> &[&'static str] {
+ &self.unsendable
+ }
+ fn unsendable_mut(&mut self) -> &mut Vec<&'static str> {
+ &mut self.unsendable
+ }
+}
+#[pymethods]
+impl PyPrefixSpan {
+ #[new]
+ #[pyo3(signature = (*args, **kwargs), text_signature = "(*,
minSupport=0.1, maxPatternLength=10, maxLocalProjDBSize=32000000,
sequenceCol='sequence')")]
+ fn new(args: &Bound<'_, PyTuple>, kwargs: Option<&Bound<'_, PyDict>>) ->
PyResult<Self> {
+ let mut this = Self {
+ inner: PrefixSpan::new(),
+ unsendable: Vec::new(),
+ };
+ init_params(
+ &mut this,
+ "PrefixSpan",
+ &[],
+ &[
+ ("maxLocalProjDBSize", Kind::Int),
+ ("maxPatternLength", Kind::Int),
+ ("minSupport", Kind::Float),
+ ("sequenceCol", Kind::Str),
+ ],
+ args,
+ kwargs,
+ )?;
+ Ok(this)
+ }
+ #[pyo3(name = "setMaxLocalProjDBSize")]
+ fn set_max_local_proj_db_size<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "maxLocalProjDBSize", Kind::Int, value)
+ }
+ #[pyo3(name = "setMaxPatternLength")]
+ fn set_max_pattern_length<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "maxPatternLength", Kind::Int, value)
+ }
+ #[pyo3(name = "setMinSupport")]
+ fn set_min_support<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "minSupport", Kind::Float, value)
+ }
+ #[pyo3(name = "setSequenceCol")]
+ fn set_sequence_col<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "sequenceCol", Kind::Str, value)
+ }
+ #[pyo3(name = "findFrequentSequentialPatterns")]
+ fn find_frequent_sequential_patterns(
+ slf: &Bound<'_, Self>,
+ dataset: &Bound<'_, PyAny>,
+ ) -> PyResult<PyDataFrame> {
+ let input = dataset_of(dataset, "findFrequentSequentialPatterns",
"select")?;
+ let algorithm = snapshot(slf)?;
+ Ok(PyDataFrame::new(
+ algorithm
+ .find_frequent_sequential_patterns(&input)
+ .to_pyerr()?,
+ ))
+ }
+}
+
+pub(crate) fn register(m: &Bound<'_, PyModule>) -> PyResult<()> {
+ m.add_class::<PyFPGrowth>()?;
+ m.add_class::<PyFPGrowthModel>()?;
+ m.add_class::<PyPrefixSpan>()?;
+ Ok(())
+}
diff --git a/crates/spark-connect/src/ml.rs b/crates/spark-connect/src/ml.rs
index 3a863b79..4ad781a2 100644
--- a/crates/spark-connect/src/ml.rs
+++ b/crates/spark-connect/src/ml.rs
@@ -14,6 +14,8 @@ use uuid::Uuid;
mod feature;
pub use feature::*;
+mod fpm;
+pub use fpm::*;
use crate::dataframe::DataFrame;
use crate::expression::LiteralExpression;
diff --git a/crates/spark-connect/src/ml/fpm.rs
b/crates/spark-connect/src/ml/fpm.rs
new file mode 100644
index 00000000..81865749
--- /dev/null
+++ b/crates/spark-connect/src/ml/fpm.rs
@@ -0,0 +1,321 @@
+// SPDX-License-Identifier: Apache-2.0
+//! Frequent itemsets, association rules and sequential patterns, executed by
Spark Connect.
+use super::*;
+
+#[derive(Debug, Clone)]
+pub struct FPGrowth {
+ operator: MlOperator,
+ params: Params,
+}
+impl FPGrowth {
+ pub fn new() -> Self {
+ Self {
+ operator: MlOperator::new("org.apache.spark.ml.fpm.FPGrowth",
OperatorType::Estimator),
+ params: Params::new(),
+ }
+ }
+ /// Fit and retain the typed model, including its mined itemsets and
association rules.
+ pub fn fit(&mut self, df: &DataFrame) ->
spark_connect_core::error::Result<FPGrowthModel> {
+ self.ensure_operator();
+ let info = fit_via_command(&self.operator, &self.params, df)?;
+ Ok(FPGrowthModel {
+ operator: MlOperator::with_uid(
+ "org.apache.spark.ml.fpm.FPGrowthModel",
+ info.uid.as_deref().unwrap_or(&self.operator.uid),
+ OperatorType::Model,
+ ),
+ params: self.params.clone(),
+ cached: CachedModel::from_info(&info, &df.session, "FPGrowth")?,
+ })
+ }
+}
+impl Default for FPGrowth {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+impl Estimator for FPGrowth {
+ 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>> {
+ Ok(Box::new(self.fit(df)?))
+ }
+}
+
+/// A session-owned FPGrowth model. Lazy result tables retain its server cache
entry.
+#[derive(Debug, Clone)]
+pub struct FPGrowthModel {
+ operator: MlOperator,
+ params: Params,
+ cached: CachedModel,
+}
+impl FPGrowthModel {
+ fn attribute(&self, method: &str) ->
spark_connect_core::error::Result<DataFrame> {
+ 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(self.cached.0.model_ref.clone()),
+ methods: vec![proto::fetch::Method {
+ method: method.into(),
+ args: Vec::new(),
+ }],
+ })),
+ ..Default::default()
+ },
+ ))),
+ ..Default::default()
+ };
+ DataFrame::from_relation(
+ self.cached.0.session.clone(),
+ relation,
+ Some(self.cached.0.clone()),
+ )
+ }
+ /// Frequent itemsets and their counts, as a lazy Spark DataFrame.
+ pub fn freq_itemsets(&self) ->
spark_connect_core::error::Result<DataFrame> {
+ self.attribute("freqItemsets")
+ }
+ /// Association rules computed by the fitted server model.
+ pub fn association_rules(&self) ->
spark_connect_core::error::Result<DataFrame> {
+ self.attribute("associationRules")
+ }
+}
+impl Transformer for FPGrowthModel {
+ 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,
+ df: &DataFrame,
+ ) -> spark_connect_core::error::Result<proto::MlRelation> {
+ self.cached.build_ml_relation(df, &self.params)
+ }
+ fn transform_impl(&mut self, df: &DataFrame) ->
spark_connect_core::error::Result<DataFrame> {
+ self.cached.transform(df, &self.params)
+ }
+}
+impl Model for FPGrowthModel {
+ fn clone_box(&self) -> Box<dyn Model> {
+ Box::new(self.clone())
+ }
+}
+
+/// PrefixSpan mines sequential patterns directly; it has no fit/transform
model.
+#[derive(Debug, Clone, Default)]
+pub struct PrefixSpan {
+ params: Params,
+}
+impl PrefixSpan {
+ pub fn new() -> Self {
+ Self::default()
+ }
+ pub fn params(&self) -> &Params {
+ &self.params
+ }
+ pub fn params_mut(&mut self) -> &mut Params {
+ &mut self.params
+ }
+ /// Build Spark's lazy PrefixSpan helper relation and retain the input's
resources.
+ pub fn find_frequent_sequential_patterns(
+ &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 = [
+ ("minSupport", L::Double(0.1)),
+ ("maxPatternLength", L::Integer(10)),
+ ("maxLocalProjDBSize", L::Integer(32000000)),
+ ("sequenceCol", L::String("sequence".into())),
+ ];
+ let mut args = vec![proto::fetch::method::Args {
+ args_type: Some(ArgsType::Input(dataset.relation()?)),
+ }];
+ for (name, default) in defaults {
+ let value = 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(value)),
+ });
+ }
+ 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:
"prefixSpanFindFrequentSequentialPatterns".into(),
+ args,
+ }],
+ })),
+ ..Default::default()
+ },
+ ))),
+ ..Default::default()
+ };
+ Ok(DataFrame::new(
+ dataset.session.clone(),
+ LogicalPlan::MlTransform {
+ ml_relation: relation,
+ input: dataset.plan.clone(),
+ owner: None,
+ },
+ ))
+ }
+}
+
+impl FPGrowth {
+ /// Set `itemsCol`. Spark validates the value when the operation runs.
+ pub fn set_items_col(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("itemsCol", value);
+ self
+ }
+ /// Get `itemsCol`, using Spark's default when defined.
+ pub fn items_col(&self) -> &str {
+ self.params.string_or("itemsCol", "items")
+ }
+ /// Set `minConfidence`. Spark validates the value when the operation runs.
+ pub fn set_min_confidence(mut self, value: f64) -> Self {
+ self.params = self.params.set_param_double("minConfidence", value);
+ self
+ }
+ /// Get `minConfidence`, using Spark's default when defined.
+ pub fn min_confidence(&self) -> f64 {
+ self.params.double_or("minConfidence", 0.8)
+ }
+ /// Set `minSupport`. Spark validates the value when the operation runs.
+ pub fn set_min_support(mut self, value: f64) -> Self {
+ self.params = self.params.set_param_double("minSupport", value);
+ self
+ }
+ /// Get `minSupport`, using Spark's default when defined.
+ pub fn min_support(&self) -> f64 {
+ self.params.double_or("minSupport", 0.3)
+ }
+ /// Set `numPartitions`. Spark validates the value when the operation runs.
+ pub fn set_num_partitions(mut self, value: i32) -> Self {
+ self.params = self.params.set_param_int32("numPartitions", value);
+ self
+ }
+ /// Get `numPartitions`, using Spark's default when defined.
+ pub fn num_partitions(&self) -> Option<i32> {
+ self.params.long_opt("numPartitions").map(|v| v as i32)
+ }
+ /// Set `predictionCol`. Spark validates the value when the operation runs.
+ pub fn set_prediction_col(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("predictionCol", value);
+ self
+ }
+ /// Get `predictionCol`, using Spark's default when defined.
+ pub fn prediction_col(&self) -> &str {
+ self.params.string_or("predictionCol", "prediction")
+ }
+}
+
+impl FPGrowthModel {
+ /// Set `itemsCol`. Spark validates the value when the operation runs.
+ pub fn set_items_col(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("itemsCol", value);
+ self
+ }
+ /// Get `itemsCol`, using Spark's default when defined.
+ pub fn items_col(&self) -> &str {
+ self.params.string_or("itemsCol", "items")
+ }
+ /// Set `minConfidence`. Spark validates the value when the operation runs.
+ pub fn set_min_confidence(mut self, value: f64) -> Self {
+ self.params = self.params.set_param_double("minConfidence", value);
+ self
+ }
+ /// Get `minConfidence`, using Spark's default when defined.
+ pub fn min_confidence(&self) -> f64 {
+ self.params.double_or("minConfidence", 0.8)
+ }
+ /// Get `minSupport`, using Spark's default when defined.
+ pub fn min_support(&self) -> f64 {
+ self.params.double_or("minSupport", 0.3)
+ }
+ /// Get `numPartitions`, using Spark's default when defined.
+ pub fn num_partitions(&self) -> Option<i32> {
+ self.params.long_opt("numPartitions").map(|v| v as i32)
+ }
+ /// Set `predictionCol`. Spark validates the value when the operation runs.
+ pub fn set_prediction_col(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("predictionCol", value);
+ self
+ }
+ /// Get `predictionCol`, using Spark's default when defined.
+ pub fn prediction_col(&self) -> &str {
+ self.params.string_or("predictionCol", "prediction")
+ }
+}
+
+impl PrefixSpan {
+ /// Set `maxLocalProjDBSize`. Spark validates the value when the operation
runs.
+ pub fn set_max_local_proj_db_size(mut self, value: i64) -> Self {
+ self.params = self
+ .params
+ .set_param_int_narrow("maxLocalProjDBSize", value);
+ self
+ }
+ /// Get `maxLocalProjDBSize`, using Spark's default when defined.
+ pub fn max_local_proj_db_size(&self) -> i64 {
+ self.params
+ .long_opt("maxLocalProjDBSize")
+ .unwrap_or(32000000)
+ }
+ /// Set `maxPatternLength`. Spark validates the value when the operation
runs.
+ pub fn set_max_pattern_length(mut self, value: i32) -> Self {
+ self.params = self.params.set_param_int32("maxPatternLength", value);
+ self
+ }
+ /// Get `maxPatternLength`, using Spark's default when defined.
+ pub fn max_pattern_length(&self) -> i32 {
+ self.params.int_or("maxPatternLength", 10)
+ }
+ /// Set `minSupport`. Spark validates the value when the operation runs.
+ pub fn set_min_support(mut self, value: f64) -> Self {
+ self.params = self.params.set_param_double("minSupport", value);
+ self
+ }
+ /// Get `minSupport`, using Spark's default when defined.
+ pub fn min_support(&self) -> f64 {
+ self.params.double_or("minSupport", 0.1)
+ }
+ /// Set `sequenceCol`. Spark validates the value when the operation runs.
+ pub fn set_sequence_col(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("sequenceCol", value);
+ self
+ }
+ /// Get `sequenceCol`, using Spark's default when defined.
+ pub fn sequence_col(&self) -> &str {
+ self.params.string_or("sequenceCol", "sequence")
+ }
+}
diff --git a/crates/spark-connect/tests/e2e_frequent_patterns.rs
b/crates/spark-connect/tests/e2e_frequent_patterns.rs
new file mode 100644
index 00000000..2dad2c1f
--- /dev/null
+++ b/crates/spark-connect/tests/e2e_frequent_patterns.rs
@@ -0,0 +1,122 @@
+// SPDX-License-Identifier: Apache-2.0
+//! Frequent-pattern mining on a live server. Set SPARK_REMOTE to run.
+mod common;
+use common::live_session;
+use serde_json::{json, Value as Json};
+use spark_connect::ml::{FPGrowth, Model, PrefixSpan, Transformer};
+use spark_connect::row::Value;
+use spark_connect::DataFrame;
+
+fn value(v: &Value) -> Json {
+ match v {
+ Value::List(v) => v.iter().map(value).collect(),
+ Value::String(v) => json!(v),
+ Value::Long(v) => json!(v),
+ Value::Integer(v) => json!(v),
+ Value::Double(v) => json!(v),
+ Value::Null => Json::Null,
+ _ => panic!("unexpected mining value: {v:?}"),
+ }
+}
+fn sort(values: &mut Json) {
+ values.as_array_mut().unwrap().sort_by_key(Json::to_string);
+}
+fn normalized(frame: &DataFrame, kind: &str) -> Json {
+ let mut rows: Vec<Json> = frame
+ .collect()
+ .unwrap()
+ .iter()
+ .map(|r| r.values().iter().map(value).collect())
+ .collect();
+ for row in &mut rows {
+ let row = row.as_array_mut().unwrap();
+ match kind {
+ "predictions" => sort(row.last_mut().unwrap()),
+ "itemsets" => sort(&mut row[0]),
+ "rules" => {
+ sort(&mut row[0]);
+ sort(&mut row[1]);
+ }
+ _ => {
+ for set in row[0].as_array_mut().unwrap() {
+ sort(set);
+ }
+ }
+ }
+ }
+ rows.sort_by_key(Json::to_string);
+ json!(rows)
+}
+fn assert_values(a: &Json, e: &Json) {
+ match e {
+ Json::Array(e) => {
+ let a = a.as_array().unwrap();
+ assert_eq!(a.len(), e.len());
+ for (a, e) in a.iter().zip(e) {
+ assert_values(a, e);
+ }
+ }
+ Json::Number(e) => assert!(
+ (a.as_f64().unwrap() - e.as_f64().unwrap()).abs() < 1e-10,
+ "{a} != {e}"
+ ),
+ _ => assert_eq!(a, e),
+ }
+}
+#[test]
+fn fpgrowth_itemsets_rules_predictions_and_model_lifetime() {
+ let Some(s) = live_session() else { return };
+ let golden: Json =
+
serde_json::from_str(include_str!("../../../tests/golden/frequent_patterns.json")).unwrap();
+ for case in golden["fpgrowth"].as_array().unwrap() {
+ let v = &case["values"];
+ let mut model = FPGrowth::new()
+ .set_items_col("basket")
+ .set_prediction_col("suggested")
+ .set_min_support(v["minSupport"].as_f64().unwrap())
+ .set_min_confidence(v["minConfidence"].as_f64().unwrap())
+ .set_num_partitions(v["numPartitions"].as_i64().unwrap() as i32)
+ .fit(&s.sql(case["sql"].as_str().unwrap()).unwrap())
+ .unwrap();
+ let held = s.sql(case["held"].as_str().unwrap()).unwrap();
+ let tables = [
+ ("itemsets", model.freq_itemsets().unwrap()),
+ ("rules", model.association_rules().unwrap()),
+ ("predictions", model.clone_box().transform(&held).unwrap()),
+ ];
+ model = model.set_min_confidence(0.95).set_prediction_col("changed");
+ let changed = model.transform(&held).unwrap();
+ drop(model);
+ for (kind, table) in tables {
+ assert_values(&normalized(&table, kind), &case[kind]["rows"]);
+ assert_eq!(table.schema().unwrap().json_value(),
case[kind]["schema"]);
+ }
+ assert_values(
+ &normalized(&changed, "predictions"),
+ &case["changed_predictions"]["rows"],
+ );
+ assert_eq!(
+ changed.schema().unwrap().json_value(),
+ case["changed_predictions"]["schema"]
+ );
+ }
+}
+#[test]
+fn prefixspan_matches_reference_results() {
+ let Some(s) = live_session() else { return };
+ let golden: Json =
+
serde_json::from_str(include_str!("../../../tests/golden/frequent_patterns.json")).unwrap();
+ let input = s.sql(golden["sequences"].as_str().unwrap()).unwrap();
+ for case in golden["prefixspan"].as_array().unwrap() {
+ let v = &case["values"];
+ let stage = PrefixSpan::new()
+ .set_sequence_col("events")
+ .set_min_support(0.5)
+ .set_max_pattern_length(v["maxPatternLength"].as_i64().unwrap() as
i32)
+
.set_max_local_proj_db_size(v["maxLocalProjDBSize"].as_i64().unwrap());
+ let result = stage.find_frequent_sequential_patterns(&input).unwrap();
+ drop(stage);
+ assert_values(&normalized(&result, "sequences"), &case["rows"]);
+ assert_eq!(result.schema().unwrap().json_value(), case["schema"]);
+ }
+}
diff --git a/crates/spark-connect/tests/frequent_patterns_golden.rs
b/crates/spark-connect/tests/frequent_patterns_golden.rs
new file mode 100644
index 00000000..60ec205b
--- /dev/null
+++ b/crates/spark-connect/tests/frequent_patterns_golden.rs
@@ -0,0 +1,107 @@
+// SPDX-License-Identifier: Apache-2.0
+//! Frequent-pattern parameter and helper parity with official PySpark.
+use base64::{engine::general_purpose::STANDARD, Engine};
+use prost::Message;
+use serde_json::Value as Json;
+use spark_connect::ml::{Estimator, FPGrowth, PrefixSpan};
+use spark_connect::SparkSession;
+use spark_connect_proto as proto;
+
+fn fixture() -> Json {
+
serde_json::from_str(include_str!("../../../tests/golden/frequent_patterns.json")).unwrap()
+}
+
+#[test]
+fn typed_mining_parameters_and_prefixspan_helper_match_official() {
+ let session = SparkSession::builder()
+ .remote("sc://localhost:1")
+ .get_or_create()
+ .unwrap();
+ let input = session.range(1).unwrap();
+ for case in fixture()["params"].as_array().unwrap() {
+ let values = case["values"].as_object().unwrap();
+ if values.values().any(Json::is_null) {
+ continue;
+ } // Python tests cover explicit None.
+ let expected = proto::MlParams::decode(
+ STANDARD
+ .decode(case["params_b64"].as_str().unwrap())
+ .unwrap()
+ .as_slice(),
+ )
+ .unwrap();
+ if case["name"] == "FPGrowth" {
+ let stage = if values.is_empty() {
+ FPGrowth::new()
+ } else {
+ FPGrowth::new()
+ .set_items_col("basket")
+ .set_prediction_col("suggested")
+ .set_min_support(0.4)
+ .set_min_confidence(0.7)
+ .set_num_partitions(2)
+ };
+ assert_eq!(stage.params().to_proto(), expected);
+ } else {
+ let stage = if values.is_empty() {
+ PrefixSpan::new()
+ } else {
+ PrefixSpan::new()
+ .set_min_support(0.5)
+ .set_max_pattern_length(5)
+
.set_max_local_proj_db_size(values["maxLocalProjDBSize"].as_i64().unwrap())
+ .set_sequence_col("events")
+ };
+ assert_eq!(stage.params().to_proto(), expected);
+ let result = stage
+ .find_frequent_sequential_patterns(&input)
+ .unwrap()
+ .to_relation()
+ .unwrap();
+ let Some(proto::relation::RelType::MlRelation(ml)) =
result.rel_type else {
+ panic!("ML relation")
+ };
+ let Some(proto::ml_relation::MlType::Fetch(fetch)) = ml.ml_type
else {
+ panic!("fetch")
+ };
+ assert_eq!(fetch.obj_ref.unwrap().id,
"______ML_CONNECT_HELPER______");
+ let method = &fetch.methods[0];
+ assert_eq!(method.method,
"prefixSpanFindFrequentSequentialPatterns");
+ assert_eq!(method.args.len(), 5);
+ for (arg, expected) in method.args[1..]
+ .iter()
+ .zip(case["args_b64"].as_array().unwrap())
+ {
+ let Some(proto::fetch::method::args::ArgsType::Param(actual))
= &arg.args_type
+ else {
+ panic!("param")
+ };
+ assert_eq!(
+ actual.encode_to_vec(),
+ STANDARD.decode(expected.as_str().unwrap()).unwrap()
+ );
+ }
+ }
+ }
+}
+
+#[test]
+fn mining_defaults_and_typed_getters() {
+ let fp = FPGrowth::new();
+ assert_eq!(fp.items_col(), "items");
+ assert_eq!(fp.prediction_col(), "prediction");
+ assert_eq!(fp.min_support(), 0.3);
+ assert_eq!(fp.min_confidence(), 0.8);
+ assert_eq!(fp.num_partitions(), None);
+ assert_eq!(fp.set_num_partitions(2).num_partitions(), Some(2));
+ let seq = PrefixSpan::new();
+ assert_eq!(seq.min_support(), 0.1);
+ assert_eq!(seq.max_pattern_length(), 10);
+ assert_eq!(seq.max_local_proj_db_size(), 32000000);
+ assert_eq!(seq.sequence_col(), "sequence");
+ assert_eq!(
+ seq.set_max_local_proj_db_size(1_i64 << 31)
+ .max_local_proj_db_size(),
+ 1_i64 << 31
+ );
+}
diff --git a/docs/compatibility.md b/docs/compatibility.md
index fc869025..69c4e225 100644
--- a/docs/compatibility.md
+++ b/docs/compatibility.md
@@ -857,3 +857,34 @@ model lifetime, invalid inputs and pandas rejection.
Schema checks compare class
nullability and ML metadata; Connect omits the backing SQL schema of JVM UDTs
on the wire.
Run `scripts/capture_ml_features_golden.py` with the official client to
regenerate the fixture.
Native live tests run in CI; set `FEATURE_REFERENCE=1` explicitly to run their
reference mode.
+
+
+## Native FPGrowth and PrefixSpan
+
+Rust `ml::FPGrowth` fits Spark's frequent-itemset model and returns a typed
+`FPGrowthModel`. The model exposes lazy `freq_itemsets()` and
`association_rules()`
+DataFrames and `transform()` predictions. The Python classes are exported from
+`pyspark.ml.connect` and `pyspark.ml.connect.fpm`; fitted models expose
+`freqItemsets` and `associationRules` as properties. All five estimator
constructor
+parameters have named setters; model setters cover the item column, prediction
+column and minimum confidence. Parameters for prediction are captured when its
lazy
+plan is built. The itemset/rule properties fetch the fitted server model,
matching
+standard PySpark's Connect attribute relations.
+
+Rust `ml::PrefixSpan::find_frequent_sequential_patterns` and Python
+`PrefixSpan.findFrequentSequentialPatterns` mine arrays of itemsets directly
through
+the Connect helper, with all four constructor parameters and named setters.
They
+return sequence/frequency DataFrames and have no fit/transform model.
+
+These APIs accept Spark DataFrames and reject pandas frames before requests.
Lazy
+model tables retain their cached model; PrefixSpan retains its input plan,
including
+any upstream fitted models. Fitted-model transforms require the fitting
session.
+Persistence is outside this native addition. The vendored `pyspark.ml.fpm`
module is
+unchanged.
+
+Spark 4.3.0's Connect helper currently rejects `Long` argument literals:
PrefixSpan's
+`maxLocalProjDBSize` works within the signed 32-bit range, including its
default
+32,000,000; larger values raise the same `LONG not supported` server error as
official
+PySpark. The client preserves PySpark's integer widths and explicit null
parameters.
+Tests cover this limitation, typed string/integer itemsets, association rules,
held-out
+predictions, model setters, sequence-length limits, invalid data, and model
lifetime.
diff --git a/python/pyspark/ml/connect/__init__.py
b/python/pyspark/ml/connect/__init__.py
index 2ebb7d17..2cb2c64f 100644
--- a/python/pyspark/ml/connect/__init__.py
+++ b/python/pyspark/ml/connect/__init__.py
@@ -41,6 +41,7 @@ from pyspark.ml.connect.evaluation import (
)
from pyspark.ml.connect.pipeline import Pipeline, PipelineModel
from pyspark.ml.connect.tuning import CrossValidator, CrossValidatorModel
+from pyspark.ml.connect.fpm import FPGrowth, FPGrowthModel, PrefixSpan
from pyspark._pyspark import MLModel
# Base ABCs (vendored from upstream base.py) and the submodules, matching the
reference
@@ -100,6 +101,9 @@ __all__ = [
"CrossValidator",
"CrossValidatorModel",
"MLModel",
+ "FPGrowth",
+ "FPGrowthModel",
+ "PrefixSpan",
]
__all__ += [name for name in _native._ml_feature_names if name not in __all__]
diff --git a/python/pyspark/ml/connect/fpm.py b/python/pyspark/ml/connect/fpm.py
new file mode 100644
index 00000000..7699aa05
--- /dev/null
+++ b/python/pyspark/ml/connect/fpm.py
@@ -0,0 +1,5 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Native Spark Connect frequent itemset and sequence mining."""
+from pyspark._pyspark import FPGrowth, FPGrowthModel, PrefixSpan
+
+__all__ = ["FPGrowth", "FPGrowthModel", "PrefixSpan"]
diff --git a/python/tests/_frequent_patterns.py
b/python/tests/_frequent_patterns.py
new file mode 100644
index 00000000..67795db5
--- /dev/null
+++ b/python/tests/_frequent_patterns.py
@@ -0,0 +1,45 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Reference inputs and output normalization for frequent-pattern mining."""
+
+import json
+from pathlib import Path
+
+import pytest
+
+GOLDEN = json.loads((Path(__file__).parents[2] /
"tests/golden/frequent_patterns.json").read_text())
+
+
+def configured(cls, values, setters=False):
+ 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 normalized(frame, kind):
+ result = []
+ for row in frame.collect():
+ row = list(row)
+ if kind == "predictions":
+ row[-1] = sorted(row[-1])
+ elif kind == "itemsets":
+ row[0] = sorted(row[0])
+ elif kind == "rules":
+ row[0], row[1] = sorted(row[0]), sorted(row[1])
+ else:
+ row[0] = [sorted(v) for v in row[0]]
+ result.append(row)
+ return sorted(result, key=lambda v: json.dumps(v))
+
+
+def assert_values(actual, expected):
+ if isinstance(expected, list):
+ assert len(actual) == len(expected)
+ for a, e in zip(actual, expected):
+ assert_values(a, e)
+ elif isinstance(expected, float):
+ assert actual == pytest.approx(expected, rel=1e-10, abs=1e-12)
+ else:
+ assert actual == expected
diff --git a/python/tests/test_frequent_patterns_e2e.py
b/python/tests/test_frequent_patterns_e2e.py
new file mode 100644
index 00000000..93427155
--- /dev/null
+++ b/python/tests/test_frequent_patterns_e2e.py
@@ -0,0 +1,133 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Native frequent-pattern mining, with explicit official-reference mode."""
+
+import gc
+import os
+
+import pytest
+from _frequent_patterns import GOLDEN, assert_values, configured, normalized
+from pyspark.errors import PySparkException
+from pyspark.sql import SparkSession
+
+REFERENCE = os.environ.get("FPM_REFERENCE") == "1"
+
+
+def algorithm(name):
+ if REFERENCE:
+ from pyspark.ml import fpm
+ else:
+ from pyspark import _pyspark
+ from pyspark.ml.connect import fpm
+
+ assert getattr(fpm, name) is getattr(_pyspark, name)
+ return getattr(fpm, name)
+
+
[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()
+ yield spark
+ spark.stop()
+
+
[email protected]("case", GOLDEN["fpgrowth"], ids=lambda c: c["id"])
[email protected]("setters", [False, True])
+def
test_fpgrowth_mines_and_predicts_like_official_and_retains_results(session,
case, setters):
+ estimator = configured(algorithm("FPGrowth"), case["values"], setters)
+ model = estimator.fit(session.sql(case["sql"]))
+ assert isinstance(model, algorithm("FPGrowthModel"))
+ held = session.sql(case["held"])
+ tables = {
+ "itemsets": model.freqItemsets,
+ "rules": model.associationRules,
+ "predictions": model.transform(held),
+ }
+ assert model.setMinConfidence(0.95) is model
+ assert model.setPredictionCol("changed") is model
+ tables["changed_predictions"] = model.transform(held)
+ del model, estimator
+ gc.collect()
+ for name, table in tables.items():
+ assert_values(
+ normalized(table, "predictions" if name == "changed_predictions"
else name),
+ case[name]["rows"],
+ )
+ assert table.schema.jsonValue() == case[name]["schema"]
+
+
[email protected]("case", GOLDEN["prefixspan"])
[email protected]("setters", [False, True])
+def test_prefixspan_matches_official_patterns_and_projection_limits(session,
case, setters):
+ stage = configured(algorithm("PrefixSpan"), case["values"], setters)
+ patterns =
stage.findFrequentSequentialPatterns(session.sql(GOLDEN["sequences"]))
+ stage.setMaxPatternLength(99)
+ del stage
+ assert_values(normalized(patterns, "sequences"), case["rows"])
+ assert patterns.schema.jsonValue() == case["schema"]
+
+
[email protected](
+ "name,values",
+ [
+ ("FPGrowth", dict(minSupport=-0.1)),
+ ("FPGrowth", dict(minConfidence=1.1)),
+ ("FPGrowth", dict(numPartitions=0)),
+ ("PrefixSpan", dict(minSupport=-0.1)),
+ ("PrefixSpan", dict(maxPatternLength=0)),
+ ],
+)
+def test_spark_rejects_invalid_mining_parameters(session, name, values):
+ with pytest.raises(PySparkException):
+ if name == "FPGrowth":
+ algorithm(name)(itemsCol="basket", **values).fit(
+ session.sql(GOLDEN["fpgrowth"][0]["sql"])
+ )
+ else:
+ algorithm(name)(sequenceCol="events",
**values).findFrequentSequentialPatterns(
+ session.sql(GOLDEN["sequences"])
+ ).collect()
+
+
+def test_duplicate_items_are_rejected(session):
+ with pytest.raises(PySparkException):
+ algorithm("FPGrowth")().fit(session.sql("SELECT array('a','a') AS
items"))
+
+
+def test_prefixspan_composes_with_upstream_fitted_model(session):
+ from pyspark.sql import functions as F
+
+ case = GOLDEN["fpgrowth"][0]
+ model =
algorithm("FPGrowth")(**case["values"]).fit(session.sql(case["sql"]))
+ predicted = model.transform(session.sql(case["held"]))
+ sequences = predicted.select(F.array("suggested").alias("sequence"))
+ result = algorithm("PrefixSpan")(
+ minSupport=0.1, maxPatternLength=2
+ ).findFrequentSequentialPatterns(sequences)
+ # Official helper relations do not retain upstream models; retain them in
reference mode.
+ if not REFERENCE:
+ del sequences, predicted, model
+ gc.collect()
+ assert result.count() > 0
+
+
+def test_native_model_rejects_other_session_before_query(session):
+ if REFERENCE:
+ pytest.skip("Native fitted-session ownership contract")
+ case = GOLDEN["fpgrowth"][0]
+ model =
algorithm("FPGrowth")(**case["values"]).fit(session.sql(case["sql"]))
+ other = session.newSession()
+ try:
+ with pytest.raises(ValueError, match="fitting session"):
+ model.transform(other.sql(case["held"]))
+ finally:
+ other.stop()
+
+
+def
test_prefixspan_reports_the_server_limit_for_long_helper_arguments(session):
+ with pytest.raises(PySparkException, match="LONG not supported"):
+ algorithm("PrefixSpan")(
+ sequenceCol="events", maxLocalProjDBSize=2**31
+
).findFrequentSequentialPatterns(session.sql(GOLDEN["sequences"])).collect()
diff --git a/python/tests/test_frequent_patterns_offline.py
b/python/tests/test_frequent_patterns_offline.py
new file mode 100644
index 00000000..f8cb135a
--- /dev/null
+++ b/python/tests/test_frequent_patterns_offline.py
@@ -0,0 +1,149 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Native frequent-pattern signatures, wire protocol and input rejection."""
+
+import base64
+import inspect
+
+import pytest
+from _frequent_patterns import GOLDEN, configured
+from _mock_connect_server import mock_connect_session
+from pyspark import _pyspark
+from pyspark.ml.connect import fpm
+from pyspark.sql import SparkSession
+from pyspark.sql.connect import proto as pb2
+from test_ml_offline import _commands_but_deletes, _operator_info, _relation,
_requests_but_deletes
+
+
[email protected](scope="module")
+def server():
+ with mock_connect_session() as pair:
+ yield pair
+
+
[email protected]
+def session(server):
+ _, service = server
+ service.reset()
+ spark = SparkSession.builder.remote(service.remote).getOrCreate()
+ yield spark, service
+ service.forget_session(spark.session_id)
+ spark.stop()
+
+
[email protected]("name", ["FPGrowth", "PrefixSpan"])
+def test_native_exports_and_constructor_signatures(name):
+ import pyspark.ml.connect as connect
+
+ cls = getattr(fpm, name)
+ assert cls is getattr(_pyspark, name) is getattr(connect, name)
+ parameters = inspect.signature(cls).parameters
+ assert list(parameters) == list(GOLDEN["defaults"][name])
+ for key, value in GOLDEN["defaults"][name].items():
+ assert parameters[key].default == value
+ assert parameters[key].kind == inspect.Parameter.KEYWORD_ONLY
+ with pytest.raises(TypeError, match="keyword arguments"):
+ cls(1)
+ with pytest.raises(TypeError, match="unexpected keyword"):
+ cls(unknown=1)
+
+
[email protected]("case", GOLDEN["params"])
[email protected]("setters", [False, True])
+def test_parameters_and_helper_arguments_match_official(session, case,
setters):
+ spark, service = session
+ stage = configured(getattr(fpm, case["name"]), case["values"], setters)
+ expected = pb2.MlParams.FromString(base64.b64decode(case["params_b64"]))
+ frame = spark.range(1)
+ if case["name"] == "FPGrowth":
+ service.execute_payload = _operator_info("mining-model")
+ sent = len(service.execute_requests)
+ model = stage.fit(frame)
+ assert isinstance(model, fpm.FPGrowthModel)
+ fit = _commands_but_deletes(service, sent)[0].ml_command.fit
+ assert fit.estimator.name == "org.apache.spark.ml.fpm.FPGrowth"
+ assert fit.params == expected
+ assert fit.dataset == _relation(frame)
+ transformed = _relation(model.transform(frame)).ml_relation.transform
+ assert transformed.params == expected
+ assert transformed.obj_ref.id == "mining-model"
+ for attribute in ["freqItemsets", "associationRules"]:
+ sent = _requests_but_deletes(service)
+ fetch = _relation(getattr(model, attribute)).ml_relation.fetch
+ assert fetch.obj_ref.id == "mining-model"
+ assert len(fetch.methods) == 1
+ assert fetch.methods[0].method == attribute
+ assert not fetch.methods[0].args
+ assert _requests_but_deletes(service) == sent
+ else:
+ sent = _requests_but_deletes(service)
+ result = stage.findFrequentSequentialPatterns(frame)
+ fetch = _relation(result).ml_relation.fetch
+ assert fetch.obj_ref.id == "______ML_CONNECT_HELPER______"
+ assert len(fetch.methods) == 1
+ method = fetch.methods[0]
+ assert method.method == case["helper"]
+ assert method.args[0].input == _relation(frame)
+ assert [arg.param.SerializeToString() for arg in method.args[1:]] == [
+ base64.b64decode(v) for v in case["args_b64"]
+ ]
+ assert _requests_but_deletes(service) == sent
+
+
[email protected](
+ "name,params", [(name, list(values)) for name, values in
GOLDEN["defaults"].items()]
+)
+def test_setters_validate_types(name, params):
+ stage = getattr(fpm, name)()
+ for param in params:
+ with pytest.raises(TypeError, match="Invalid param value"):
+ getattr(stage, "set" + param[0].upper() + param[1:])(object())
+
+
+def test_rejects_pandas_before_validation_or_requests(session):
+ import pandas as pd
+
+ spark, service = session
+ service.execute_payload = _operator_info("pandas-model")
+ model = fpm.FPGrowth().fit(spark.range(1))
+ for method in [
+ fpm.FPGrowth(numPartitions=2**70).fit,
+ model.transform,
+
fpm.PrefixSpan(maxLocalProjDBSize=2**70).findFrequentSequentialPatterns,
+ ]:
+ for frame in [pd.DataFrame(), pd.DataFrame({"items": [["a"]]})]:
+ sent = _requests_but_deletes(service)
+ with pytest.raises(TypeError, match="requires a Spark DataFrame"):
+ method(frame)
+ assert _requests_but_deletes(service) == sent
+
+
[email protected](
+ "name,param", [("FPGrowth", "numPartitions"), ("PrefixSpan",
"maxLocalProjDBSize")]
+)
+def test_oversized_integers_fail_before_requests_and_setters_recover(session,
name, param):
+ from pyspark.errors import PySparkValueError
+
+ spark, service = session
+ stage = getattr(fpm, name)(**{param: 2**70})
+ operation = stage.fit if name == "FPGrowth" else
stage.findFrequentSequentialPatterns
+ sent = _requests_but_deletes(service)
+ with pytest.raises(PySparkValueError, match="VALUE_NOT_BETWEEN"):
+ operation(spark.range(1))
+ assert _requests_but_deletes(service) == sent
+ getattr(stage, "set" + param[0].upper() + param[1:])(1)
+ service.execute_payload = _operator_info("recovered-model")
+ operation(spark.range(1))
+
+
+def test_fitted_model_named_setters_snapshot_transform_parameters(session):
+ spark, service = session
+ service.execute_payload = _operator_info("model-setters")
+ model = fpm.FPGrowth(itemsCol="items",
minConfidence=0.6).fit(spark.range(1))
+ before = model.transform(spark.range(1))
+ assert model.setItemsCol("basket") is model
+ assert model.setPredictionCol("next") is model
+ assert model.setMinConfidence(0.9) is model
+ after =
_relation(model.transform(spark.range(1))).ml_relation.transform.params.params
+ assert after["itemsCol"].string == "basket" and
after["predictionCol"].string == "next"
+ assert after["minConfidence"].double == 0.9
+ assert
_relation(before).ml_relation.transform.params.params["minConfidence"].double
== 0.6
diff --git a/scripts/capture_frequent_patterns_golden.py
b/scripts/capture_frequent_patterns_golden.py
new file mode 100644
index 00000000..cc40c052
--- /dev/null
+++ b/scripts/capture_frequent_patterns_golden.py
@@ -0,0 +1,141 @@
+#!/usr/bin/env python3
+"""Capture frequent-pattern mining fixtures with official PySpark 4.3.0."""
+
+import argparse
+import base64
+import inspect
+import json
+from pathlib import Path
+
+import pyspark
+from pyspark.ml import fpm
+from pyspark.ml.connect.serialize import serialize_ml_params
+from pyspark.sql import SparkSession
+
+TRANSACTIONS = "SELECT * FROM VALUES (0,array('a','b')), (1,array('b','c')),
(2,array('a','b','c')), (3,array('a','c')), (4,array('a','b')), (5,array('b'))
AS t(id,basket)"
+HELD_OUT = "SELECT * FROM VALUES (10,array('a')), (11,array('b')),
(12,array('a','b')), (13,array('z')), (14,CAST(array() AS ARRAY<STRING>)) AS
t(id,basket)"
+NUMERIC = "SELECT * FROM VALUES (0,array(1,2)), (1,array(2,3)),
(2,array(1,2,3)), (3,array(1,3)), (4,array(1,2)), (5,array(2)) AS t(id,basket)"
+SEQUENCES = "SELECT * FROM VALUES (0,array(array(1,2),array(3))),
(1,array(array(1),array(3,2),array(1,2))), (2,array(array(1,2),array(5))),
(3,array(array(6))) AS t(id,events)"
+
+
+def rows(frame, kind):
+ values = []
+ for row in frame.collect():
+ row = list(row)
+ if kind == "predictions":
+ row[-1] = sorted(row[-1])
+ elif kind == "itemsets":
+ row[0] = sorted(row[0])
+ elif kind == "rules":
+ row[0], row[1] = sorted(row[0]), sorted(row[1])
+ else:
+ row[0] = [sorted(v) for v in row[0]]
+ values.append(row)
+ return sorted(values, key=lambda v: json.dumps(v))
+
+
+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/frequent_patterns.json"))
+ args = parser.parse_args()
+ assert pyspark.__version__ == "4.3.0"
+ spark = SparkSession.builder.remote(args.remote).getOrCreate()
+ result = {
+ "spark_version": pyspark.__version__,
+ "defaults": {},
+ "params": [],
+ "fpgrowth": [],
+ "prefixspan": [],
+ "sequences": SEQUENCES,
+ }
+ try:
+ samples = {
+ "FPGrowth": dict(
+ minSupport=0.4,
+ minConfidence=0.7,
+ itemsCol="basket",
+ predictionCol="suggested",
+ numPartitions=2,
+ ),
+ "PrefixSpan": dict(
+ minSupport=0.5, maxPatternLength=5, maxLocalProjDBSize=2**31,
sequenceCol="events"
+ ),
+ }
+ for name, values in samples.items():
+ cls = getattr(fpm, name)
+ result["defaults"][name] = {
+ k: v.default for k, v in
inspect.signature(cls).parameters.items()
+ }
+ variants = [{}, values, {k: None for k in values}]
+ if name == "PrefixSpan":
+ variants += [
+ dict(values, maxLocalProjDBSize=size) for size in [2**31 -
1, 2**63 - 1]
+ ]
+ for values in variants:
+ instance = cls(**values)
+ entry = {
+ "name": name,
+ "values": values,
+ "params_b64": encoded(serialize_ml_params(instance,
spark.client)),
+ }
+ if name == "PrefixSpan":
+ fetch = (
+ instance.findFrequentSequentialPatterns(spark.range(1))
+ ._plan.plan(spark.client)
+ .ml_relation.fetch
+ )
+ entry["helper"] = fetch.methods[0].method
+ entry["args_b64"] = [encoded(arg.param) for arg in
fetch.methods[0].args[1:]]
+ result["params"].append(entry)
+ for key, sql, held, support, confidence, partitions in [
+ ("strings", TRANSACTIONS, HELD_OUT, 0.3, 0.5, 2),
+ ("high-confidence", TRANSACTIONS, HELD_OUT, 0.5, 0.9, 1),
+ ("integers", NUMERIC, NUMERIC, 0.3, 0.6, 2),
+ ]:
+ values = dict(
+ minSupport=support,
+ minConfidence=confidence,
+ itemsCol="basket",
+ predictionCol="suggested",
+ numPartitions=partitions,
+ )
+ model = fpm.FPGrowth(**values).fit(spark.sql(sql))
+ entry = dict(id=key, sql=sql, held=held, values=values)
+ for name, frame, kind in [
+ ("itemsets", model.freqItemsets, "itemsets"),
+ ("rules", model.associationRules, "rules"),
+ ("predictions", model.transform(spark.sql(held)),
"predictions"),
+ ]:
+ entry[name] = {"rows": rows(frame, kind), "schema":
frame.schema.jsonValue()}
+ changed = (
+
model.setMinConfidence(0.95).setPredictionCol("changed").transform(spark.sql(held))
+ )
+ entry["changed_predictions"] = {
+ "rows": rows(changed, "predictions"),
+ "schema": changed.schema.jsonValue(),
+ }
+ result["fpgrowth"].append(entry)
+ for length, size in [(5, 32000000), (1, 1024)]:
+ values = dict(
+ minSupport=0.5,
+ maxPatternLength=length,
+ maxLocalProjDBSize=size,
+ sequenceCol="events",
+ )
+ frame =
fpm.PrefixSpan(**values).findFrequentSequentialPatterns(spark.sql(SEQUENCES))
+ result["prefixspan"].append(
+ dict(values=values, rows=rows(frame, "sequences"),
schema=frame.schema.jsonValue())
+ )
+ args.out.write_text(json.dumps(result, indent=2) + "\n")
+ print("Captured FPGrowth itemsets, rules and predictions, and
PrefixSpan results.")
+ finally:
+ spark.stop()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/golden/frequent_patterns.json
b/tests/golden/frequent_patterns.json
new file mode 100644
index 00000000..70a97a45
--- /dev/null
+++ b/tests/golden/frequent_patterns.json
@@ -0,0 +1,1178 @@
+{
+ "spark_version": "4.3.0",
+ "defaults": {
+ "FPGrowth": {
+ "minSupport": 0.3,
+ "minConfidence": 0.8,
+ "itemsCol": "items",
+ "predictionCol": "prediction",
+ "numPartitions": null
+ },
+ "PrefixSpan": {
+ "minSupport": 0.1,
+ "maxPatternLength": 10,
+ "maxLocalProjDBSize": 32000000,
+ "sequenceCol": "sequence"
+ }
+ },
+ "params": [
+ {
+ "name": "FPGrowth",
+ "values": {},
+ "params_b64": ""
+ },
+ {
+ "name": "FPGrowth",
+ "values": {
+ "minSupport": 0.4,
+ "minConfidence": 0.7,
+ "itemsCol": "basket",
+ "predictionCol": "suggested",
+ "numPartitions": 2
+ },
+ "params_b64":
"ChQKCGl0ZW1zQ29sEghqBmJhc2tldAoaCg1taW5Db25maWRlbmNlEglZZmZmZmZm5j8KFwoKbWluU3VwcG9ydBIJWZqZmZmZmdk/ChMKDW51bVBhcnRpdGlvbnMSAjACChwKDXByZWRpY3Rpb25Db2wSC2oJc3VnZ2VzdGVk"
+ },
+ {
+ "name": "FPGrowth",
+ "values": {
+ "minSupport": null,
+ "minConfidence": null,
+ "itemsCol": null,
+ "predictionCol": null,
+ "numPartitions": null
+ },
+ "params_b64":
"ChAKCGl0ZW1zQ29sEgQKAgoAChUKDW1pbkNvbmZpZGVuY2USBAoCCgAKEgoKbWluU3VwcG9ydBIECgIKAAoVCg1udW1QYXJ0aXRpb25zEgQKAgoAChUKDXByZWRpY3Rpb25Db2wSBAoCCgA="
+ },
+ {
+ "name": "PrefixSpan",
+ "values": {},
+ "params_b64": "",
+ "helper": "prefixSpanFindFrequentSequentialPatterns",
+ "args_b64": [
+ "WZqZmZmZmbk/",
+ "MAo=",
+ "MICQoQ8=",
+ "aghzZXF1ZW5jZQ=="
+ ]
+ },
+ {
+ "name": "PrefixSpan",
+ "values": {
+ "minSupport": 0.5,
+ "maxPatternLength": 5,
+ "maxLocalProjDBSize": 2147483648,
+ "sequenceCol": "events"
+ },
+ "params_b64":
"ChwKEm1heExvY2FsUHJvakRCU2l6ZRIGOICAgIAIChYKEG1heFBhdHRlcm5MZW5ndGgSAjAFChcKCm1pblN1cHBvcnQSCVkAAAAAAADgPwoXCgtzZXF1ZW5jZUNvbBIIagZldmVudHM=",
+ "helper": "prefixSpanFindFrequentSequentialPatterns",
+ "args_b64": [
+ "WQAAAAAAAOA/",
+ "MAU=",
+ "OICAgIAI",
+ "agZldmVudHM="
+ ]
+ },
+ {
+ "name": "PrefixSpan",
+ "values": {
+ "minSupport": null,
+ "maxPatternLength": null,
+ "maxLocalProjDBSize": null,
+ "sequenceCol": null
+ },
+ "params_b64":
"ChoKEm1heExvY2FsUHJvakRCU2l6ZRIECgIKAAoYChBtYXhQYXR0ZXJuTGVuZ3RoEgQKAgoAChIKCm1pblN1cHBvcnQSBAoCCgAKEwoLc2VxdWVuY2VDb2wSBAoCCgA=",
+ "helper": "prefixSpanFindFrequentSequentialPatterns",
+ "args_b64": [
+ "CgIKAA==",
+ "CgIKAA==",
+ "CgIKAA==",
+ "CgIKAA=="
+ ]
+ },
+ {
+ "name": "PrefixSpan",
+ "values": {
+ "minSupport": 0.5,
+ "maxPatternLength": 5,
+ "maxLocalProjDBSize": 2147483647,
+ "sequenceCol": "events"
+ },
+ "params_b64":
"ChwKEm1heExvY2FsUHJvakRCU2l6ZRIGMP////8HChYKEG1heFBhdHRlcm5MZW5ndGgSAjAFChcKCm1pblN1cHBvcnQSCVkAAAAAAADgPwoXCgtzZXF1ZW5jZUNvbBIIagZldmVudHM=",
+ "helper": "prefixSpanFindFrequentSequentialPatterns",
+ "args_b64": [
+ "WQAAAAAAAOA/",
+ "MAU=",
+ "MP////8H",
+ "agZldmVudHM="
+ ]
+ },
+ {
+ "name": "PrefixSpan",
+ "values": {
+ "minSupport": 0.5,
+ "maxPatternLength": 5,
+ "maxLocalProjDBSize": 9223372036854775807,
+ "sequenceCol": "events"
+ },
+ "params_b64":
"CiAKEm1heExvY2FsUHJvakRCU2l6ZRIKOP//////////fwoWChBtYXhQYXR0ZXJuTGVuZ3RoEgIwBQoXCgptaW5TdXBwb3J0EglZAAAAAAAA4D8KFwoLc2VxdWVuY2VDb2wSCGoGZXZlbnRz",
+ "helper": "prefixSpanFindFrequentSequentialPatterns",
+ "args_b64": [
+ "WQAAAAAAAOA/",
+ "MAU=",
+ "OP//////////fw==",
+ "agZldmVudHM="
+ ]
+ }
+ ],
+ "fpgrowth": [
+ {
+ "id": "strings",
+ "sql": "SELECT * FROM VALUES (0,array('a','b')), (1,array('b','c')),
(2,array('a','b','c')), (3,array('a','c')), (4,array('a','b')), (5,array('b'))
AS t(id,basket)",
+ "held": "SELECT * FROM VALUES (10,array('a')), (11,array('b')),
(12,array('a','b')), (13,array('z')), (14,CAST(array() AS ARRAY<STRING>)) AS
t(id,basket)",
+ "values": {
+ "minSupport": 0.3,
+ "minConfidence": 0.5,
+ "itemsCol": "basket",
+ "predictionCol": "suggested",
+ "numPartitions": 2
+ },
+ "itemsets": {
+ "rows": [
+ [
+ [
+ "a",
+ "b"
+ ],
+ 3
+ ],
+ [
+ [
+ "a",
+ "c"
+ ],
+ 2
+ ],
+ [
+ [
+ "a"
+ ],
+ 4
+ ],
+ [
+ [
+ "b",
+ "c"
+ ],
+ 2
+ ],
+ [
+ [
+ "b"
+ ],
+ 5
+ ],
+ [
+ [
+ "c"
+ ],
+ 3
+ ]
+ ],
+ "schema": {
+ "type": "struct",
+ "fields": [
+ {
+ "name": "items",
+ "type": {
+ "type": "array",
+ "elementType": "string",
+ "containsNull": false
+ },
+ "nullable": false,
+ "metadata": {}
+ },
+ {
+ "name": "freq",
+ "type": "long",
+ "nullable": false,
+ "metadata": {}
+ }
+ ]
+ }
+ },
+ "rules": {
+ "rows": [
+ [
+ [
+ "a"
+ ],
+ [
+ "b"
+ ],
+ 0.75,
+ 0.8999999999999999,
+ 0.5
+ ],
+ [
+ [
+ "a"
+ ],
+ [
+ "c"
+ ],
+ 0.5,
+ 1.0,
+ 0.3333333333333333
+ ],
+ [
+ [
+ "b"
+ ],
+ [
+ "a"
+ ],
+ 0.6,
+ 0.9,
+ 0.5
+ ],
+ [
+ [
+ "c"
+ ],
+ [
+ "a"
+ ],
+ 0.6666666666666666,
+ 1.0,
+ 0.3333333333333333
+ ],
+ [
+ [
+ "c"
+ ],
+ [
+ "b"
+ ],
+ 0.6666666666666666,
+ 0.7999999999999999,
+ 0.3333333333333333
+ ]
+ ],
+ "schema": {
+ "type": "struct",
+ "fields": [
+ {
+ "name": "antecedent",
+ "type": {
+ "type": "array",
+ "elementType": "string",
+ "containsNull": false
+ },
+ "nullable": false,
+ "metadata": {}
+ },
+ {
+ "name": "consequent",
+ "type": {
+ "type": "array",
+ "elementType": "string",
+ "containsNull": false
+ },
+ "nullable": false,
+ "metadata": {}
+ },
+ {
+ "name": "confidence",
+ "type": "double",
+ "nullable": false,
+ "metadata": {}
+ },
+ {
+ "name": "lift",
+ "type": "double",
+ "nullable": true,
+ "metadata": {}
+ },
+ {
+ "name": "support",
+ "type": "double",
+ "nullable": false,
+ "metadata": {}
+ }
+ ]
+ }
+ },
+ "predictions": {
+ "rows": [
+ [
+ 10,
+ [
+ "a"
+ ],
+ [
+ "b",
+ "c"
+ ]
+ ],
+ [
+ 11,
+ [
+ "b"
+ ],
+ [
+ "a"
+ ]
+ ],
+ [
+ 12,
+ [
+ "a",
+ "b"
+ ],
+ [
+ "c"
+ ]
+ ],
+ [
+ 13,
+ [
+ "z"
+ ],
+ []
+ ],
+ [
+ 14,
+ [],
+ []
+ ]
+ ],
+ "schema": {
+ "type": "struct",
+ "fields": [
+ {
+ "name": "id",
+ "type": "integer",
+ "nullable": false,
+ "metadata": {}
+ },
+ {
+ "name": "basket",
+ "type": {
+ "type": "array",
+ "elementType": "string",
+ "containsNull": true
+ },
+ "nullable": false,
+ "metadata": {}
+ },
+ {
+ "name": "suggested",
+ "type": {
+ "type": "array",
+ "elementType": "string",
+ "containsNull": true
+ },
+ "nullable": true,
+ "metadata": {}
+ }
+ ]
+ }
+ },
+ "changed_predictions": {
+ "rows": [
+ [
+ 10,
+ [
+ "a"
+ ],
+ []
+ ],
+ [
+ 11,
+ [
+ "b"
+ ],
+ []
+ ],
+ [
+ 12,
+ [
+ "a",
+ "b"
+ ],
+ []
+ ],
+ [
+ 13,
+ [
+ "z"
+ ],
+ []
+ ],
+ [
+ 14,
+ [],
+ []
+ ]
+ ],
+ "schema": {
+ "type": "struct",
+ "fields": [
+ {
+ "name": "id",
+ "type": "integer",
+ "nullable": false,
+ "metadata": {}
+ },
+ {
+ "name": "basket",
+ "type": {
+ "type": "array",
+ "elementType": "string",
+ "containsNull": true
+ },
+ "nullable": false,
+ "metadata": {}
+ },
+ {
+ "name": "changed",
+ "type": {
+ "type": "array",
+ "elementType": "string",
+ "containsNull": true
+ },
+ "nullable": true,
+ "metadata": {}
+ }
+ ]
+ }
+ }
+ },
+ {
+ "id": "high-confidence",
+ "sql": "SELECT * FROM VALUES (0,array('a','b')), (1,array('b','c')),
(2,array('a','b','c')), (3,array('a','c')), (4,array('a','b')), (5,array('b'))
AS t(id,basket)",
+ "held": "SELECT * FROM VALUES (10,array('a')), (11,array('b')),
(12,array('a','b')), (13,array('z')), (14,CAST(array() AS ARRAY<STRING>)) AS
t(id,basket)",
+ "values": {
+ "minSupport": 0.5,
+ "minConfidence": 0.9,
+ "itemsCol": "basket",
+ "predictionCol": "suggested",
+ "numPartitions": 1
+ },
+ "itemsets": {
+ "rows": [
+ [
+ [
+ "a",
+ "b"
+ ],
+ 3
+ ],
+ [
+ [
+ "a"
+ ],
+ 4
+ ],
+ [
+ [
+ "b"
+ ],
+ 5
+ ],
+ [
+ [
+ "c"
+ ],
+ 3
+ ]
+ ],
+ "schema": {
+ "type": "struct",
+ "fields": [
+ {
+ "name": "items",
+ "type": {
+ "type": "array",
+ "elementType": "string",
+ "containsNull": false
+ },
+ "nullable": false,
+ "metadata": {}
+ },
+ {
+ "name": "freq",
+ "type": "long",
+ "nullable": false,
+ "metadata": {}
+ }
+ ]
+ }
+ },
+ "rules": {
+ "rows": [],
+ "schema": {
+ "type": "struct",
+ "fields": [
+ {
+ "name": "antecedent",
+ "type": {
+ "type": "array",
+ "elementType": "string",
+ "containsNull": false
+ },
+ "nullable": false,
+ "metadata": {}
+ },
+ {
+ "name": "consequent",
+ "type": {
+ "type": "array",
+ "elementType": "string",
+ "containsNull": false
+ },
+ "nullable": false,
+ "metadata": {}
+ },
+ {
+ "name": "confidence",
+ "type": "double",
+ "nullable": false,
+ "metadata": {}
+ },
+ {
+ "name": "lift",
+ "type": "double",
+ "nullable": true,
+ "metadata": {}
+ },
+ {
+ "name": "support",
+ "type": "double",
+ "nullable": false,
+ "metadata": {}
+ }
+ ]
+ }
+ },
+ "predictions": {
+ "rows": [
+ [
+ 10,
+ [
+ "a"
+ ],
+ []
+ ],
+ [
+ 11,
+ [
+ "b"
+ ],
+ []
+ ],
+ [
+ 12,
+ [
+ "a",
+ "b"
+ ],
+ []
+ ],
+ [
+ 13,
+ [
+ "z"
+ ],
+ []
+ ],
+ [
+ 14,
+ [],
+ []
+ ]
+ ],
+ "schema": {
+ "type": "struct",
+ "fields": [
+ {
+ "name": "id",
+ "type": "integer",
+ "nullable": false,
+ "metadata": {}
+ },
+ {
+ "name": "basket",
+ "type": {
+ "type": "array",
+ "elementType": "string",
+ "containsNull": true
+ },
+ "nullable": false,
+ "metadata": {}
+ },
+ {
+ "name": "suggested",
+ "type": {
+ "type": "array",
+ "elementType": "string",
+ "containsNull": true
+ },
+ "nullable": true,
+ "metadata": {}
+ }
+ ]
+ }
+ },
+ "changed_predictions": {
+ "rows": [
+ [
+ 10,
+ [
+ "a"
+ ],
+ []
+ ],
+ [
+ 11,
+ [
+ "b"
+ ],
+ []
+ ],
+ [
+ 12,
+ [
+ "a",
+ "b"
+ ],
+ []
+ ],
+ [
+ 13,
+ [
+ "z"
+ ],
+ []
+ ],
+ [
+ 14,
+ [],
+ []
+ ]
+ ],
+ "schema": {
+ "type": "struct",
+ "fields": [
+ {
+ "name": "id",
+ "type": "integer",
+ "nullable": false,
+ "metadata": {}
+ },
+ {
+ "name": "basket",
+ "type": {
+ "type": "array",
+ "elementType": "string",
+ "containsNull": true
+ },
+ "nullable": false,
+ "metadata": {}
+ },
+ {
+ "name": "changed",
+ "type": {
+ "type": "array",
+ "elementType": "string",
+ "containsNull": true
+ },
+ "nullable": true,
+ "metadata": {}
+ }
+ ]
+ }
+ }
+ },
+ {
+ "id": "integers",
+ "sql": "SELECT * FROM VALUES (0,array(1,2)), (1,array(2,3)),
(2,array(1,2,3)), (3,array(1,3)), (4,array(1,2)), (5,array(2)) AS t(id,basket)",
+ "held": "SELECT * FROM VALUES (0,array(1,2)), (1,array(2,3)),
(2,array(1,2,3)), (3,array(1,3)), (4,array(1,2)), (5,array(2)) AS t(id,basket)",
+ "values": {
+ "minSupport": 0.3,
+ "minConfidence": 0.6,
+ "itemsCol": "basket",
+ "predictionCol": "suggested",
+ "numPartitions": 2
+ },
+ "itemsets": {
+ "rows": [
+ [
+ [
+ 1,
+ 2
+ ],
+ 3
+ ],
+ [
+ [
+ 1,
+ 3
+ ],
+ 2
+ ],
+ [
+ [
+ 1
+ ],
+ 4
+ ],
+ [
+ [
+ 2,
+ 3
+ ],
+ 2
+ ],
+ [
+ [
+ 2
+ ],
+ 5
+ ],
+ [
+ [
+ 3
+ ],
+ 3
+ ]
+ ],
+ "schema": {
+ "type": "struct",
+ "fields": [
+ {
+ "name": "items",
+ "type": {
+ "type": "array",
+ "elementType": "integer",
+ "containsNull": false
+ },
+ "nullable": false,
+ "metadata": {}
+ },
+ {
+ "name": "freq",
+ "type": "long",
+ "nullable": false,
+ "metadata": {}
+ }
+ ]
+ }
+ },
+ "rules": {
+ "rows": [
+ [
+ [
+ 1
+ ],
+ [
+ 2
+ ],
+ 0.75,
+ 0.8999999999999999,
+ 0.5
+ ],
+ [
+ [
+ 2
+ ],
+ [
+ 1
+ ],
+ 0.6,
+ 0.9,
+ 0.5
+ ],
+ [
+ [
+ 3
+ ],
+ [
+ 1
+ ],
+ 0.6666666666666666,
+ 1.0,
+ 0.3333333333333333
+ ],
+ [
+ [
+ 3
+ ],
+ [
+ 2
+ ],
+ 0.6666666666666666,
+ 0.7999999999999999,
+ 0.3333333333333333
+ ]
+ ],
+ "schema": {
+ "type": "struct",
+ "fields": [
+ {
+ "name": "antecedent",
+ "type": {
+ "type": "array",
+ "elementType": "integer",
+ "containsNull": false
+ },
+ "nullable": false,
+ "metadata": {}
+ },
+ {
+ "name": "consequent",
+ "type": {
+ "type": "array",
+ "elementType": "integer",
+ "containsNull": false
+ },
+ "nullable": false,
+ "metadata": {}
+ },
+ {
+ "name": "confidence",
+ "type": "double",
+ "nullable": false,
+ "metadata": {}
+ },
+ {
+ "name": "lift",
+ "type": "double",
+ "nullable": true,
+ "metadata": {}
+ },
+ {
+ "name": "support",
+ "type": "double",
+ "nullable": false,
+ "metadata": {}
+ }
+ ]
+ }
+ },
+ "predictions": {
+ "rows": [
+ [
+ 0,
+ [
+ 1,
+ 2
+ ],
+ []
+ ],
+ [
+ 1,
+ [
+ 2,
+ 3
+ ],
+ [
+ 1
+ ]
+ ],
+ [
+ 2,
+ [
+ 1,
+ 2,
+ 3
+ ],
+ []
+ ],
+ [
+ 3,
+ [
+ 1,
+ 3
+ ],
+ [
+ 2
+ ]
+ ],
+ [
+ 4,
+ [
+ 1,
+ 2
+ ],
+ []
+ ],
+ [
+ 5,
+ [
+ 2
+ ],
+ [
+ 1
+ ]
+ ]
+ ],
+ "schema": {
+ "type": "struct",
+ "fields": [
+ {
+ "name": "id",
+ "type": "integer",
+ "nullable": false,
+ "metadata": {}
+ },
+ {
+ "name": "basket",
+ "type": {
+ "type": "array",
+ "elementType": "integer",
+ "containsNull": false
+ },
+ "nullable": false,
+ "metadata": {}
+ },
+ {
+ "name": "suggested",
+ "type": {
+ "type": "array",
+ "elementType": "integer",
+ "containsNull": false
+ },
+ "nullable": true,
+ "metadata": {}
+ }
+ ]
+ }
+ },
+ "changed_predictions": {
+ "rows": [
+ [
+ 0,
+ [
+ 1,
+ 2
+ ],
+ []
+ ],
+ [
+ 1,
+ [
+ 2,
+ 3
+ ],
+ []
+ ],
+ [
+ 2,
+ [
+ 1,
+ 2,
+ 3
+ ],
+ []
+ ],
+ [
+ 3,
+ [
+ 1,
+ 3
+ ],
+ []
+ ],
+ [
+ 4,
+ [
+ 1,
+ 2
+ ],
+ []
+ ],
+ [
+ 5,
+ [
+ 2
+ ],
+ []
+ ]
+ ],
+ "schema": {
+ "type": "struct",
+ "fields": [
+ {
+ "name": "id",
+ "type": "integer",
+ "nullable": false,
+ "metadata": {}
+ },
+ {
+ "name": "basket",
+ "type": {
+ "type": "array",
+ "elementType": "integer",
+ "containsNull": false
+ },
+ "nullable": false,
+ "metadata": {}
+ },
+ {
+ "name": "changed",
+ "type": {
+ "type": "array",
+ "elementType": "integer",
+ "containsNull": false
+ },
+ "nullable": true,
+ "metadata": {}
+ }
+ ]
+ }
+ }
+ }
+ ],
+ "prefixspan": [
+ {
+ "values": {
+ "minSupport": 0.5,
+ "maxPatternLength": 5,
+ "maxLocalProjDBSize": 32000000,
+ "sequenceCol": "events"
+ },
+ "rows": [
+ [
+ [
+ [
+ 1,
+ 2
+ ]
+ ],
+ 3
+ ],
+ [
+ [
+ [
+ 1
+ ],
+ [
+ 3
+ ]
+ ],
+ 2
+ ],
+ [
+ [
+ [
+ 1
+ ]
+ ],
+ 3
+ ],
+ [
+ [
+ [
+ 2
+ ]
+ ],
+ 3
+ ],
+ [
+ [
+ [
+ 3
+ ]
+ ],
+ 2
+ ]
+ ],
+ "schema": {
+ "type": "struct",
+ "fields": [
+ {
+ "name": "sequence",
+ "type": {
+ "type": "array",
+ "elementType": {
+ "type": "array",
+ "elementType": "integer",
+ "containsNull": false
+ },
+ "containsNull": false
+ },
+ "nullable": false,
+ "metadata": {}
+ },
+ {
+ "name": "freq",
+ "type": "long",
+ "nullable": false,
+ "metadata": {}
+ }
+ ]
+ }
+ },
+ {
+ "values": {
+ "minSupport": 0.5,
+ "maxPatternLength": 1,
+ "maxLocalProjDBSize": 1024,
+ "sequenceCol": "events"
+ },
+ "rows": [
+ [
+ [
+ [
+ 1
+ ]
+ ],
+ 3
+ ],
+ [
+ [
+ [
+ 2
+ ]
+ ],
+ 3
+ ],
+ [
+ [
+ [
+ 3
+ ]
+ ],
+ 2
+ ]
+ ],
+ "schema": {
+ "type": "struct",
+ "fields": [
+ {
+ "name": "sequence",
+ "type": {
+ "type": "array",
+ "elementType": {
+ "type": "array",
+ "elementType": "integer",
+ "containsNull": false
+ },
+ "containsNull": false
+ },
+ "nullable": false,
+ "metadata": {}
+ },
+ {
+ "name": "freq",
+ "type": "long",
+ "nullable": false,
+ "metadata": {}
+ }
+ ]
+ }
+ }
+ ],
+ "sequences": "SELECT * FROM VALUES (0,array(array(1,2),array(3))),
(1,array(array(1),array(3,2),array(1,2))), (2,array(array(1,2),array(5))),
(3,array(array(6))) AS t(id,events)"
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]