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 cc9a1cd9 [SPARK-61639][CONNECT][RUST] Add native ALS recommendation
cc9a1cd9 is described below
commit cc9a1cd92d1452b41074f2afe196b4980d909d6b
Author: Ruifeng Zheng <[email protected]>
AuthorDate: Fri Nov 13 20:54:25 2026 +0800
[SPARK-61639][CONNECT][RUST] Add native ALS recommendation
### What changes were proposed in this pull request?
Add native Rust `ALS`/`ALSModel`, PyO3 bindings, and exports from
`pyspark.ml.connect.recommendation` and `pyspark.ml.connect`. Support all 18
estimator parameters, explicit/implicit feedback, nonnegative factors,
fit/transform, rank, user/item factor tables, and all four recommendation APIs.
Lazy factor/recommendation results retain their cached model and any models
used by the subset DataFrame.
### Why are the changes needed?
The native client has no recommendation estimator. This adds standard Spark
ML ALS over Connect, with reference-backed parameter encoding and numerical
tests against official PySpark 4.3.0. It is based on master after the
FPGrowth/PrefixSpan merge and preserves those algorithms' CI coverage.
### Does this PR introduce _any_ user-facing change?
Yes. Rust and Rust-backed Python users can train recommenders, inspect
factors, predict ratings and generate recommendations. Python mirrors the 17
official constructor keywords; `predictionCol` is set with `setPredictionCol`,
and `setNumBlocks` sets both block counts. Model transform setters include
cold-start handling. Factor/recommendation methods query the fitted server
model, matching official Connect behavior.
Fit, transform and subset recommendation arguments require Spark
DataFrames. Pandas inputs are rejected before conversion/RPC, and model
operations reject DataFrames from another session. Vendored
`pyspark.ml.recommendation` is unchanged. Native model persistence remains
separate work.
### How was this patch tested?
- Official PySpark 4.3.0 fixtures cover parameter protobufs and integer
widths, explicit and implicit/nonnegative feedback, held-out predictions, cold
starts, factors, all-user/all-item recommendations, and subset recommendations
including duplicate/unknown IDs.
- Full offline Python suite: 4245 passed, 8 skipped, 14 subtests passed.
Native live ML suite, including feature stages and frequent patterns: 169
passed. Official-reference ALS live tests: 10 passed, 1 skipped.
- Rust: 2 parameter golden tests, 3 live ALS tests, and 682 library tests
passed. All integration tests compile with and without `wasm-udf`; workspace
formatting, Clippy with warnings denied, and release extension build passed.
- The live tests cover schema/numerical parity, model setter snapshots,
invalid parameters and fractional IDs, session mismatches, and lazy model/input
lifetime.
- 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. Client and worker Python versions were aligned to
3.13.
- 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 #647 from zhengruifeng/add-native-als.
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 | 2 +
crates/pyspark-rs/src/ml/recommendation.rs | 379 +++++++
crates/spark-connect/src/ml.rs | 3 +
crates/spark-connect/src/ml/recommendation.rs | 449 ++++++++
crates/spark-connect/tests/als_golden.rs | 63 ++
crates/spark-connect/tests/common/als.rs | 43 +
crates/spark-connect/tests/e2e_als.rs | 202 ++++
docs/compatibility.md | 24 +
python/pyspark/ml/connect/__init__.py | 3 +
python/pyspark/ml/connect/recommendation.py | 6 +
python/tests/_als.py | 56 +
python/tests/test_als_e2e.py | 115 +++
python/tests/test_als_offline.py | 191 ++++
scripts/capture_als_golden.py | 144 +++
tests/golden/als.json | 1380 +++++++++++++++++++++++++
18 files changed, 3063 insertions(+), 2 deletions(-)
diff --git a/.github/workflows/build_python_connect.yml
b/.github/workflows/build_python_connect.yml
index 321f742e..79f86457 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
tests/test_frequent_patterns_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_e2 [...]
- 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 b505bc97..cb0a1281 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_frequent_patterns_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 tests/test_als_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 1d092722..e36e0f8a 100644
--- a/crates/pyspark-rs/src/lib.rs
+++ b/crates/pyspark-rs/src/lib.rs
@@ -269,6 +269,7 @@ fn _pyspark(_py: Python<'_>, m: &Bound<'_, PyModule>) ->
PyResult<()> {
m.add_class::<ml::PyKMeans>()?;
m.add_class::<ml::PyGaussianMixture>()?;
m.add_class::<ml::PyBisectingKMeans>()?;
+ ml::recommendation::register(m)?;
m.add_class::<ml::PyRegressionEvaluator>()?;
m.add_class::<ml::PyBinaryClassificationEvaluator>()?;
m.add_class::<ml::PyPipeline>()?;
diff --git a/crates/pyspark-rs/src/ml.rs b/crates/pyspark-rs/src/ml.rs
index 5b3de76f..f755fb58 100644
--- a/crates/pyspark-rs/src/ml.rs
+++ b/crates/pyspark-rs/src/ml.rs
@@ -31,6 +31,8 @@ use spark_connect::DataFrame;
pub(crate) mod feature;
pub(crate) mod fpm;
+pub(crate) mod recommendation;
+
use crate::dataframe::PyDataFrame;
use crate::errors::ResultExt;
use crate::interrupt::interruptible;
diff --git a/crates/pyspark-rs/src/ml/recommendation.rs
b/crates/pyspark-rs/src/ml/recommendation.rs
new file mode 100644
index 00000000..4df04a13
--- /dev/null
+++ b/crates/pyspark-rs/src/ml/recommendation.rs
@@ -0,0 +1,379 @@
+// SPDX-License-Identifier: Apache-2.0
+//! Native ALS fitting, prediction, factors and recommendations.
+use super::*;
+use spark_connect::ml::{ALSModel, ALS};
+use spark_connect_proto as proto;
+
+fn count_literal(value: &Bound<'_, PyAny>) ->
PyResult<proto::expression::Literal> {
+ let column = crate::functions::to_value_column(value)?;
+ match column.expression().node() {
+ spark_connect::expression::ExpressionNode::Literal(literal) => {
+ Ok(literal.to_literal_proto())
+ }
+ _ => Err(crate::column::raise_pyspark(
+ value.py(),
+ "PySparkTypeError",
+ "UNSUPPORTED_DATA_TYPE",
+ &[("data_type", &value.get_type().name()?.to_string())],
+ )),
+ }
+}
+
+#[pyclass(name = "ALS", module = "pyspark.ml.connect.recommendation")]
+pub struct PyALS {
+ inner: ALS,
+ unsendable: Vec<&'static str>,
+}
+impl Native for PyALS {
+ type Core = ALS;
+ 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 PyALS {
+ #[new]
+ #[pyo3(signature=(*args,**kwargs),text_signature="(*, rank=10, maxIter=10,
regParam=0.1, numUserBlocks=10, numItemBlocks=10, implicitPrefs=False,
alpha=1.0, userCol='user', itemCol='item', seed=None, ratingCol='rating',
nonnegative=False, checkpointInterval=10,
intermediateStorageLevel='MEMORY_AND_DISK',
finalStorageLevel='MEMORY_AND_DISK', coldStartStrategy='nan', blockSize=4096)")]
+ fn new(args: &Bound<'_, PyTuple>, kwargs: Option<&Bound<'_, PyDict>>) ->
PyResult<Self> {
+ let mut this = Self {
+ inner: ALS::new(),
+ unsendable: Vec::new(),
+ };
+ init_params(
+ &mut this,
+ "ALS",
+ &[],
+ &[
+ ("rank", Kind::Int),
+ ("maxIter", Kind::Int),
+ ("regParam", Kind::Float),
+ ("numUserBlocks", Kind::Int),
+ ("numItemBlocks", Kind::Int),
+ ("implicitPrefs", Kind::Bool),
+ ("alpha", Kind::Float),
+ ("userCol", Kind::Str),
+ ("itemCol", Kind::Str),
+ ("seed", Kind::Int),
+ ("ratingCol", Kind::Str),
+ ("nonnegative", Kind::Bool),
+ ("checkpointInterval", Kind::Int),
+ ("intermediateStorageLevel", Kind::Str),
+ ("finalStorageLevel", Kind::Str),
+ ("coldStartStrategy", Kind::Str),
+ ("blockSize", Kind::Int),
+ ],
+ args,
+ kwargs,
+ )?;
+ Ok(this)
+ }
+ #[pyo3(name = "setAlpha")]
+ fn set_alpha<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "alpha", Kind::Float, value)
+ }
+ #[pyo3(name = "setBlockSize")]
+ fn set_block_size<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "blockSize", 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 = "setColdStartStrategy")]
+ fn set_cold_start_strategy<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "coldStartStrategy", Kind::Str, value)
+ }
+ #[pyo3(name = "setFinalStorageLevel")]
+ fn set_final_storage_level<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "finalStorageLevel", Kind::Str, value)
+ }
+ #[pyo3(name = "setImplicitPrefs")]
+ fn set_implicit_prefs<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "implicitPrefs", Kind::Bool, value)
+ }
+ #[pyo3(name = "setIntermediateStorageLevel")]
+ fn set_intermediate_storage_level<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "intermediateStorageLevel", Kind::Str, value)
+ }
+ #[pyo3(name = "setItemCol")]
+ fn set_item_col<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "itemCol", 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 = "setNonnegative")]
+ fn set_nonnegative<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "nonnegative", Kind::Bool, value)
+ }
+ #[pyo3(name = "setNumItemBlocks")]
+ fn set_num_item_blocks<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "numItemBlocks", Kind::Int, value)
+ }
+ #[pyo3(name = "setNumUserBlocks")]
+ fn set_num_user_blocks<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "numUserBlocks", 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)
+ }
+ #[pyo3(name = "setRank")]
+ fn set_rank<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "rank", Kind::Int, value)
+ }
+ #[pyo3(name = "setRatingCol")]
+ fn set_rating_col<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "ratingCol", Kind::Str, value)
+ }
+ #[pyo3(name = "setRegParam")]
+ fn set_reg_param<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "regParam", Kind::Float, 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 = "setUserCol")]
+ fn set_user_col<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "userCol", Kind::Str, value)
+ }
+ #[pyo3(name = "setNumBlocks")]
+ fn set_num_blocks<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ let users = convert("numUserBlocks", Kind::Int, value)?;
+ let items = convert("numItemBlocks", Kind::Int, value)?;
+ {
+ let mut this = slf.try_borrow_mut()?;
+ apply(&mut *this, "numUserBlocks", users);
+ apply(&mut *this, "numItemBlocks", items);
+ }
+ Ok(slf)
+ }
+ fn fit(slf: &Bound<'_, Self>, dataset: &Bound<'_, PyAny>) ->
PyResult<PyALSModel> {
+ let input = dataset_of(dataset, "fit", "select")?;
+ let mut estimator = snapshot(slf)?;
+ let session = input.spark_session();
+ let inner = interruptible(slf.py(), &session, || {
+ estimator.fit(&input).map_err(Box::new)
+ })?;
+ Ok(PyALSModel {
+ inner,
+ unsendable: Vec::new(),
+ })
+ }
+}
+
+#[pyclass(name = "ALSModel", module = "pyspark.ml.connect.recommendation")]
+pub struct PyALSModel {
+ inner: ALSModel,
+ unsendable: Vec<&'static str>,
+}
+impl Native for PyALSModel {
+ type Core = ALSModel;
+ 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 PyALSModel {
+ #[pyo3(name = "setBlockSize")]
+ fn set_block_size<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "blockSize", Kind::Int, value)
+ }
+ #[pyo3(name = "setColdStartStrategy")]
+ fn set_cold_start_strategy<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "coldStartStrategy", Kind::Str, value)
+ }
+ #[pyo3(name = "setItemCol")]
+ fn set_item_col<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "itemCol", Kind::Str, value)
+ }
+ #[pyo3(name = "setPredictionCol")]
+ fn set_prediction_col<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "predictionCol", Kind::Str, value)
+ }
+ #[pyo3(name = "setUserCol")]
+ fn set_user_col<'py>(
+ slf: Bound<'py, Self>,
+ value: &Bound<'py, PyAny>,
+ ) -> PyResult<Bound<'py, Self>> {
+ set_param(slf, "userCol", 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]
+ fn rank(&self) -> i32 {
+ self.inner.rank()
+ }
+ #[getter]
+ #[pyo3(name = "userFactors")]
+ fn user_factors(&self) -> PyResult<PyDataFrame> {
+ Ok(PyDataFrame::new(self.inner.user_factors().to_pyerr()?))
+ }
+ #[getter]
+ #[pyo3(name = "itemFactors")]
+ fn item_factors(&self) -> PyResult<PyDataFrame> {
+ Ok(PyDataFrame::new(self.inner.item_factors().to_pyerr()?))
+ }
+ #[allow(non_snake_case)]
+ #[pyo3(name="recommendForAllUsers",signature=(numItems))]
+ fn recommend_for_all_users(
+ slf: &Bound<'_, Self>,
+ numItems: &Bound<'_, PyAny>,
+ ) -> PyResult<PyDataFrame> {
+ let count = count_literal(numItems)?;
+ let model = slf.try_borrow()?.inner.clone();
+ Ok(PyDataFrame::new(
+ model.recommend_with_literal(true, None, count).to_pyerr()?,
+ ))
+ }
+ #[allow(non_snake_case)]
+ #[pyo3(name="recommendForAllItems",signature=(numUsers))]
+ fn recommend_for_all_items(
+ slf: &Bound<'_, Self>,
+ numUsers: &Bound<'_, PyAny>,
+ ) -> PyResult<PyDataFrame> {
+ let count = count_literal(numUsers)?;
+ let model = slf.try_borrow()?.inner.clone();
+ Ok(PyDataFrame::new(
+ model
+ .recommend_with_literal(false, None, count)
+ .to_pyerr()?,
+ ))
+ }
+ #[allow(non_snake_case)]
+ #[pyo3(name="recommendForUserSubset",signature=(dataset, numItems))]
+ fn recommend_for_user_subset(
+ slf: &Bound<'_, Self>,
+ dataset: &Bound<'_, PyAny>,
+ numItems: &Bound<'_, PyAny>,
+ ) -> PyResult<PyDataFrame> {
+ let input = dataset_of(dataset, "recommendForUserSubset", "select")?;
+ let count = count_literal(numItems)?;
+ let model = slf.try_borrow()?.inner.clone();
+ Ok(PyDataFrame::new(
+ model
+ .recommend_with_literal(true, Some(&input), count)
+ .to_pyerr()?,
+ ))
+ }
+ #[allow(non_snake_case)]
+ #[pyo3(name="recommendForItemSubset",signature=(dataset, numUsers))]
+ fn recommend_for_item_subset(
+ slf: &Bound<'_, Self>,
+ dataset: &Bound<'_, PyAny>,
+ numUsers: &Bound<'_, PyAny>,
+ ) -> PyResult<PyDataFrame> {
+ let input = dataset_of(dataset, "recommendForItemSubset", "select")?;
+ let count = count_literal(numUsers)?;
+ let model = slf.try_borrow()?.inner.clone();
+ Ok(PyDataFrame::new(
+ model
+ .recommend_with_literal(false, Some(&input), count)
+ .to_pyerr()?,
+ ))
+ }
+}
+
+pub(crate) fn register(m: &Bound<'_, PyModule>) -> PyResult<()> {
+ m.add_class::<PyALS>()?;
+ m.add_class::<PyALSModel>()?;
+ Ok(())
+}
diff --git a/crates/spark-connect/src/ml.rs b/crates/spark-connect/src/ml.rs
index 4ad781a2..2907ee51 100644
--- a/crates/spark-connect/src/ml.rs
+++ b/crates/spark-connect/src/ml.rs
@@ -12,6 +12,9 @@ use std::collections::HashMap;
use std::sync::Arc;
use uuid::Uuid;
+mod recommendation;
+pub use recommendation::*;
+
mod feature;
pub use feature::*;
mod fpm;
diff --git a/crates/spark-connect/src/ml/recommendation.rs
b/crates/spark-connect/src/ml/recommendation.rs
new file mode 100644
index 00000000..5b24d4f9
--- /dev/null
+++ b/crates/spark-connect/src/ml/recommendation.rs
@@ -0,0 +1,449 @@
+// SPDX-License-Identifier: Apache-2.0
+//! Alternating least squares recommendation through Spark Connect.
+use super::*;
+
+#[derive(Debug, Clone)]
+pub struct ALS {
+ operator: MlOperator,
+ params: Params,
+}
+impl ALS {
+ pub fn new() -> Self {
+ Self {
+ operator: MlOperator::new(
+ "org.apache.spark.ml.recommendation.ALS",
+ OperatorType::Estimator,
+ ),
+ params: Params::new(),
+ }
+ }
+ /// Fit the typed ALS model, including factor tables and recommendation
methods.
+ pub fn fit(&mut self, df: &DataFrame) ->
spark_connect_core::error::Result<ALSModel> {
+ self.ensure_operator();
+ let info = fit_via_command(&self.operator, &self.params, df)?;
+ let mut params = self.params.clone();
+ params.params.retain(|name, _| {
+ [
+ "blockSize",
+ "coldStartStrategy",
+ "itemCol",
+ "predictionCol",
+ "userCol",
+ ]
+ .contains(&name.as_str())
+ });
+ Ok(ALSModel {
+ operator: MlOperator::with_uid(
+ "org.apache.spark.ml.recommendation.ALSModel",
+ info.uid.as_deref().unwrap_or(&self.operator.uid),
+ OperatorType::Model,
+ ),
+ rank: self.rank(),
+ params,
+ cached: CachedModel::from_info(&info, &df.session, "ALS")?,
+ })
+ }
+ /// Set both user and item partition counts.
+ pub fn set_num_blocks(self, value: i32) -> Self {
+ self.set_num_user_blocks(value).set_num_item_blocks(value)
+ }
+}
+impl Default for ALS {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+impl Estimator for ALS {
+ 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 fitted, session-owned ALS model. Lazy result tables keep its cache entry
alive.
+#[derive(Debug, Clone)]
+pub struct ALSModel {
+ operator: MlOperator,
+ params: Params,
+ cached: CachedModel,
+ rank: i32,
+}
+impl ALSModel {
+ /// The rank used by the successful fit.
+ pub fn rank(&self) -> i32 {
+ self.rank
+ }
+ fn fetch(
+ &self,
+ method: &str,
+ args: Vec<proto::fetch::method::Args>,
+ input: Option<&DataFrame>,
+ ) -> 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,
+ }],
+ })),
+ ..Default::default()
+ },
+ ))),
+ ..Default::default()
+ };
+ if let Some(df) = input {
+ Ok(DataFrame::new(
+ self.cached.0.session.clone(),
+ LogicalPlan::MlTransform {
+ ml_relation: relation,
+ input: df.plan.clone(),
+ owner: Some(RelationOwner(self.cached.0.clone())),
+ },
+ ))
+ } else {
+ DataFrame::from_relation(
+ self.cached.0.session.clone(),
+ relation,
+ Some(self.cached.0.clone()),
+ )
+ }
+ }
+ pub fn user_factors(&self) -> spark_connect_core::error::Result<DataFrame>
{
+ self.fetch("userFactors", Vec::new(), None)
+ }
+ pub fn item_factors(&self) -> spark_connect_core::error::Result<DataFrame>
{
+ self.fetch("itemFactors", Vec::new(), None)
+ }
+ /// Binding seam that preserves the literal type of Python
recommendation-count arguments.
+ #[doc(hidden)]
+ pub fn recommend_with_literal(
+ &self,
+ users: bool,
+ subset: Option<&DataFrame>,
+ count: proto::expression::Literal,
+ ) -> spark_connect_core::error::Result<DataFrame> {
+ use proto::fetch::method::args::ArgsType;
+ let mut args = Vec::new();
+ if let Some(df) = subset {
+ if df.session.session_id() != self.cached.0.session.session_id() {
+ return Err(spark_connect_core::error::SparkError::value_msg(
+ "A fitted ML model must recommend data from its fitting
session",
+ ));
+ }
+ args.push(proto::fetch::method::Args {
+ args_type: Some(ArgsType::Input(df.relation()?)),
+ });
+ }
+ args.push(proto::fetch::method::Args {
+ args_type: Some(ArgsType::Param(count)),
+ });
+ let method = match (users, subset.is_some()) {
+ (true, false) => "recommendForAllUsers",
+ (false, false) => "recommendForAllItems",
+ (true, true) => "recommendForUserSubset",
+ (false, true) => "recommendForItemSubset",
+ };
+ self.fetch(method, args, subset)
+ }
+ pub fn recommend_for_all_users(
+ &self,
+ num_items: i32,
+ ) -> spark_connect_core::error::Result<DataFrame> {
+ self.recommend_with_literal(
+ true,
+ None,
+ LiteralExpression::Integer(num_items).to_literal_proto(),
+ )
+ }
+ pub fn recommend_for_all_items(
+ &self,
+ num_users: i32,
+ ) -> spark_connect_core::error::Result<DataFrame> {
+ self.recommend_with_literal(
+ false,
+ None,
+ LiteralExpression::Integer(num_users).to_literal_proto(),
+ )
+ }
+ pub fn recommend_for_user_subset(
+ &self,
+ dataset: &DataFrame,
+ num_items: i32,
+ ) -> spark_connect_core::error::Result<DataFrame> {
+ self.recommend_with_literal(
+ true,
+ Some(dataset),
+ LiteralExpression::Integer(num_items).to_literal_proto(),
+ )
+ }
+ pub fn recommend_for_item_subset(
+ &self,
+ dataset: &DataFrame,
+ num_users: i32,
+ ) -> spark_connect_core::error::Result<DataFrame> {
+ self.recommend_with_literal(
+ false,
+ Some(dataset),
+ LiteralExpression::Integer(num_users).to_literal_proto(),
+ )
+ }
+}
+impl Transformer for ALSModel {
+ 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 ALSModel {
+ fn clone_box(&self) -> Box<dyn Model> {
+ Box::new(self.clone())
+ }
+}
+
+impl ALS {
+ /// Set `alpha`; Spark validates its value.
+ pub fn set_alpha(mut self, value: f64) -> Self {
+ self.params = self.params.set_param_double("alpha", value);
+ self
+ }
+ /// Read `alpha`, with Spark's default when defined.
+ pub fn alpha(&self) -> f64 {
+ self.params.double_or("alpha", 1.0)
+ }
+ /// Set `blockSize`; Spark validates its value.
+ pub fn set_block_size(mut self, value: i32) -> Self {
+ self.params = self.params.set_param_int32("blockSize", value);
+ self
+ }
+ /// Read `blockSize`, with Spark's default when defined.
+ pub fn block_size(&self) -> i32 {
+ self.params.int_or("blockSize", 4096)
+ }
+ /// Set `checkpointInterval`; Spark validates its value.
+ pub fn set_checkpoint_interval(mut self, value: i32) -> Self {
+ self.params = self.params.set_param_int32("checkpointInterval", value);
+ self
+ }
+ /// Read `checkpointInterval`, with Spark's default when defined.
+ pub fn checkpoint_interval(&self) -> i32 {
+ self.params.int_or("checkpointInterval", 10)
+ }
+ /// Set `coldStartStrategy`; Spark validates its value.
+ pub fn set_cold_start_strategy(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("coldStartStrategy", value);
+ self
+ }
+ /// Read `coldStartStrategy`, with Spark's default when defined.
+ pub fn cold_start_strategy(&self) -> &str {
+ self.params.string_or("coldStartStrategy", "nan")
+ }
+ /// Set `finalStorageLevel`; Spark validates its value.
+ pub fn set_final_storage_level(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("finalStorageLevel", value);
+ self
+ }
+ /// Read `finalStorageLevel`, with Spark's default when defined.
+ pub fn final_storage_level(&self) -> &str {
+ self.params
+ .string_or("finalStorageLevel", "MEMORY_AND_DISK")
+ }
+ /// Set `implicitPrefs`; Spark validates its value.
+ pub fn set_implicit_prefs(mut self, value: bool) -> Self {
+ self.params = self.params.set_param_bool("implicitPrefs", value);
+ self
+ }
+ /// Read `implicitPrefs`, with Spark's default when defined.
+ pub fn implicit_prefs(&self) -> bool {
+ self.params.bool_or("implicitPrefs", false)
+ }
+ /// Set `intermediateStorageLevel`; Spark validates its value.
+ pub fn set_intermediate_storage_level(mut self, value: &str) -> Self {
+ self.params = self
+ .params
+ .set_param_string("intermediateStorageLevel", value);
+ self
+ }
+ /// Read `intermediateStorageLevel`, with Spark's default when defined.
+ pub fn intermediate_storage_level(&self) -> &str {
+ self.params
+ .string_or("intermediateStorageLevel", "MEMORY_AND_DISK")
+ }
+ /// Set `itemCol`; Spark validates its value.
+ pub fn set_item_col(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("itemCol", value);
+ self
+ }
+ /// Read `itemCol`, with Spark's default when defined.
+ pub fn item_col(&self) -> &str {
+ self.params.string_or("itemCol", "item")
+ }
+ /// Set `maxIter`; Spark validates its value.
+ pub fn set_max_iter(mut self, value: i32) -> Self {
+ self.params = self.params.set_param_int32("maxIter", value);
+ self
+ }
+ /// Read `maxIter`, with Spark's default when defined.
+ pub fn max_iter(&self) -> i32 {
+ self.params.int_or("maxIter", 10)
+ }
+ /// Set `nonnegative`; Spark validates its value.
+ pub fn set_nonnegative(mut self, value: bool) -> Self {
+ self.params = self.params.set_param_bool("nonnegative", value);
+ self
+ }
+ /// Read `nonnegative`, with Spark's default when defined.
+ pub fn nonnegative(&self) -> bool {
+ self.params.bool_or("nonnegative", false)
+ }
+ /// Set `numItemBlocks`; Spark validates its value.
+ pub fn set_num_item_blocks(mut self, value: i32) -> Self {
+ self.params = self.params.set_param_int32("numItemBlocks", value);
+ self
+ }
+ /// Read `numItemBlocks`, with Spark's default when defined.
+ pub fn num_item_blocks(&self) -> i32 {
+ self.params.int_or("numItemBlocks", 10)
+ }
+ /// Set `numUserBlocks`; Spark validates its value.
+ pub fn set_num_user_blocks(mut self, value: i32) -> Self {
+ self.params = self.params.set_param_int32("numUserBlocks", value);
+ self
+ }
+ /// Read `numUserBlocks`, with Spark's default when defined.
+ pub fn num_user_blocks(&self) -> i32 {
+ self.params.int_or("numUserBlocks", 10)
+ }
+ /// Set `predictionCol`; Spark validates its value.
+ pub fn set_prediction_col(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("predictionCol", value);
+ self
+ }
+ /// Read `predictionCol`, with Spark's default when defined.
+ pub fn prediction_col(&self) -> &str {
+ self.params.string_or("predictionCol", "prediction")
+ }
+ /// Set `rank`; Spark validates its value.
+ pub fn set_rank(mut self, value: i32) -> Self {
+ self.params = self.params.set_param_int32("rank", value);
+ self
+ }
+ /// Read `rank`, with Spark's default when defined.
+ pub fn rank(&self) -> i32 {
+ self.params.int_or("rank", 10)
+ }
+ /// Set `ratingCol`; Spark validates its value.
+ pub fn set_rating_col(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("ratingCol", value);
+ self
+ }
+ /// Read `ratingCol`, with Spark's default when defined.
+ pub fn rating_col(&self) -> &str {
+ self.params.string_or("ratingCol", "rating")
+ }
+ /// Set `regParam`; Spark validates its value.
+ pub fn set_reg_param(mut self, value: f64) -> Self {
+ self.params = self.params.set_param_double("regParam", value);
+ self
+ }
+ /// Read `regParam`, with Spark's default when defined.
+ pub fn reg_param(&self) -> f64 {
+ self.params.double_or("regParam", 0.1)
+ }
+ /// Set `seed`; Spark validates its value.
+ pub fn set_seed(mut self, value: i64) -> Self {
+ self.params = self.params.set_param_int_narrow("seed", value);
+ self
+ }
+ /// Read `seed`, with Spark's default when defined.
+ pub fn seed(&self) -> Option<i64> {
+ self.params.long_opt("seed")
+ }
+ /// Set `userCol`; Spark validates its value.
+ pub fn set_user_col(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("userCol", value);
+ self
+ }
+ /// Read `userCol`, with Spark's default when defined.
+ pub fn user_col(&self) -> &str {
+ self.params.string_or("userCol", "user")
+ }
+}
+
+impl ALSModel {
+ /// Set `blockSize`; Spark validates its value.
+ pub fn set_block_size(mut self, value: i32) -> Self {
+ self.params = self.params.set_param_int32("blockSize", value);
+ self
+ }
+ /// Read `blockSize`, with Spark's default when defined.
+ pub fn block_size(&self) -> i32 {
+ self.params.int_or("blockSize", 4096)
+ }
+ /// Set `coldStartStrategy`; Spark validates its value.
+ pub fn set_cold_start_strategy(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("coldStartStrategy", value);
+ self
+ }
+ /// Read `coldStartStrategy`, with Spark's default when defined.
+ pub fn cold_start_strategy(&self) -> &str {
+ self.params.string_or("coldStartStrategy", "nan")
+ }
+ /// Set `itemCol`; Spark validates its value.
+ pub fn set_item_col(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("itemCol", value);
+ self
+ }
+ /// Read `itemCol`, with Spark's default when defined.
+ pub fn item_col(&self) -> &str {
+ self.params.string_or("itemCol", "item")
+ }
+ /// Set `predictionCol`; Spark validates its value.
+ pub fn set_prediction_col(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("predictionCol", value);
+ self
+ }
+ /// Read `predictionCol`, with Spark's default when defined.
+ pub fn prediction_col(&self) -> &str {
+ self.params.string_or("predictionCol", "prediction")
+ }
+ /// Set `userCol`; Spark validates its value.
+ pub fn set_user_col(mut self, value: &str) -> Self {
+ self.params = self.params.set_param_string("userCol", value);
+ self
+ }
+ /// Read `userCol`, with Spark's default when defined.
+ pub fn user_col(&self) -> &str {
+ self.params.string_or("userCol", "user")
+ }
+}
diff --git a/crates/spark-connect/tests/als_golden.rs
b/crates/spark-connect/tests/als_golden.rs
new file mode 100644
index 00000000..1f327b97
--- /dev/null
+++ b/crates/spark-connect/tests/als_golden.rs
@@ -0,0 +1,63 @@
+//! Check native ALS parameter encodings against official PySpark, including
seed widths.
+#[path = "common/als.rs"]
+mod als;
+
+use base64::{engine::general_purpose::STANDARD, Engine};
+use prost::Message;
+use spark_connect::ml::{Estimator, ALS};
+
+#[test]
+fn als_parameters_match_official_pyspark() {
+ for case in als::fixture()["params"].as_array().unwrap() {
+ // Explicit Python None is covered by the Python binding tests; typed
Rust setters
+ // take concrete values, and unset parameters retain the server
defaults.
+ if case["values"]
+ .as_object()
+ .unwrap()
+ .values()
+ .any(|v| v.is_null())
+ {
+ continue;
+ }
+ let bytes = STANDARD
+ .decode(case["params_b64"].as_str().unwrap())
+ .unwrap();
+ let expected =
spark_connect_proto::MlParams::decode(bytes.as_slice()).unwrap();
+ assert_eq!(
+ als::configured(&case["values"]).params().to_proto(),
+ expected
+ );
+ }
+}
+
+#[test]
+fn als_defaults_and_shared_block_setter() {
+ let estimator = ALS::default();
+ assert!(estimator.params().to_proto().params.is_empty());
+ let defaults = &als::fixture()["defaults"];
+ assert_eq!(estimator.rank(), defaults["rank"].as_i64().unwrap() as i32);
+ assert_eq!(
+ estimator.max_iter(),
+ defaults["maxIter"].as_i64().unwrap() as i32
+ );
+ assert_eq!(
+ estimator.reg_param(),
+ defaults["regParam"].as_f64().unwrap()
+ );
+ assert_eq!(estimator.user_col(), defaults["userCol"].as_str().unwrap());
+ assert_eq!(estimator.item_col(), defaults["itemCol"].as_str().unwrap());
+ assert_eq!(
+ estimator.rating_col(),
+ defaults["ratingCol"].as_str().unwrap()
+ );
+ assert_eq!(
+ estimator.cold_start_strategy(),
+ defaults["coldStartStrategy"].as_str().unwrap()
+ );
+ assert_eq!(estimator.prediction_col(), "prediction");
+ assert_eq!(estimator.seed(), None);
+ let estimator = estimator.set_num_blocks(3);
+ assert_eq!(estimator.num_user_blocks(), 3);
+ assert_eq!(estimator.num_item_blocks(), 3);
+ assert_eq!(estimator.params().to_proto().params.len(), 2);
+}
diff --git a/crates/spark-connect/tests/common/als.rs
b/crates/spark-connect/tests/common/als.rs
new file mode 100644
index 00000000..913ff1d9
--- /dev/null
+++ b/crates/spark-connect/tests/common/als.rs
@@ -0,0 +1,43 @@
+//! Shared inputs captured from official PySpark 4.3.0, used by ALS protocol
and live tests.
+use serde_json::Value as Json;
+use spark_connect::ml::ALS;
+
+pub fn fixture() -> Json {
+
serde_json::from_str(include_str!("../../../../tests/golden/als.json")).unwrap()
+}
+
+pub fn configured(values: &Json) -> ALS {
+ let mut estimator = ALS::new();
+ for (name, value) in values.as_object().unwrap() {
+ estimator = match name.as_str() {
+ "rank" =>
estimator.set_rank(value.as_i64().unwrap().try_into().unwrap()),
+ "maxIter" =>
estimator.set_max_iter(value.as_i64().unwrap().try_into().unwrap()),
+ "regParam" => estimator.set_reg_param(value.as_f64().unwrap()),
+ "numUserBlocks" => {
+
estimator.set_num_user_blocks(value.as_i64().unwrap().try_into().unwrap())
+ }
+ "numItemBlocks" => {
+
estimator.set_num_item_blocks(value.as_i64().unwrap().try_into().unwrap())
+ }
+ "implicitPrefs" =>
estimator.set_implicit_prefs(value.as_bool().unwrap()),
+ "alpha" => estimator.set_alpha(value.as_f64().unwrap()),
+ "userCol" => estimator.set_user_col(value.as_str().unwrap()),
+ "itemCol" => estimator.set_item_col(value.as_str().unwrap()),
+ "seed" => estimator.set_seed(value.as_i64().unwrap()),
+ "ratingCol" => estimator.set_rating_col(value.as_str().unwrap()),
+ "nonnegative" =>
estimator.set_nonnegative(value.as_bool().unwrap()),
+ "checkpointInterval" => {
+
estimator.set_checkpoint_interval(value.as_i64().unwrap().try_into().unwrap())
+ }
+ "intermediateStorageLevel" => {
+
estimator.set_intermediate_storage_level(value.as_str().unwrap())
+ }
+ "finalStorageLevel" =>
estimator.set_final_storage_level(value.as_str().unwrap()),
+ "coldStartStrategy" =>
estimator.set_cold_start_strategy(value.as_str().unwrap()),
+ "blockSize" =>
estimator.set_block_size(value.as_i64().unwrap().try_into().unwrap()),
+ "predictionCol" =>
estimator.set_prediction_col(value.as_str().unwrap()),
+ other => panic!("unexpected ALS parameter: {other}"),
+ };
+ }
+ estimator
+}
diff --git a/crates/spark-connect/tests/e2e_als.rs
b/crates/spark-connect/tests/e2e_als.rs
new file mode 100644
index 00000000..3b7cded1
--- /dev/null
+++ b/crates/spark-connect/tests/e2e_als.rs
@@ -0,0 +1,202 @@
+//! Reference-backed ALS fit, factor, recommendation and lazy ownership tests.
+#[path = "common/als.rs"]
+mod als;
+mod common;
+
+use common::live_session;
+use serde_json::{json, Value as Json};
+use spark_connect::column::col;
+use spark_connect::ml::{Estimator, StringIndexer, Transformer, ALS};
+use spark_connect::row::Value;
+use spark_connect::DataFrame;
+
+fn object(fields: &[String], values: &[Value]) -> Json {
+ fields
+ .iter()
+ .zip(values)
+ .map(|(name, value)| (name.clone(), normalize(value)))
+ .collect()
+}
+
+fn normalize(value: &Value) -> Json {
+ match value {
+ Value::Null => Json::Null,
+ Value::Bool(v) => json!(v),
+ Value::Byte(v) => json!(v),
+ Value::Short(v) => json!(v),
+ Value::Integer(v) => json!(v),
+ Value::Long(v) => json!(v),
+ Value::Float(v) if v.is_nan() => json!({"float": "nan"}),
+ Value::Double(v) if v.is_nan() => json!({"float": "nan"}),
+ Value::Float(v) => json!(v),
+ Value::Double(v) => json!(v),
+ Value::String(v) => json!(v),
+ Value::List(v) => v.iter().map(normalize).collect(),
+ Value::Struct(v) => object(v.fields(), v.values()),
+ other => panic!("unexpected ALS result value: {other:?}"),
+ }
+}
+
+fn assert_close(actual: &Json, expected: &Json) {
+ match (actual, expected) {
+ (Json::Object(a), Json::Object(e)) => {
+ assert_eq!(a.keys().collect::<Vec<_>>(),
e.keys().collect::<Vec<_>>());
+ for (key, value) in e {
+ assert_close(&a[key], value);
+ }
+ }
+ (Json::Array(a), Json::Array(e)) => {
+ assert_eq!(a.len(), e.len());
+ for (value, expected) in a.iter().zip(e) {
+ assert_close(value, expected);
+ }
+ }
+ (Json::Number(a), Json::Number(e)) if a.is_f64() || e.is_f64() => {
+ let (a, e) = (a.as_f64().unwrap(), e.as_f64().unwrap());
+ assert!(
+ (a - e).abs() <= 2e-5 + 2e-4 * e.abs(),
+ "expected {e}, got {a}"
+ );
+ }
+ _ => assert_eq!(actual, expected),
+ }
+}
+
+fn assert_result(df: DataFrame, expected: &Json) {
+ assert_eq!(df.schema().unwrap().json_value(), expected["schema"]);
+ let mut rows: Vec<Json> = df
+ .collect()
+ .unwrap()
+ .iter()
+ .map(|row| object(row.fields(), row.values()))
+ .collect();
+ rows.sort_by_key(|row| {
+ ["id", "u", "i"]
+ .iter()
+ .find_map(|key| row[*key].as_i64())
+ .unwrap()
+ });
+ assert_close(&json!(rows), &expected["rows"]);
+}
+
+#[test]
+fn als_explicit_and_implicit_results_match_official_and_keep_models_alive() {
+ let Some(spark) = live_session() else {
+ return;
+ };
+ let fixture = als::fixture();
+ let training = spark.sql(fixture["train"].as_str().unwrap()).unwrap();
+ let held = spark.sql(fixture["held"].as_str().unwrap()).unwrap();
+ let users = spark.sql(fixture["users"].as_str().unwrap()).unwrap();
+ let items = spark.sql(fixture["items"].as_str().unwrap()).unwrap();
+ for case in fixture["cases"].as_array().unwrap() {
+ let mut model =
als::configured(&case["values"]).fit(&training).unwrap();
+ assert_eq!(model.rank(), case["rank"].as_i64().unwrap() as i32);
+ let mut params: Vec<_> =
model.params().to_proto().params.into_keys().collect();
+ params.sort();
+ assert_eq!(
+ params,
+ [
+ "blockSize",
+ "coldStartStrategy",
+ "itemCol",
+ "predictionCol",
+ "userCol"
+ ]
+ );
+ let predictions = model.transform(&held).unwrap();
+ let results = [
+ ("predictions", predictions),
+ ("user_factors", model.user_factors().unwrap()),
+ ("item_factors", model.item_factors().unwrap()),
+ ("all_users", model.recommend_for_all_users(2).unwrap()),
+ ("all_items", model.recommend_for_all_items(2).unwrap()),
+ (
+ "user_subset",
+ model.recommend_for_user_subset(&users, 2).unwrap(),
+ ),
+ (
+ "item_subset",
+ model.recommend_for_item_subset(&items, 2).unwrap(),
+ ),
+ ];
+ model = model
+ .set_cold_start_strategy("drop")
+ .set_prediction_col("filtered");
+ let dropped = model.transform(&held).unwrap();
+ let other = spark.new_session();
+ let foreign = other.range(1).unwrap();
+ assert!(model.transform(&foreign).is_err());
+ assert!(model.recommend_for_user_subset(&foreign, 2).is_err());
+ assert!(model.recommend_for_item_subset(&foreign, 2).is_err());
+ other.stop().unwrap();
+ drop(model);
+ for (name, frame) in results {
+ assert_result(frame, &case[name]);
+ }
+ assert_result(dropped, &case["drop_predictions"]);
+ }
+ spark.stop().unwrap();
+}
+
+#[test]
+fn als_recommendations_retain_models_used_to_build_the_subset() {
+ let Some(spark) = live_session() else {
+ return;
+ };
+ let fixture = als::fixture();
+ let training = spark.sql(fixture["train"].as_str().unwrap()).unwrap();
+ let model = als::configured(&fixture["cases"][0]["values"])
+ .fit(&training)
+ .unwrap();
+ let labels = spark
+ .sql("SELECT * FROM VALUES ('a'), ('a'), ('b') AS t(label)")
+ .unwrap();
+ let mut indexer = StringIndexer::new()
+ .set_input_col("label")
+ .set_output_col("index")
+ .fit(&labels)
+ .unwrap();
+ let subset = indexer
+ .transform(&labels)
+ .unwrap()
+ .with_column("u", col("index").cast_str("int"))
+ .select([col("u")]);
+ let deferred = model.recommend_for_user_subset(&subset, 2).unwrap();
+ let expected = model
+ .recommend_for_user_subset(
+ &spark.sql("SELECT * FROM VALUES (0), (1) AS t(u)").unwrap(),
+ 2,
+ )
+ .unwrap();
+ let expected = json!({
+ "schema": expected.schema().unwrap().json_value(),
+ "rows":
expected.order_by(vec![col("u").asc().expression().clone()]).collect().unwrap().iter().map(|r|
object(r.fields(), r.values())).collect::<Vec<_>>()
+ });
+ drop(subset);
+ drop(indexer);
+ drop(model);
+ assert_result(deferred, &expected);
+ spark.stop().unwrap();
+}
+
+#[test]
+fn als_rejects_invalid_parameters_and_fractional_ids() {
+ let Some(spark) = live_session() else {
+ return;
+ };
+ let training = spark
+ .sql("SELECT * FROM VALUES (0, 0, 1.0D), (1, 1, 2.0D) AS t(user, item,
rating)")
+ .unwrap();
+ assert!(ALS::new().set_rank(0).fit(&training).is_err());
+ assert!(ALS::new().set_reg_param(-1.0).fit(&training).is_err());
+ assert!(ALS::new()
+ .set_cold_start_strategy("invalid")
+ .fit(&training)
+ .is_err());
+ let fractional = spark
+ .sql("SELECT 0.5D AS user, 0 AS item, 1.0D AS rating")
+ .unwrap();
+ assert!(ALS::new().fit(&fractional).is_err());
+ spark.stop().unwrap();
+}
diff --git a/docs/compatibility.md b/docs/compatibility.md
index 69c4e225..cbf44db3 100644
--- a/docs/compatibility.md
+++ b/docs/compatibility.md
@@ -888,3 +888,27 @@ Spark 4.3.0's Connect helper currently rejects `Long`
argument literals: PrefixS
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.
+
+## Native ALS recommendation
+
+`ml::ALS` / `ml::ALSModel` in Rust and `pyspark.ml.connect.recommendation.ALS`
/
+`ALSModel` in the Rust-backed Python package run Spark's standard ALS over
Connect.
+The estimator exposes all 18 parameters, including explicit/implicit feedback,
+nonnegative factors, regularization, block counts, storage levels and seed.
+Python mirrors the 17 official constructor keywords; use `setPredictionCol` for
+an alternate prediction column, and `setNumBlocks` to set both block counts.
+
+The fitted model supports transform, rank, user/item factor tables,
recommendations
+for all users/items, and recommendations for a subset of users/items. Rust uses
+`user_factors`, `item_factors`, and `recommend_for_*`; Python exposes
`userFactors`,
+`itemFactors`, and `recommendFor*`. Model setters control transform parameters,
+including `coldStartStrategy="drop"` to remove predictions for unknown IDs.
+Factor and recommendation relations access the fitted server model, matching
+PySpark Connect. Lazy results retain their cached model and any models
referenced
+by the subset DataFrame until evaluation completes.
+
+Fit, transform and subset recommendation inputs must be Spark DataFrames;
pandas
+DataFrames are rejected before conversion or RPC. Model operations must use the
+fit session. Official PySpark 4.3.0 fixtures cover explicit and implicit
ratings,
+predictions, cold starts, factors, and all four recommendation methods, with
live
+Rust and native Python tests. Model persistence is separate from these APIs.
diff --git a/python/pyspark/ml/connect/__init__.py
b/python/pyspark/ml/connect/__init__.py
index 2cb2c64f..7b520fd7 100644
--- a/python/pyspark/ml/connect/__init__.py
+++ b/python/pyspark/ml/connect/__init__.py
@@ -39,6 +39,7 @@ from pyspark.ml.connect.evaluation import (
BinaryClassificationEvaluator,
MulticlassClassificationEvaluator,
)
+from pyspark.ml.connect.recommendation import ALS, ALSModel
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
@@ -91,6 +92,8 @@ __all__ = [
"DecisionTreeRegressor",
"RandomForestRegressor",
"KMeans",
+ "ALS",
+ "ALSModel",
"LDA",
"PowerIterationClustering",
"GaussianMixture",
diff --git a/python/pyspark/ml/connect/recommendation.py
b/python/pyspark/ml/connect/recommendation.py
new file mode 100644
index 00000000..6c43fc67
--- /dev/null
+++ b/python/pyspark/ml/connect/recommendation.py
@@ -0,0 +1,6 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Native ALS recommendation through Spark Connect."""
+
+from pyspark._pyspark import ALS, ALSModel
+
+__all__ = ["ALS", "ALSModel"]
diff --git a/python/tests/_als.py b/python/tests/_als.py
new file mode 100644
index 00000000..8a08a7c4
--- /dev/null
+++ b/python/tests/_als.py
@@ -0,0 +1,56 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Shared ALS fixtures and numeric comparisons."""
+
+import json
+import math
+from pathlib import Path
+
+import pytest
+
+GOLDEN = json.loads((Path(__file__).parents[2] /
"tests/golden/als.json").read_text())
+
+
+def clean(value):
+ if hasattr(value, "asDict"):
+ return {k: clean(v) for k, v in value.asDict().items()}
+ if isinstance(value, (list, tuple)):
+ return [clean(v) for v in value]
+ return value
+
+
+def assert_values(actual, expected):
+ actual = clean(actual)
+ if isinstance(expected, dict):
+ if "float" in expected:
+ assert math.isnan(actual)
+ else:
+ assert set(actual) == set(expected)
+ for k, v in expected.items():
+ assert_values(actual[k], v)
+ elif 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=2e-4, abs=2e-5)
+ else:
+ assert actual == expected
+
+
+def assert_frame(frame, expected):
+ rows = sorted(
+ [clean(row) for row in frame.collect()],
+ key=lambda v: next(v[k] for k in ("id", "u", "i") if k in v),
+ )
+ assert_values(rows, expected["rows"])
+ assert frame.schema.jsonValue() == expected["schema"]
+
+
+def configured(cls, values, setters=False):
+ stage = (
+ cls() if setters else cls(**{k: v for k, v in values.items() if k in
GOLDEN["defaults"]})
+ )
+ for key, value in values.items():
+ if setters or key not in GOLDEN["defaults"]:
+ assert getattr(stage, "set" + key[0].upper() + key[1:])(value) is
stage
+ return stage
diff --git a/python/tests/test_als_e2e.py b/python/tests/test_als_e2e.py
new file mode 100644
index 00000000..05cd1f9f
--- /dev/null
+++ b/python/tests/test_als_e2e.py
@@ -0,0 +1,115 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Native ALS recommendation, with an explicit official PySpark reference
mode."""
+
+import gc
+import os
+
+import pytest
+from _als import GOLDEN, assert_frame, configured
+from pyspark.errors import PySparkException
+from pyspark.sql import SparkSession
+
+REFERENCE = os.environ.get("ALS_REFERENCE") == "1"
+
+
+def algorithm(name):
+ if REFERENCE:
+ from pyspark.ml import recommendation
+ else:
+ from pyspark import _pyspark
+ from pyspark.ml.connect import recommendation
+
+ assert getattr(recommendation, name) is getattr(_pyspark, name)
+ return getattr(recommendation, 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["cases"], ids=lambda c: c["name"])
[email protected]("setters", [False, True])
+def test_als_predictions_factors_and_recommendations_match_official(session,
case, setters):
+ stage = configured(algorithm("ALS"), case["values"], setters)
+ assert stage.setNumBlocks(1) is stage
+ model = stage.fit(session.sql(GOLDEN["train"]).coalesce(1))
+ assert isinstance(model, algorithm("ALSModel"))
+ assert model.rank == case["rank"]
+ tables = {
+ "predictions": model.transform(session.sql(GOLDEN["held"])),
+ "user_factors": model.userFactors,
+ "item_factors": model.itemFactors,
+ "all_users": model.recommendForAllUsers(2),
+ "all_items": model.recommendForAllItems(2),
+ "user_subset":
model.recommendForUserSubset(session.sql(GOLDEN["users"]), 2),
+ "item_subset":
model.recommendForItemSubset(session.sql(GOLDEN["items"]), 2),
+ }
+ assert model.setColdStartStrategy("drop") is model
+ assert model.setPredictionCol("filtered") is model
+ tables["drop_predictions"] = model.transform(session.sql(GOLDEN["held"]))
+ del stage, model
+ gc.collect()
+ for key, frame in tables.items():
+ assert_frame(frame, case[key])
+
+
[email protected](
+ "values",
+ [dict(rank=0), dict(regParam=-0.1), dict(numUserBlocks=0),
dict(coldStartStrategy="invalid")],
+)
+def test_als_invalid_parameters_are_rejected_by_spark(session, values):
+ params = dict(GOLDEN["cases"][0]["values"], **values)
+ with pytest.raises(PySparkException):
+ configured(algorithm("ALS"), params).fit(session.sql(GOLDEN["train"]))
+
+
+def test_als_rejects_fractional_ids(session):
+ values = GOLDEN["cases"][0]["values"]
+ with pytest.raises(PySparkException):
+ configured(algorithm("ALS"), values).fit(session.sql("SELECT 0.5D AS
u, 1 AS i, 3.0D AS r"))
+
+
+def test_als_retains_model_used_by_a_recommendation_subset(session):
+ from pyspark.sql import functions as F
+
+ if REFERENCE:
+ from pyspark.ml.feature import StringIndexer
+ else:
+ from pyspark.ml.connect.feature import StringIndexer
+ values = GOLDEN["cases"][0]["values"]
+ model = configured(algorithm("ALS"),
values).fit(session.sql(GOLDEN["train"]).coalesce(1))
+ data = session.sql("SELECT * FROM VALUES ('a'),('c') AS t(category)")
+ indexer = StringIndexer(inputCol="category", outputCol="u",
stringOrderType="alphabetAsc").fit(
+ session.sql("SELECT * FROM VALUES ('a'),('b'),('c') AS t(category)")
+ )
+ subset = indexer.transform(data).select(F.col("u").cast("int").alias("u"))
+ result = model.recommendForUserSubset(subset, 2)
+ if not REFERENCE:
+ del subset, indexer, model
+ gc.collect()
+ assert_frame(result, GOLDEN["cases"][0]["user_subset"])
+
+
+def test_native_als_rejects_other_sessions(session):
+ if REFERENCE:
+ pytest.skip("Native fitted-session ownership contract")
+ model = configured(algorithm("ALS"), GOLDEN["cases"][0]["values"]).fit(
+ session.sql(GOLDEN["train"]).coalesce(1)
+ )
+ other = session.newSession()
+ try:
+ for operation in [
+ lambda: model.transform(other.sql(GOLDEN["held"])),
+ lambda: model.recommendForUserSubset(other.sql(GOLDEN["users"]),
2),
+ lambda: model.recommendForItemSubset(other.sql(GOLDEN["items"]),
2),
+ ]:
+ with pytest.raises(ValueError, match="fitting session"):
+ operation()
+ finally:
+ other.stop()
diff --git a/python/tests/test_als_offline.py b/python/tests/test_als_offline.py
new file mode 100644
index 00000000..085bb834
--- /dev/null
+++ b/python/tests/test_als_offline.py
@@ -0,0 +1,191 @@
+# SPDX-License-Identifier: Apache-2.0
+"""Native ALS parameter, model-relation and dataset-contract checks."""
+
+import base64
+import inspect
+
+import pytest
+from _als import GOLDEN, configured
+from _mock_connect_server import mock_connect_session
+from pyspark import _pyspark
+from pyspark.ml.connect import recommendation
+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
+
+MODEL_PARAMS = {"blockSize", "coldStartStrategy", "itemCol", "predictionCol",
"userCol"}
+
+
[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()
+
+
+def fitted(spark, service, values=None):
+ service.execute_payload = _operator_info("als-model")
+ return configured(recommendation.ALS, values or
GOLDEN["cases"][0]["values"]).fit(
+ spark.range(1)
+ )
+
+
+def test_native_exports_and_constructor_signature():
+ import pyspark.ml.connect as connect
+
+ assert recommendation.ALS is connect.ALS is _pyspark.ALS
+ assert recommendation.ALSModel is connect.ALSModel is _pyspark.ALSModel
+ params = inspect.signature(recommendation.ALS).parameters
+ assert list(params) == list(GOLDEN["defaults"])
+ for key, value in GOLDEN["defaults"].items():
+ assert params[key].default == value
+ assert params[key].kind == inspect.Parameter.KEYWORD_ONLY
+ with pytest.raises(TypeError, match="keyword arguments"):
+ recommendation.ALS(2)
+ with pytest.raises(TypeError, match="unexpected keyword"):
+ recommendation.ALS(predictionCol="score")
+
+
[email protected]("case", GOLDEN["params"])
[email protected]("setters", [False, True])
+def
test_als_fit_parameters_and_filtered_model_transform_match_reference(session,
case, setters):
+ spark, service = session
+ stage = configured(recommendation.ALS, case["values"], setters)
+ service.execute_payload = _operator_info("als-model")
+ sent = len(service.execute_requests)
+ model = stage.fit(spark.range(1))
+ expected = pb2.MlParams.FromString(base64.b64decode(case["params_b64"]))
+ fit = _commands_but_deletes(service, sent)[0].ml_command.fit
+ assert fit.estimator.name == "org.apache.spark.ml.recommendation.ALS"
+ assert fit.params == expected
+ assert isinstance(model, recommendation.ALSModel)
+ relation = _relation(model.transform(spark.range(1))).ml_relation.transform
+ assert relation.obj_ref.id == "als-model"
+ assert dict(relation.params.params) == {
+ k: v for k, v in expected.params.items() if k in MODEL_PARAMS
+ }
+
+
+def test_num_blocks_sets_both_partition_parameters(session):
+ spark, service = session
+ stage = recommendation.ALS()
+ assert stage.setNumBlocks(3) is stage
+ service.execute_payload = _operator_info("blocks-model")
+ sent = len(service.execute_requests)
+ stage.fit(spark.range(1))
+ params = _commands_but_deletes(service,
sent)[0].ml_command.fit.params.params
+ assert dict(params) == {
+ "numUserBlocks": pb2.Expression.Literal(integer=3),
+ "numItemBlocks": pb2.Expression.Literal(integer=3),
+ }
+
+
[email protected]("case", GOLDEN["fetches"])
+def test_recommendation_count_literals_match_reference(session, case):
+ spark, service = session
+ model = fitted(spark, service)
+ sent = _requests_but_deletes(service)
+ fetch =
_relation(model.recommendForAllUsers(numItems=case["count"])).ml_relation.fetch
+ assert fetch.obj_ref.id == "als-model"
+ assert fetch.methods[0].method == case["method"]
+ assert fetch.methods[0].args[0].param.SerializeToString() ==
base64.b64decode(case["arg_b64"])
+ assert _requests_but_deletes(service) == sent
+
+
+def test_factor_properties_rank_and_recommendation_methods_are_lazy(session):
+ spark, service = session
+ model = fitted(spark, service)
+ frame = spark.range(1)
+ sent = _requests_but_deletes(service)
+ assert model.rank == 2
+ for attribute in ["userFactors", "itemFactors"]:
+ fetch = _relation(getattr(model, attribute)).ml_relation.fetch
+ assert fetch.obj_ref.id == "als-model"
+ assert fetch.methods[0].method == attribute
+ assert not fetch.methods[0].args
+ for name, kwarg, subset in [
+ ("recommendForAllUsers", "numItems", False),
+ ("recommendForAllItems", "numUsers", False),
+ ("recommendForUserSubset", "numItems", True),
+ ("recommendForItemSubset", "numUsers", True),
+ ]:
+ kwargs = {kwarg: 2}
+ if subset:
+ kwargs["dataset"] = frame
+ fetch = _relation(getattr(model, name)(**kwargs)).ml_relation.fetch
+ assert fetch.methods[0].method == name
+ assert fetch.obj_ref.id == "als-model"
+ assert fetch.methods[0].args[-1].param ==
pb2.Expression.Literal(integer=2)
+ if subset:
+ assert fetch.methods[0].args[0].input == _relation(frame)
+ assert _requests_but_deletes(service) == sent
+
+
[email protected]("param", list(GOLDEN["defaults"]) + ["predictionCol"])
+def test_als_setters_validate_types(param):
+ stage = recommendation.ALS()
+ with pytest.raises(TypeError, match="Invalid param value"):
+ getattr(stage, "set" + param[0].upper() + param[1:])(object())
+
+
+def
test_pandas_is_rejected_before_requests_in_fit_transform_and_subsets(session):
+ import pandas as pd
+
+ spark, service = session
+ model = fitted(spark, service)
+ operations = [
+ recommendation.ALS(rank=2**70).fit,
+ model.transform,
+ lambda x: model.recommendForUserSubset(x, object()),
+ lambda x: model.recommendForItemSubset(x, object()),
+ ]
+ for operation in operations:
+ for pdf in [pd.DataFrame(), pd.DataFrame({"u": [0]})]:
+ sent = _requests_but_deletes(service)
+ with pytest.raises(TypeError, match="requires a Spark DataFrame"):
+ operation(pdf)
+ assert _requests_but_deletes(service) == sent
+
+
+def test_unsendable_recommendation_counts_fail_before_requests(session):
+ from pyspark.errors import PySparkTypeError, PySparkValueError
+
+ spark, service = session
+ model = fitted(spark, service)
+ for value, error in [
+ (2**70, PySparkValueError),
+ ([], PySparkTypeError),
+ (object(), PySparkTypeError),
+ ]:
+ sent = _requests_but_deletes(service)
+ with pytest.raises(error):
+ model.recommendForAllUsers(value)
+ assert _requests_but_deletes(service) == sent
+
+
+def test_model_setters_snapshot_transform_parameters(session):
+ spark, service = session
+ model = fitted(spark, service)
+ before = model.transform(spark.range(1))
+ for name, value in [
+ ("setUserCol", "user"),
+ ("setItemCol", "item"),
+ ("setPredictionCol", "p"),
+ ("setColdStartStrategy", "drop"),
+ ("setBlockSize", 16),
+ ]:
+ assert getattr(model, name)(value) is model
+ after =
_relation(model.transform(spark.range(1))).ml_relation.transform.params.params
+ assert after["userCol"].string == "user" and after["itemCol"].string ==
"item"
+ assert after["predictionCol"].string == "p" and
after["coldStartStrategy"].string == "drop"
+ assert after["blockSize"].integer == 16
+ assert
_relation(before).ml_relation.transform.params.params["predictionCol"].string
== "score"
diff --git a/scripts/capture_als_golden.py b/scripts/capture_als_golden.py
new file mode 100644
index 00000000..05dffd60
--- /dev/null
+++ b/scripts/capture_als_golden.py
@@ -0,0 +1,144 @@
+#!/usr/bin/env python3
+"""Capture ALS fixtures with official PySpark 4.3.0 and a Spark Connect
server."""
+
+import argparse
+import base64
+import inspect
+import json
+import math
+from pathlib import Path
+
+import pyspark
+from pyspark.ml.connect.serialize import serialize_ml_params
+from pyspark.ml.recommendation import ALS
+from pyspark.sql import SparkSession
+
+TRAIN = "SELECT * FROM VALUES
(0,0,5.0D),(0,1,1.0D),(0,2,2.0D),(1,0,1.0D),(1,1,5.0D),(1,3,3.0D),(2,0,3.0D),(2,2,5.0D),(2,3,1.0D),(3,1,2.0D),(3,2,1.0D),(3,3,5.0D)
AS t(u,i,r)"
+HELD = (
+ "SELECT * FROM VALUES
(0,0,3),(1,1,2),(2,2,1),(3,3,0),(4,99,0),(5,0,99),(6,99,99) AS t(id,u,i)"
+)
+USERS = "SELECT * FROM VALUES (0),(0),(2),(99) AS t(u)"
+ITEMS = "SELECT * FROM VALUES (1),(3),(3),(99) AS t(i)"
+
+
+def clean(value):
+ if hasattr(value, "asDict"):
+ return {k: clean(v) for k, v in value.asDict().items()}
+ if isinstance(value, (list, tuple)):
+ return [clean(v) for v in value]
+ if isinstance(value, float) and not math.isfinite(value):
+ return {"float": str(value)}
+ return value
+
+
+def result(frame):
+ return {
+ "schema": frame.schema.jsonValue(),
+ "rows": sorted(
+ [clean(row) for row in frame.collect()],
+ key=lambda v: next(v[k] for k in ("id", "u", "i") if k in v),
+ ),
+ }
+
+
+def encoded(message):
+ return
base64.b64encode(message.SerializeToString(deterministic=True)).decode()
+
+
+def configured(values):
+ defaults = inspect.signature(ALS).parameters
+ estimator = ALS(**{k: v for k, v in values.items() if k in defaults})
+ for key, value in values.items():
+ if key not in defaults:
+ getattr(estimator, "set" + key[0].upper() + key[1:])(value)
+ return estimator
+
+
+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/als.json"))
+ args = parser.parse_args()
+ assert pyspark.__version__ == "4.3.0"
+ spark = SparkSession.builder.remote(args.remote).getOrCreate()
+ base = dict(
+ rank=2,
+ maxIter=8,
+ regParam=0.1,
+ numUserBlocks=1,
+ numItemBlocks=1,
+ implicitPrefs=False,
+ alpha=1.0,
+ userCol="u",
+ itemCol="i",
+ seed=42,
+ ratingCol="r",
+ nonnegative=False,
+ checkpointInterval=-1,
+ intermediateStorageLevel="MEMORY_AND_DISK",
+ finalStorageLevel="MEMORY_AND_DISK",
+ coldStartStrategy="nan",
+ blockSize=2,
+ predictionCol="score",
+ )
+ output = {
+ "spark_version": pyspark.__version__,
+ "train": TRAIN,
+ "held": HELD,
+ "users": USERS,
+ "items": ITEMS,
+ "defaults": {k: v.default for k, v in
inspect.signature(ALS).parameters.items()},
+ "params": [],
+ "cases": [],
+ "fetches": [],
+ }
+ try:
+ variants = [{}, base, {k: None for k in base}] + [
+ dict(base, seed=s) for s in [2**31 - 1, 2**31, 2**63 - 1, -(2**63)]
+ ]
+ for values in variants:
+ stage = configured(values)
+ output["params"].append(
+ {"values": values, "params_b64":
encoded(serialize_ml_params(stage, spark.client))}
+ )
+ for name, values in [
+ ("explicit", base),
+ ("implicit-nonnegative", dict(base, implicitPrefs=True,
nonnegative=True, alpha=2.0)),
+ ]:
+ model = configured(values).fit(spark.sql(TRAIN).coalesce(1))
+ case = {"name": name, "values": values, "rank": model.rank}
+ tables = {
+ "predictions": model.transform(spark.sql(HELD)),
+ "user_factors": model.userFactors,
+ "item_factors": model.itemFactors,
+ "all_users": model.recommendForAllUsers(2),
+ "all_items": model.recommendForAllItems(2),
+ "user_subset": model.recommendForUserSubset(spark.sql(USERS),
2),
+ "item_subset": model.recommendForItemSubset(spark.sql(ITEMS),
2),
+ }
+ for key, frame in tables.items():
+ case[key] = result(frame)
+ if name == "explicit":
+ for count in [2, 2**31, None, True, 2.0, "2"]:
+ frame = model.recommendForAllUsers(count)
+ fetch = frame._plan.plan(spark.client).ml_relation.fetch
+ output["fetches"].append(
+ {
+ "count": count,
+ "method": fetch.methods[-1].method,
+ "arg_b64":
encoded(fetch.methods[-1].args[0].param),
+ }
+ )
+ model.setColdStartStrategy("drop").setPredictionCol("filtered")
+ case["drop_predictions"] = result(model.transform(spark.sql(HELD)))
+ output["cases"].append(case)
+ args.out.write_text(json.dumps(output, indent=2, allow_nan=False) +
"\n")
+ print(
+ "Captured explicit/implicit ALS predictions, factors,
recommendations and parameter literals."
+ )
+ finally:
+ spark.stop()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/golden/als.json b/tests/golden/als.json
new file mode 100644
index 00000000..d766cf1c
--- /dev/null
+++ b/tests/golden/als.json
@@ -0,0 +1,1380 @@
+{
+ "spark_version": "4.3.0",
+ "train": "SELECT * FROM VALUES
(0,0,5.0D),(0,1,1.0D),(0,2,2.0D),(1,0,1.0D),(1,1,5.0D),(1,3,3.0D),(2,0,3.0D),(2,2,5.0D),(2,3,1.0D),(3,1,2.0D),(3,2,1.0D),(3,3,5.0D)
AS t(u,i,r)",
+ "held": "SELECT * FROM VALUES
(0,0,3),(1,1,2),(2,2,1),(3,3,0),(4,99,0),(5,0,99),(6,99,99) AS t(id,u,i)",
+ "users": "SELECT * FROM VALUES (0),(0),(2),(99) AS t(u)",
+ "items": "SELECT * FROM VALUES (1),(3),(3),(99) AS t(i)",
+ "defaults": {
+ "rank": 10,
+ "maxIter": 10,
+ "regParam": 0.1,
+ "numUserBlocks": 10,
+ "numItemBlocks": 10,
+ "implicitPrefs": false,
+ "alpha": 1.0,
+ "userCol": "user",
+ "itemCol": "item",
+ "seed": null,
+ "ratingCol": "rating",
+ "nonnegative": false,
+ "checkpointInterval": 10,
+ "intermediateStorageLevel": "MEMORY_AND_DISK",
+ "finalStorageLevel": "MEMORY_AND_DISK",
+ "coldStartStrategy": "nan",
+ "blockSize": 4096
+ },
+ "params": [
+ {
+ "values": {},
+ "params_b64": ""
+ },
+ {
+ "values": {
+ "rank": 2,
+ "maxIter": 8,
+ "regParam": 0.1,
+ "numUserBlocks": 1,
+ "numItemBlocks": 1,
+ "implicitPrefs": false,
+ "alpha": 1.0,
+ "userCol": "u",
+ "itemCol": "i",
+ "seed": 42,
+ "ratingCol": "r",
+ "nonnegative": false,
+ "checkpointInterval": -1,
+ "intermediateStorageLevel": "MEMORY_AND_DISK",
+ "finalStorageLevel": "MEMORY_AND_DISK",
+ "coldStartStrategy": "nan",
+ "blockSize": 2,
+ "predictionCol": "score"
+ },
+ "params_b64":
"ChIKBWFscGhhEglZAAAAAAAA8D8KDwoJYmxvY2tTaXplEgIwAgohChJjaGVja3BvaW50SW50ZXJ2YWwSCzD///////////8BChoKEWNvbGRTdGFydFN0cmF0ZWd5EgVqA25hbgomChFmaW5hbFN0b3JhZ2VMZXZlbBIRag9NRU1PUllfQU5EX0RJU0sKEwoNaW1wbGljaXRQcmVmcxICGAAKLQoYaW50ZXJtZWRpYXRlU3RvcmFnZUxldmVsEhFqD01FTU9SWV9BTkRfRElTSwoOCgdpdGVtQ29sEgNqAWkKDQoHbWF4SXRlchICMAgKEQoLbm9ubmVnYXRpdmUSAhgAChMKDW51bUl0ZW1CbG9ja3MSAjABChMKDW51bVVzZXJCbG9ja3MSAjABChgKDXByZWRpY3Rpb25Db2wSB2oFc2NvcmUKCgoEcmFuaxICMAIKEAoJcmF0aW5nQ29sEgN
[...]
+ },
+ {
+ "values": {
+ "rank": null,
+ "maxIter": null,
+ "regParam": null,
+ "numUserBlocks": null,
+ "numItemBlocks": null,
+ "implicitPrefs": null,
+ "alpha": null,
+ "userCol": null,
+ "itemCol": null,
+ "seed": null,
+ "ratingCol": null,
+ "nonnegative": null,
+ "checkpointInterval": null,
+ "intermediateStorageLevel": null,
+ "finalStorageLevel": null,
+ "coldStartStrategy": null,
+ "blockSize": null,
+ "predictionCol": null
+ },
+ "params_b64":
"Cg0KBWFscGhhEgQKAgoAChEKCWJsb2NrU2l6ZRIECgIKAAoaChJjaGVja3BvaW50SW50ZXJ2YWwSBAoCCgAKGQoRY29sZFN0YXJ0U3RyYXRlZ3kSBAoCCgAKGQoRZmluYWxTdG9yYWdlTGV2ZWwSBAoCCgAKFQoNaW1wbGljaXRQcmVmcxIECgIKAAogChhpbnRlcm1lZGlhdGVTdG9yYWdlTGV2ZWwSBAoCCgAKDwoHaXRlbUNvbBIECgIKAAoPCgdtYXhJdGVyEgQKAgoAChMKC25vbm5lZ2F0aXZlEgQKAgoAChUKDW51bUl0ZW1CbG9ja3MSBAoCCgAKFQoNbnVtVXNlckJsb2NrcxIECgIKAAoVCg1wcmVkaWN0aW9uQ29sEgQKAgoACgwKBHJhbmsSBAoCCgAKEQoJcmF0aW5nQ29sEgQKAgoAChAKCHJlZ1BhcmFtEgQKAgoACgwKBHN
[...]
+ },
+ {
+ "values": {
+ "rank": 2,
+ "maxIter": 8,
+ "regParam": 0.1,
+ "numUserBlocks": 1,
+ "numItemBlocks": 1,
+ "implicitPrefs": false,
+ "alpha": 1.0,
+ "userCol": "u",
+ "itemCol": "i",
+ "seed": 2147483647,
+ "ratingCol": "r",
+ "nonnegative": false,
+ "checkpointInterval": -1,
+ "intermediateStorageLevel": "MEMORY_AND_DISK",
+ "finalStorageLevel": "MEMORY_AND_DISK",
+ "coldStartStrategy": "nan",
+ "blockSize": 2,
+ "predictionCol": "score"
+ },
+ "params_b64":
"ChIKBWFscGhhEglZAAAAAAAA8D8KDwoJYmxvY2tTaXplEgIwAgohChJjaGVja3BvaW50SW50ZXJ2YWwSCzD///////////8BChoKEWNvbGRTdGFydFN0cmF0ZWd5EgVqA25hbgomChFmaW5hbFN0b3JhZ2VMZXZlbBIRag9NRU1PUllfQU5EX0RJU0sKEwoNaW1wbGljaXRQcmVmcxICGAAKLQoYaW50ZXJtZWRpYXRlU3RvcmFnZUxldmVsEhFqD01FTU9SWV9BTkRfRElTSwoOCgdpdGVtQ29sEgNqAWkKDQoHbWF4SXRlchICMAgKEQoLbm9ubmVnYXRpdmUSAhgAChMKDW51bUl0ZW1CbG9ja3MSAjABChMKDW51bVVzZXJCbG9ja3MSAjABChgKDXByZWRpY3Rpb25Db2wSB2oFc2NvcmUKCgoEcmFuaxICMAIKEAoJcmF0aW5nQ29sEgN
[...]
+ },
+ {
+ "values": {
+ "rank": 2,
+ "maxIter": 8,
+ "regParam": 0.1,
+ "numUserBlocks": 1,
+ "numItemBlocks": 1,
+ "implicitPrefs": false,
+ "alpha": 1.0,
+ "userCol": "u",
+ "itemCol": "i",
+ "seed": 2147483648,
+ "ratingCol": "r",
+ "nonnegative": false,
+ "checkpointInterval": -1,
+ "intermediateStorageLevel": "MEMORY_AND_DISK",
+ "finalStorageLevel": "MEMORY_AND_DISK",
+ "coldStartStrategy": "nan",
+ "blockSize": 2,
+ "predictionCol": "score"
+ },
+ "params_b64":
"ChIKBWFscGhhEglZAAAAAAAA8D8KDwoJYmxvY2tTaXplEgIwAgohChJjaGVja3BvaW50SW50ZXJ2YWwSCzD///////////8BChoKEWNvbGRTdGFydFN0cmF0ZWd5EgVqA25hbgomChFmaW5hbFN0b3JhZ2VMZXZlbBIRag9NRU1PUllfQU5EX0RJU0sKEwoNaW1wbGljaXRQcmVmcxICGAAKLQoYaW50ZXJtZWRpYXRlU3RvcmFnZUxldmVsEhFqD01FTU9SWV9BTkRfRElTSwoOCgdpdGVtQ29sEgNqAWkKDQoHbWF4SXRlchICMAgKEQoLbm9ubmVnYXRpdmUSAhgAChMKDW51bUl0ZW1CbG9ja3MSAjABChMKDW51bVVzZXJCbG9ja3MSAjABChgKDXByZWRpY3Rpb25Db2wSB2oFc2NvcmUKCgoEcmFuaxICMAIKEAoJcmF0aW5nQ29sEgN
[...]
+ },
+ {
+ "values": {
+ "rank": 2,
+ "maxIter": 8,
+ "regParam": 0.1,
+ "numUserBlocks": 1,
+ "numItemBlocks": 1,
+ "implicitPrefs": false,
+ "alpha": 1.0,
+ "userCol": "u",
+ "itemCol": "i",
+ "seed": 9223372036854775807,
+ "ratingCol": "r",
+ "nonnegative": false,
+ "checkpointInterval": -1,
+ "intermediateStorageLevel": "MEMORY_AND_DISK",
+ "finalStorageLevel": "MEMORY_AND_DISK",
+ "coldStartStrategy": "nan",
+ "blockSize": 2,
+ "predictionCol": "score"
+ },
+ "params_b64":
"ChIKBWFscGhhEglZAAAAAAAA8D8KDwoJYmxvY2tTaXplEgIwAgohChJjaGVja3BvaW50SW50ZXJ2YWwSCzD///////////8BChoKEWNvbGRTdGFydFN0cmF0ZWd5EgVqA25hbgomChFmaW5hbFN0b3JhZ2VMZXZlbBIRag9NRU1PUllfQU5EX0RJU0sKEwoNaW1wbGljaXRQcmVmcxICGAAKLQoYaW50ZXJtZWRpYXRlU3RvcmFnZUxldmVsEhFqD01FTU9SWV9BTkRfRElTSwoOCgdpdGVtQ29sEgNqAWkKDQoHbWF4SXRlchICMAgKEQoLbm9ubmVnYXRpdmUSAhgAChMKDW51bUl0ZW1CbG9ja3MSAjABChMKDW51bVVzZXJCbG9ja3MSAjABChgKDXByZWRpY3Rpb25Db2wSB2oFc2NvcmUKCgoEcmFuaxICMAIKEAoJcmF0aW5nQ29sEgN
[...]
+ },
+ {
+ "values": {
+ "rank": 2,
+ "maxIter": 8,
+ "regParam": 0.1,
+ "numUserBlocks": 1,
+ "numItemBlocks": 1,
+ "implicitPrefs": false,
+ "alpha": 1.0,
+ "userCol": "u",
+ "itemCol": "i",
+ "seed": -9223372036854775808,
+ "ratingCol": "r",
+ "nonnegative": false,
+ "checkpointInterval": -1,
+ "intermediateStorageLevel": "MEMORY_AND_DISK",
+ "finalStorageLevel": "MEMORY_AND_DISK",
+ "coldStartStrategy": "nan",
+ "blockSize": 2,
+ "predictionCol": "score"
+ },
+ "params_b64":
"ChIKBWFscGhhEglZAAAAAAAA8D8KDwoJYmxvY2tTaXplEgIwAgohChJjaGVja3BvaW50SW50ZXJ2YWwSCzD///////////8BChoKEWNvbGRTdGFydFN0cmF0ZWd5EgVqA25hbgomChFmaW5hbFN0b3JhZ2VMZXZlbBIRag9NRU1PUllfQU5EX0RJU0sKEwoNaW1wbGljaXRQcmVmcxICGAAKLQoYaW50ZXJtZWRpYXRlU3RvcmFnZUxldmVsEhFqD01FTU9SWV9BTkRfRElTSwoOCgdpdGVtQ29sEgNqAWkKDQoHbWF4SXRlchICMAgKEQoLbm9ubmVnYXRpdmUSAhgAChMKDW51bUl0ZW1CbG9ja3MSAjABChMKDW51bVVzZXJCbG9ja3MSAjABChgKDXByZWRpY3Rpb25Db2wSB2oFc2NvcmUKCgoEcmFuaxICMAIKEAoJcmF0aW5nQ29sEgN
[...]
+ }
+ ],
+ "cases": [
+ {
+ "name": "explicit",
+ "values": {
+ "rank": 2,
+ "maxIter": 8,
+ "regParam": 0.1,
+ "numUserBlocks": 1,
+ "numItemBlocks": 1,
+ "implicitPrefs": false,
+ "alpha": 1.0,
+ "userCol": "u",
+ "itemCol": "i",
+ "seed": 42,
+ "ratingCol": "r",
+ "nonnegative": false,
+ "checkpointInterval": -1,
+ "intermediateStorageLevel": "MEMORY_AND_DISK",
+ "finalStorageLevel": "MEMORY_AND_DISK",
+ "coldStartStrategy": "nan",
+ "blockSize": 2,
+ "predictionCol": "score"
+ },
+ "rank": 2,
+ "predictions": {
+ "schema": {
+ "type": "struct",
+ "fields": [
+ {
+ "name": "id",
+ "type": "integer",
+ "nullable": false,
+ "metadata": {}
+ },
+ {
+ "name": "u",
+ "type": "integer",
+ "nullable": true,
+ "metadata": {}
+ },
+ {
+ "name": "i",
+ "type": "integer",
+ "nullable": true,
+ "metadata": {}
+ },
+ {
+ "name": "score",
+ "type": "float",
+ "nullable": false,
+ "metadata": {}
+ }
+ ]
+ },
+ "rows": [
+ {
+ "id": 0,
+ "u": 0,
+ "i": 3,
+ "score": -2.1525332927703857
+ },
+ {
+ "id": 1,
+ "u": 1,
+ "i": 2,
+ "score": -10.773255348205566
+ },
+ {
+ "id": 2,
+ "u": 2,
+ "i": 1,
+ "score": -2.197770595550537
+ },
+ {
+ "id": 3,
+ "u": 3,
+ "i": 0,
+ "score": -11.028754234313965
+ },
+ {
+ "id": 4,
+ "u": 99,
+ "i": 0,
+ "score": {
+ "float": "nan"
+ }
+ },
+ {
+ "id": 5,
+ "u": 0,
+ "i": 99,
+ "score": {
+ "float": "nan"
+ }
+ },
+ {
+ "id": 6,
+ "u": 99,
+ "i": 99,
+ "score": {
+ "float": "nan"
+ }
+ }
+ ]
+ },
+ "user_factors": {
+ "schema": {
+ "type": "struct",
+ "fields": [
+ {
+ "name": "id",
+ "type": "integer",
+ "nullable": false,
+ "metadata": {}
+ },
+ {
+ "name": "features",
+ "type": {
+ "type": "array",
+ "elementType": "float",
+ "containsNull": false
+ },
+ "nullable": true,
+ "metadata": {}
+ }
+ ]
+ },
+ "rows": [
+ {
+ "id": 0,
+ "features": [
+ -0.6108363270759583,
+ -1.2426494359970093
+ ]
+ },
+ {
+ "id": 1,
+ "features": [
+ 3.107534885406494,
+ -1.2144067287445068
+ ]
+ },
+ {
+ "id": 2,
+ "features": [
+ -1.3985501527786255,
+ -0.10068392008543015
+ ]
+ },
+ {
+ "id": 3,
+ "features": [
+ 0.5775889754295349,
+ 3.2558352947235107
+ ]
+ }
+ ]
+ },
+ "item_factors": {
+ "schema": {
+ "type": "struct",
+ "fields": [
+ {
+ "name": "id",
+ "type": "integer",
+ "nullable": false,
+ "metadata": {}
+ },
+ {
+ "name": "features",
+ "type": {
+ "type": "array",
+ "elementType": "float",
+ "containsNull": false
+ },
+ "nullable": true,
+ "metadata": {}
+ }
+ ]
+ },
+ "rows": [
+ {
+ "id": 0,
+ "features": [
+ -1.1050530672073364,
+ -3.191343069076538
+ ]
+ },
+ {
+ "id": 1,
+ "features": [
+ 1.5673274993896484,
+ 0.05745118111371994
+ ]
+ },
+ {
+ "id": 2,
+ "features": [
+ -3.190537452697754,
+ 0.7069698572158813
+ ]
+ },
+ {
+ "id": 3,
+ "features": [
+ 1.0637704133987427,
+ 1.2093061208724976
+ ]
+ }
+ ]
+ },
+ "all_users": {
+ "schema": {
+ "type": "struct",
+ "fields": [
+ {
+ "name": "u",
+ "type": "integer",
+ "nullable": false,
+ "metadata": {}
+ },
+ {
+ "name": "recommendations",
+ "type": {
+ "type": "array",
+ "elementType": {
+ "type": "struct",
+ "fields": [
+ {
+ "name": "i",
+ "type": "integer",
+ "nullable": true,
+ "metadata": {}
+ },
+ {
+ "name": "rating",
+ "type": "float",
+ "nullable": true,
+ "metadata": {}
+ }
+ ]
+ },
+ "containsNull": true
+ },
+ "nullable": true,
+ "metadata": {}
+ }
+ ]
+ },
+ "rows": [
+ {
+ "u": 0,
+ "recommendations": [
+ {
+ "i": 0,
+ "rating": 4.6407270431518555
+ },
+ {
+ "i": 2,
+ "rating": 1.070380449295044
+ }
+ ]
+ },
+ {
+ "u": 1,
+ "recommendations": [
+ {
+ "i": 1,
+ "rating": 4.800755977630615
+ },
+ {
+ "i": 3,
+ "rating": 1.8371140956878662
+ }
+ ]
+ },
+ {
+ "u": 2,
+ "recommendations": [
+ {
+ "i": 2,
+ "rating": 4.390946388244629
+ },
+ {
+ "i": 0,
+ "rating": 1.8667891025543213
+ }
+ ]
+ },
+ {
+ "u": 3,
+ "recommendations": [
+ {
+ "i": 3,
+ "rating": 4.551723480224609
+ },
+ {
+ "i": 1,
+ "rating": 1.0923227071762085
+ }
+ ]
+ }
+ ]
+ },
+ "all_items": {
+ "schema": {
+ "type": "struct",
+ "fields": [
+ {
+ "name": "i",
+ "type": "integer",
+ "nullable": false,
+ "metadata": {}
+ },
+ {
+ "name": "recommendations",
+ "type": {
+ "type": "array",
+ "elementType": {
+ "type": "struct",
+ "fields": [
+ {
+ "name": "u",
+ "type": "integer",
+ "nullable": true,
+ "metadata": {}
+ },
+ {
+ "name": "rating",
+ "type": "float",
+ "nullable": true,
+ "metadata": {}
+ }
+ ]
+ },
+ "containsNull": true
+ },
+ "nullable": true,
+ "metadata": {}
+ }
+ ]
+ },
+ "rows": [
+ {
+ "i": 0,
+ "recommendations": [
+ {
+ "u": 0,
+ "rating": 4.6407270431518555
+ },
+ {
+ "u": 2,
+ "rating": 1.8667891025543213
+ }
+ ]
+ },
+ {
+ "i": 1,
+ "recommendations": [
+ {
+ "u": 1,
+ "rating": 4.800755977630615
+ },
+ {
+ "u": 3,
+ "rating": 1.0923227071762085
+ }
+ ]
+ },
+ {
+ "i": 2,
+ "recommendations": [
+ {
+ "u": 2,
+ "rating": 4.390946388244629
+ },
+ {
+ "u": 0,
+ "rating": 1.070380449295044
+ }
+ ]
+ },
+ {
+ "i": 3,
+ "recommendations": [
+ {
+ "u": 3,
+ "rating": 4.551723480224609
+ },
+ {
+ "u": 1,
+ "rating": 1.8371140956878662
+ }
+ ]
+ }
+ ]
+ },
+ "user_subset": {
+ "schema": {
+ "type": "struct",
+ "fields": [
+ {
+ "name": "u",
+ "type": "integer",
+ "nullable": false,
+ "metadata": {}
+ },
+ {
+ "name": "recommendations",
+ "type": {
+ "type": "array",
+ "elementType": {
+ "type": "struct",
+ "fields": [
+ {
+ "name": "i",
+ "type": "integer",
+ "nullable": true,
+ "metadata": {}
+ },
+ {
+ "name": "rating",
+ "type": "float",
+ "nullable": true,
+ "metadata": {}
+ }
+ ]
+ },
+ "containsNull": true
+ },
+ "nullable": true,
+ "metadata": {}
+ }
+ ]
+ },
+ "rows": [
+ {
+ "u": 0,
+ "recommendations": [
+ {
+ "i": 0,
+ "rating": 4.6407270431518555
+ },
+ {
+ "i": 2,
+ "rating": 1.070380449295044
+ }
+ ]
+ },
+ {
+ "u": 2,
+ "recommendations": [
+ {
+ "i": 2,
+ "rating": 4.390946388244629
+ },
+ {
+ "i": 0,
+ "rating": 1.8667891025543213
+ }
+ ]
+ }
+ ]
+ },
+ "item_subset": {
+ "schema": {
+ "type": "struct",
+ "fields": [
+ {
+ "name": "i",
+ "type": "integer",
+ "nullable": false,
+ "metadata": {}
+ },
+ {
+ "name": "recommendations",
+ "type": {
+ "type": "array",
+ "elementType": {
+ "type": "struct",
+ "fields": [
+ {
+ "name": "u",
+ "type": "integer",
+ "nullable": true,
+ "metadata": {}
+ },
+ {
+ "name": "rating",
+ "type": "float",
+ "nullable": true,
+ "metadata": {}
+ }
+ ]
+ },
+ "containsNull": true
+ },
+ "nullable": true,
+ "metadata": {}
+ }
+ ]
+ },
+ "rows": [
+ {
+ "i": 1,
+ "recommendations": [
+ {
+ "u": 1,
+ "rating": 4.800755977630615
+ },
+ {
+ "u": 3,
+ "rating": 1.0923227071762085
+ }
+ ]
+ },
+ {
+ "i": 3,
+ "recommendations": [
+ {
+ "u": 3,
+ "rating": 4.551723480224609
+ },
+ {
+ "u": 1,
+ "rating": 1.8371140956878662
+ }
+ ]
+ }
+ ]
+ },
+ "drop_predictions": {
+ "schema": {
+ "type": "struct",
+ "fields": [
+ {
+ "name": "id",
+ "type": "integer",
+ "nullable": false,
+ "metadata": {}
+ },
+ {
+ "name": "u",
+ "type": "integer",
+ "nullable": true,
+ "metadata": {}
+ },
+ {
+ "name": "i",
+ "type": "integer",
+ "nullable": true,
+ "metadata": {}
+ },
+ {
+ "name": "filtered",
+ "type": "float",
+ "nullable": false,
+ "metadata": {}
+ }
+ ]
+ },
+ "rows": [
+ {
+ "id": 0,
+ "u": 0,
+ "i": 3,
+ "filtered": -2.1525332927703857
+ },
+ {
+ "id": 1,
+ "u": 1,
+ "i": 2,
+ "filtered": -10.773255348205566
+ },
+ {
+ "id": 2,
+ "u": 2,
+ "i": 1,
+ "filtered": -2.197770595550537
+ },
+ {
+ "id": 3,
+ "u": 3,
+ "i": 0,
+ "filtered": -11.028754234313965
+ }
+ ]
+ }
+ },
+ {
+ "name": "implicit-nonnegative",
+ "values": {
+ "rank": 2,
+ "maxIter": 8,
+ "regParam": 0.1,
+ "numUserBlocks": 1,
+ "numItemBlocks": 1,
+ "implicitPrefs": true,
+ "alpha": 2.0,
+ "userCol": "u",
+ "itemCol": "i",
+ "seed": 42,
+ "ratingCol": "r",
+ "nonnegative": true,
+ "checkpointInterval": -1,
+ "intermediateStorageLevel": "MEMORY_AND_DISK",
+ "finalStorageLevel": "MEMORY_AND_DISK",
+ "coldStartStrategy": "nan",
+ "blockSize": 2,
+ "predictionCol": "score"
+ },
+ "rank": 2,
+ "predictions": {
+ "schema": {
+ "type": "struct",
+ "fields": [
+ {
+ "name": "id",
+ "type": "integer",
+ "nullable": false,
+ "metadata": {}
+ },
+ {
+ "name": "u",
+ "type": "integer",
+ "nullable": true,
+ "metadata": {}
+ },
+ {
+ "name": "i",
+ "type": "integer",
+ "nullable": true,
+ "metadata": {}
+ },
+ {
+ "name": "score",
+ "type": "float",
+ "nullable": false,
+ "metadata": {}
+ }
+ ]
+ },
+ "rows": [
+ {
+ "id": 0,
+ "u": 0,
+ "i": 3,
+ "score": 0.24526400864124298
+ },
+ {
+ "id": 1,
+ "u": 1,
+ "i": 2,
+ "score": 0.8590666055679321
+ },
+ {
+ "id": 2,
+ "u": 2,
+ "i": 1,
+ "score": 0.9728904366493225
+ },
+ {
+ "id": 3,
+ "u": 3,
+ "i": 0,
+ "score": 0.7668248414993286
+ },
+ {
+ "id": 4,
+ "u": 99,
+ "i": 0,
+ "score": {
+ "float": "nan"
+ }
+ },
+ {
+ "id": 5,
+ "u": 0,
+ "i": 99,
+ "score": {
+ "float": "nan"
+ }
+ },
+ {
+ "id": 6,
+ "u": 99,
+ "i": 99,
+ "score": {
+ "float": "nan"
+ }
+ }
+ ]
+ },
+ "user_factors": {
+ "schema": {
+ "type": "struct",
+ "fields": [
+ {
+ "name": "id",
+ "type": "integer",
+ "nullable": false,
+ "metadata": {}
+ },
+ {
+ "name": "features",
+ "type": {
+ "type": "array",
+ "elementType": "float",
+ "containsNull": false
+ },
+ "nullable": true,
+ "metadata": {}
+ }
+ ]
+ },
+ "rows": [
+ {
+ "id": 0,
+ "features": [
+ 1.1611719131469727,
+ 0.30443644523620605
+ ]
+ },
+ {
+ "id": 1,
+ "features": [
+ 0.5052933692932129,
+ 1.2656439542770386
+ ]
+ },
+ {
+ "id": 2,
+ "features": [
+ 0.734376847743988,
+ 1.058652639389038
+ ]
+ },
+ {
+ "id": 3,
+ "features": [
+ 0.42252495884895325,
+ 1.2884759902954102
+ ]
+ }
+ ]
+ },
+ "item_factors": {
+ "schema": {
+ "type": "struct",
+ "fields": [
+ {
+ "name": "id",
+ "type": "integer",
+ "nullable": false,
+ "metadata": {}
+ },
+ {
+ "name": "features",
+ "type": {
+ "type": "array",
+ "elementType": "float",
+ "containsNull": false
+ },
+ "nullable": true,
+ "metadata": {}
+ }
+ ]
+ },
+ "rows": [
+ {
+ "id": 0,
+ "features": [
+ 0.7716313004493713,
+ 0.34210288524627686
+ ]
+ },
+ {
+ "id": 1,
+ "features": [
+ 0.5928774476051331,
+ 0.5077160596847534
+ ]
+ },
+ {
+ "id": 2,
+ "features": [
+ 0.7440823316574097,
+ 0.38169243931770325
+ ]
+ },
+ {
+ "id": 3,
+ "features": [
+ 0.013430888764560223,
+ 0.7544052004814148
+ ]
+ }
+ ]
+ },
+ "all_users": {
+ "schema": {
+ "type": "struct",
+ "fields": [
+ {
+ "name": "u",
+ "type": "integer",
+ "nullable": false,
+ "metadata": {}
+ },
+ {
+ "name": "recommendations",
+ "type": {
+ "type": "array",
+ "elementType": {
+ "type": "struct",
+ "fields": [
+ {
+ "name": "i",
+ "type": "integer",
+ "nullable": true,
+ "metadata": {}
+ },
+ {
+ "name": "rating",
+ "type": "float",
+ "nullable": true,
+ "metadata": {}
+ }
+ ]
+ },
+ "containsNull": true
+ },
+ "nullable": true,
+ "metadata": {}
+ }
+ ]
+ },
+ "rows": [
+ {
+ "u": 0,
+ "recommendations": [
+ {
+ "i": 0,
+ "rating": 1.0001451969146729
+ },
+ {
+ "i": 2,
+ "rating": 0.9802086353302002
+ }
+ ]
+ },
+ {
+ "u": 1,
+ "recommendations": [
+ {
+ "i": 3,
+ "rating": 0.9615948796272278
+ },
+ {
+ "i": 1,
+ "rating": 0.9421648383140564
+ }
+ ]
+ },
+ {
+ "u": 2,
+ "recommendations": [
+ {
+ "i": 1,
+ "rating": 0.9728904366493225
+ },
+ {
+ "i": 2,
+ "rating": 0.9505165815353394
+ }
+ ]
+ },
+ {
+ "u": 3,
+ "recommendations": [
+ {
+ "i": 3,
+ "rating": 0.9777078628540039
+ },
+ {
+ "i": 1,
+ "rating": 0.9046854376792908
+ }
+ ]
+ }
+ ]
+ },
+ "all_items": {
+ "schema": {
+ "type": "struct",
+ "fields": [
+ {
+ "name": "i",
+ "type": "integer",
+ "nullable": false,
+ "metadata": {}
+ },
+ {
+ "name": "recommendations",
+ "type": {
+ "type": "array",
+ "elementType": {
+ "type": "struct",
+ "fields": [
+ {
+ "name": "u",
+ "type": "integer",
+ "nullable": true,
+ "metadata": {}
+ },
+ {
+ "name": "rating",
+ "type": "float",
+ "nullable": true,
+ "metadata": {}
+ }
+ ]
+ },
+ "containsNull": true
+ },
+ "nullable": true,
+ "metadata": {}
+ }
+ ]
+ },
+ "rows": [
+ {
+ "i": 0,
+ "recommendations": [
+ {
+ "u": 0,
+ "rating": 1.0001451969146729
+ },
+ {
+ "u": 2,
+ "rating": 0.9288362860679626
+ }
+ ]
+ },
+ {
+ "i": 1,
+ "recommendations": [
+ {
+ "u": 2,
+ "rating": 0.9728904366493225
+ },
+ {
+ "u": 1,
+ "rating": 0.9421648383140564
+ }
+ ]
+ },
+ {
+ "i": 2,
+ "recommendations": [
+ {
+ "u": 0,
+ "rating": 0.9802086353302002
+ },
+ {
+ "u": 2,
+ "rating": 0.9505165815353394
+ }
+ ]
+ },
+ {
+ "i": 3,
+ "recommendations": [
+ {
+ "u": 3,
+ "rating": 0.9777078628540039
+ },
+ {
+ "u": 1,
+ "rating": 0.9615948796272278
+ }
+ ]
+ }
+ ]
+ },
+ "user_subset": {
+ "schema": {
+ "type": "struct",
+ "fields": [
+ {
+ "name": "u",
+ "type": "integer",
+ "nullable": false,
+ "metadata": {}
+ },
+ {
+ "name": "recommendations",
+ "type": {
+ "type": "array",
+ "elementType": {
+ "type": "struct",
+ "fields": [
+ {
+ "name": "i",
+ "type": "integer",
+ "nullable": true,
+ "metadata": {}
+ },
+ {
+ "name": "rating",
+ "type": "float",
+ "nullable": true,
+ "metadata": {}
+ }
+ ]
+ },
+ "containsNull": true
+ },
+ "nullable": true,
+ "metadata": {}
+ }
+ ]
+ },
+ "rows": [
+ {
+ "u": 0,
+ "recommendations": [
+ {
+ "i": 0,
+ "rating": 1.0001451969146729
+ },
+ {
+ "i": 2,
+ "rating": 0.9802086353302002
+ }
+ ]
+ },
+ {
+ "u": 2,
+ "recommendations": [
+ {
+ "i": 1,
+ "rating": 0.9728904366493225
+ },
+ {
+ "i": 2,
+ "rating": 0.9505165815353394
+ }
+ ]
+ }
+ ]
+ },
+ "item_subset": {
+ "schema": {
+ "type": "struct",
+ "fields": [
+ {
+ "name": "i",
+ "type": "integer",
+ "nullable": false,
+ "metadata": {}
+ },
+ {
+ "name": "recommendations",
+ "type": {
+ "type": "array",
+ "elementType": {
+ "type": "struct",
+ "fields": [
+ {
+ "name": "u",
+ "type": "integer",
+ "nullable": true,
+ "metadata": {}
+ },
+ {
+ "name": "rating",
+ "type": "float",
+ "nullable": true,
+ "metadata": {}
+ }
+ ]
+ },
+ "containsNull": true
+ },
+ "nullable": true,
+ "metadata": {}
+ }
+ ]
+ },
+ "rows": [
+ {
+ "i": 1,
+ "recommendations": [
+ {
+ "u": 2,
+ "rating": 0.9728904366493225
+ },
+ {
+ "u": 1,
+ "rating": 0.9421648383140564
+ }
+ ]
+ },
+ {
+ "i": 3,
+ "recommendations": [
+ {
+ "u": 3,
+ "rating": 0.9777078628540039
+ },
+ {
+ "u": 1,
+ "rating": 0.9615948796272278
+ }
+ ]
+ }
+ ]
+ },
+ "drop_predictions": {
+ "schema": {
+ "type": "struct",
+ "fields": [
+ {
+ "name": "id",
+ "type": "integer",
+ "nullable": false,
+ "metadata": {}
+ },
+ {
+ "name": "u",
+ "type": "integer",
+ "nullable": true,
+ "metadata": {}
+ },
+ {
+ "name": "i",
+ "type": "integer",
+ "nullable": true,
+ "metadata": {}
+ },
+ {
+ "name": "filtered",
+ "type": "float",
+ "nullable": false,
+ "metadata": {}
+ }
+ ]
+ },
+ "rows": [
+ {
+ "id": 0,
+ "u": 0,
+ "i": 3,
+ "filtered": 0.24526400864124298
+ },
+ {
+ "id": 1,
+ "u": 1,
+ "i": 2,
+ "filtered": 0.8590666055679321
+ },
+ {
+ "id": 2,
+ "u": 2,
+ "i": 1,
+ "filtered": 0.9728904366493225
+ },
+ {
+ "id": 3,
+ "u": 3,
+ "i": 0,
+ "filtered": 0.7668248414993286
+ }
+ ]
+ }
+ }
+ ],
+ "fetches": [
+ {
+ "count": 2,
+ "method": "recommendForAllUsers",
+ "arg_b64": "MAI="
+ },
+ {
+ "count": 2147483648,
+ "method": "recommendForAllUsers",
+ "arg_b64": "OICAgIAI"
+ },
+ {
+ "count": null,
+ "method": "recommendForAllUsers",
+ "arg_b64": "CgIKAA=="
+ },
+ {
+ "count": true,
+ "method": "recommendForAllUsers",
+ "arg_b64": "GAE="
+ },
+ {
+ "count": 2.0,
+ "method": "recommendForAllUsers",
+ "arg_b64": "WQAAAAAAAABA"
+ },
+ {
+ "count": "2",
+ "method": "recommendForAllUsers",
+ "arg_b64": "agEy"
+ }
+ ]
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]