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 ea9ec88c [SPARK-61544][CONNECT] Support native NaiveBayes training and 
prediction
ea9ec88c is described below

commit ea9ec88c506da0ee037464222d3826aacf3784a8
Author: Ruifeng Zheng <[email protected]>
AuthorDate: Thu Nov 12 21:30:41 2026 +0800

    [SPARK-61544][CONNECT] Support native NaiveBayes training and prediction
    
    ### What changes were proposed in this pull request?
    
    Add native Rust `NaiveBayes` and `NaiveBayesModel` training and DataFrame 
prediction, and expose `NaiveBayes` in the Rust-backed Python Connect API. 
Support all nine constructor parameters and named setters: feature, label and 
output columns, smoothing, model type, thresholds and instance weights. Rust 
also provides parameter getters.
    
    The fitted model uses the existing cached-model protocol and 
ownership/session checks. Add official-PySpark parameter fixtures for all four 
model types and register the new live tests in CI.
    
    ### Why are the changes needed?
    
    Continue native ML coverage after the tree ensembles, supporting 
multinomial, Bernoulli, complement and Gaussian Naive Bayes without a Python 
estimator implementation on the client.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes. Rust and Rust-backed Python users can fit NaiveBayes and transform 
DataFrames to predictions, probabilities and raw scores. Tests cover all four 
model types and multiclass classification, sparse/dense vectors, negative 
continuous Gaussian features, analytically checked weights/smoothing, threshold 
decisions, disabled vector outputs, repeated fits and lazy model lifetime.
    
    The native Python constructor matches official PySpark's keyword 
order/defaults and nine named setters, including its parameter conversions. 
Unset values remain omitted so the server uses its defaults. This native 
surface covers construction, setters, fit and DataFrame transform; 
model-statistic inspection, single-vector prediction and persistence are 
outside its scope.
    
    ### How was this patch tested?
    
    - All 636 Rust library tests pass. Every integration test compiles with 
default features and with `wasm-udf`.
    - Four Rust live tests pass; a golden comparison matches every parameter 
for all four model types to official PySpark.
    - All 20 new behavior cases pass with official PySpark. The native 
extension passes those same cases and two shared ownership/session tests (22 
passed).
    - Native Python offline suites: 2,060 passed, 8 skipped and 14 subtests 
passed.
    - The constructor and nine named setters match official PySpark; the 
12-class SQL API introspection diff has zero missing public members.
    - Official Spark 4.3 Connect transport suite: 2,638 passed, 589 skipped 
across 87 files; zero unexpected failures.
    - Rust formatting, Ruff lint/format, Ruff exclusion and whitespace checks 
pass. Clippy passes for the Rust core and new test targets. Workspace and 
Python-wrapper Clippy report errors on unchanged source lines; none of the 
reported primary error sites was introduced by this patch.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Codex (GPT-6)
    
    This pull request and its description were written by Isaac.
    
    Closes #573 from zhengruifeng/add-naive-bayes.
    
    Authored-by: Ruifeng Zheng <[email protected]>
    Signed-off-by: Ruifeng Zheng <[email protected]>
---
 .github/workflows/build_python_connect.yml       |   4 +-
 crates/pyspark-rs/src/lib.rs                     |   1 +
 crates/pyspark-rs/src/ml.rs                      | 121 +++++++-
 crates/spark-connect/src/ml.rs                   | 357 +++++++++++++++++++++++
 crates/spark-connect/tests/e2e_naive_bayes.rs    | 264 +++++++++++++++++
 crates/spark-connect/tests/naive_bayes_golden.rs |  29 ++
 docs/compatibility.md                            |  27 ++
 python/pyspark/ml/connect/__init__.py            |   2 +
 python/pyspark/ml/connect/classification.py      |   3 +-
 python/tests/test_ml_e2e.py                      |   2 +
 python/tests/test_ml_offline.py                  |  63 ++++
 python/tests/test_naive_bayes_e2e.py             | 218 ++++++++++++++
 scripts/capture_naive_bayes_golden.py            |  59 ++++
 tests/golden/naive_bayes.json                    |  21 ++
 14 files changed, 1166 insertions(+), 5 deletions(-)

diff --git a/.github/workflows/build_python_connect.yml 
b/.github/workflows/build_python_connect.yml
index 436c4ac1..0839b090 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 -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 -q
 
       - name: Restart Connect server in local-cluster mode
         # Resource profiles and artifact distribution across executors can 
only be
@@ -556,7 +556,7 @@ jobs:
         run: |
           cargo test -p apache-spark-connect \
             --test e2e_functions --test e2e_columns --test e2e_dataframe \
-            --test e2e_coverage --test e2e_linear_svc --test 
e2e_linear_regression --test e2e_kmeans --test e2e_decision_tree_regressor 
--test e2e_decision_tree_classifier --test e2e_gbt_regressor --test 
e2e_gbt_classifier --test e2e_random_forest --test e2e_random_forest_regressor 
--test e2e_integration \
+            --test e2e_coverage --test e2e_linear_svc --test 
e2e_linear_regression --test e2e_kmeans --test e2e_decision_tree_regressor 
--test e2e_decision_tree_classifier --test e2e_gbt_regressor --test 
e2e_naive_bayes --test e2e_gbt_classifier --test e2e_random_forest --test 
e2e_random_forest_regressor --test e2e_integration \
             --test arrow_map_input --test array_literal --test 
execute_plan_hook --test raw_relation \
             --test types_roundtrip \
             --test e2e_reattach_drop \
diff --git a/crates/pyspark-rs/src/lib.rs b/crates/pyspark-rs/src/lib.rs
index 45d8122d..144b136b 100644
--- a/crates/pyspark-rs/src/lib.rs
+++ b/crates/pyspark-rs/src/lib.rs
@@ -247,6 +247,7 @@ fn _pyspark(_py: Python<'_>, m: &Bound<'_, PyModule>) -> 
PyResult<()> {
     m.add_class::<ml::PyLinearSVC>()?;
     m.add_class::<ml::PyLinearRegression>()?;
     m.add_class::<ml::PyDecisionTreeClassifier>()?;
+    m.add_class::<ml::PyNaiveBayes>()?;
     m.add_class::<ml::PyGBTClassifier>()?;
     m.add_class::<ml::PyGBTRegressor>()?;
     m.add_class::<ml::PyRandomForestClassifier>()?;
diff --git a/crates/pyspark-rs/src/ml.rs b/crates/pyspark-rs/src/ml.rs
index 888483b4..4c63a917 100644
--- a/crates/pyspark-rs/src/ml.rs
+++ b/crates/pyspark-rs/src/ml.rs
@@ -17,8 +17,8 @@ use pyo3::PyClass;
 use spark_connect::ml::{
     BinaryClassificationEvaluator, CrossValidator, DecisionTreeClassifier, 
DecisionTreeRegressor,
     Estimator, Evaluator, GBTClassifier, GBTRegressor, KMeans, 
LinearRegression, LinearSVC,
-    LogisticRegression, MaxAbsScaler, Model, 
MulticlassClassificationEvaluator, Params, Pipeline,
-    RandomForestClassifier, RandomForestRegressor, RegressionEvaluator, 
StandardScaler,
+    LogisticRegression, MaxAbsScaler, Model, 
MulticlassClassificationEvaluator, NaiveBayes, Params,
+    Pipeline, RandomForestClassifier, RandomForestRegressor, 
RegressionEvaluator, StandardScaler,
     StringIndexer, Transformer, VectorAssembler,
 };
 use spark_connect::DataFrame;
@@ -1379,6 +1379,122 @@ impl PyDecisionTreeClassifier {
     }
 }
 
+/// Naive Bayes classifier fitted and cached by Spark Connect.
+#[pyclass(name = "NaiveBayes", module = "pyspark.ml.connect.classification")]
+pub struct PyNaiveBayes {
+    inner: NaiveBayes,
+    unsendable: Vec<&'static str>,
+}
+
+const NAIVE_BAYES_PARAMS: &[(&str, Kind)] = &[
+    ("featuresCol", Kind::Str),
+    ("labelCol", Kind::Str),
+    ("predictionCol", Kind::Str),
+    ("probabilityCol", Kind::Str),
+    ("rawPredictionCol", Kind::Str),
+    ("smoothing", Kind::Float),
+    ("modelType", Kind::Str),
+    ("thresholds", Kind::FloatList),
+    ("weightCol", Kind::Str),
+];
+
+#[pymethods]
+impl PyNaiveBayes {
+    #[new]
+    #[pyo3(signature = (*args, **kwargs), text_signature = "(*, 
featuresCol='features', labelCol='label', predictionCol='prediction', 
probabilityCol='probability', rawPredictionCol='rawPrediction', smoothing=1.0, 
modelType='multinomial', thresholds=None, weightCol=None)")]
+    fn new(args: &Bound<'_, PyTuple>, kwargs: Option<&Bound<'_, PyDict>>) -> 
PyResult<Self> {
+        let mut this = Self {
+            inner: NaiveBayes::new(),
+            unsendable: Vec::new(),
+        };
+        init_params(
+            &mut this,
+            "NaiveBayes",
+            &[],
+            NAIVE_BAYES_PARAMS,
+            args,
+            kwargs,
+        )?;
+        Ok(this)
+    }
+
+    #[pyo3(name = "setFeaturesCol")]
+    fn set_feature_col<'py>(
+        slf: Bound<'py, Self>,
+        value: &Bound<'py, PyAny>,
+    ) -> PyResult<Bound<'py, Self>> {
+        set_param(slf, "featuresCol", Kind::Str, value)
+    }
+
+    #[pyo3(name = "setLabelCol")]
+    fn set_label_col<'py>(
+        slf: Bound<'py, Self>,
+        value: &Bound<'py, PyAny>,
+    ) -> PyResult<Bound<'py, Self>> {
+        set_param(slf, "labelCol", 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 = "setProbabilityCol")]
+    fn set_probability_col<'py>(
+        slf: Bound<'py, Self>,
+        value: &Bound<'py, PyAny>,
+    ) -> PyResult<Bound<'py, Self>> {
+        set_param(slf, "probabilityCol", Kind::Str, value)
+    }
+
+    #[pyo3(name = "setRawPredictionCol")]
+    fn set_raw_prediction_col<'py>(
+        slf: Bound<'py, Self>,
+        value: &Bound<'py, PyAny>,
+    ) -> PyResult<Bound<'py, Self>> {
+        set_param(slf, "rawPredictionCol", Kind::Str, value)
+    }
+
+    #[pyo3(name = "setSmoothing")]
+    fn set_smoothing<'py>(
+        slf: Bound<'py, Self>,
+        value: &Bound<'py, PyAny>,
+    ) -> PyResult<Bound<'py, Self>> {
+        set_param(slf, "smoothing", Kind::Float, value)
+    }
+
+    #[pyo3(name = "setModelType")]
+    fn set_model_type<'py>(
+        slf: Bound<'py, Self>,
+        value: &Bound<'py, PyAny>,
+    ) -> PyResult<Bound<'py, Self>> {
+        set_param(slf, "modelType", Kind::Str, value)
+    }
+
+    #[pyo3(name = "setThresholds")]
+    fn set_thresholds<'py>(
+        slf: Bound<'py, Self>,
+        value: &Bound<'py, PyAny>,
+    ) -> PyResult<Bound<'py, Self>> {
+        set_param(slf, "thresholds", Kind::FloatList, value)
+    }
+
+    #[pyo3(name = "setWeightCol")]
+    fn set_weight_col<'py>(
+        slf: Bound<'py, Self>,
+        value: &Bound<'py, PyAny>,
+    ) -> PyResult<Bound<'py, Self>> {
+        set_param(slf, "weightCol", Kind::Str, value)
+    }
+
+    fn fit(slf: &Bound<'_, Self>, df: &PyDataFrame) -> PyResult<PyMLModel> {
+        fit_native(slf, df)
+    }
+}
+
 /// Gradient-boosted binary classifier fitted and cached by Spark Connect.
 #[pyclass(name = "GBTClassifier", module = 
"pyspark.ml.connect.classification")]
 pub struct PyGBTClassifier {
@@ -2954,6 +3070,7 @@ native!(
     PyLinearSVC => LinearSVC,
     PyLinearRegression => LinearRegression,
     PyDecisionTreeClassifier => DecisionTreeClassifier,
+    PyNaiveBayes => NaiveBayes,
     PyGBTClassifier => GBTClassifier,
     PyGBTRegressor => GBTRegressor,
     PyRandomForestClassifier => RandomForestClassifier,
diff --git a/crates/spark-connect/src/ml.rs b/crates/spark-connect/src/ml.rs
index ebdc46c1..d79d2cc8 100644
--- a/crates/spark-connect/src/ml.rs
+++ b/crates/spark-connect/src/ml.rs
@@ -2198,6 +2198,214 @@ impl Model for DecisionTreeClassificationModel {
     }
 }
 
+/// Naive Bayes classification using Spark's JVM implementation and ML vectors.
+///
+/// Supports multinomial, Bernoulli, complement and Gaussian models. 
Multinomial and
+/// complement features must be nonnegative, Bernoulli features must be 0 or 
1, and
+/// Gaussian features may be continuous and negative. Unset parameters use 
Spark's defaults.
+#[derive(Debug, Clone)]
+pub struct NaiveBayes {
+    operator: MlOperator,
+    params: Params,
+}
+
+impl NaiveBayes {
+    pub fn new() -> Self {
+        Self {
+            operator: MlOperator::new(
+                "org.apache.spark.ml.classification.NaiveBayes",
+                OperatorType::Estimator,
+            ),
+            params: Params::new(),
+        }
+    }
+
+    /// Feature vector column.
+    pub fn set_feature_col(mut self, value: &str) -> Self {
+        self.params = self.params.set_param_string("featuresCol", value);
+        self
+    }
+
+    /// Numeric label column of nonnegative integer class indices.
+    pub fn set_label_col(mut self, value: &str) -> Self {
+        self.params = self.params.set_param_string("labelCol", value);
+        self
+    }
+
+    /// Predicted class output column.
+    pub fn set_prediction_col(mut self, value: &str) -> Self {
+        self.params = self.params.set_param_string("predictionCol", value);
+        self
+    }
+
+    /// Class probability output column; empty disables it.
+    pub fn set_probability_col(mut self, value: &str) -> Self {
+        self.params = self.params.set_param_string("probabilityCol", value);
+        self
+    }
+
+    /// Raw class prediction output column; empty disables it.
+    pub fn set_raw_prediction_col(mut self, value: &str) -> Self {
+        self.params = self.params.set_param_string("rawPredictionCol", value);
+        self
+    }
+
+    /// Additive smoothing parameter, which must be nonnegative.
+    pub fn set_smoothing(mut self, value: f64) -> Self {
+        self.params = self.params.set_param_double("smoothing", value);
+        self
+    }
+
+    /// Model type: multinomial, bernoulli, complement or gaussian.
+    pub fn set_model_type(mut self, value: &str) -> Self {
+        self.params = self.params.set_param_string("modelType", value);
+        self
+    }
+
+    /// Per-class thresholds: predictions maximize probability divided by 
threshold.
+    pub fn set_thresholds(mut self, value: impl IntoIterator<Item = f64>) -> 
Self {
+        self.params = self.params.set_param_double_array("thresholds", value);
+        self
+    }
+
+    /// Optional instance weight column.
+    pub fn set_weight_col(mut self, value: &str) -> Self {
+        self.params = self.params.set_param_string("weightCol", value);
+        self
+    }
+
+    /// The featuresCol value; default: "features".
+    pub fn feature_col(&self) -> &str {
+        self.params.string_or("featuresCol", "features")
+    }
+
+    /// The labelCol value; default: "label".
+    pub fn label_col(&self) -> &str {
+        self.params.string_or("labelCol", "label")
+    }
+
+    /// The predictionCol value; default: "prediction".
+    pub fn prediction_col(&self) -> &str {
+        self.params.string_or("predictionCol", "prediction")
+    }
+
+    /// The probabilityCol value; default: "probability".
+    pub fn probability_col(&self) -> &str {
+        self.params.string_or("probabilityCol", "probability")
+    }
+
+    /// The rawPredictionCol value; default: "rawPrediction".
+    pub fn raw_prediction_col(&self) -> &str {
+        self.params.string_or("rawPredictionCol", "rawPrediction")
+    }
+
+    /// The smoothing value; default: 1.0.
+    pub fn smoothing(&self) -> f64 {
+        self.params.double_or("smoothing", 1.0)
+    }
+
+    /// The modelType value; default: "multinomial".
+    pub fn model_type(&self) -> &str {
+        self.params.string_or("modelType", "multinomial")
+    }
+
+    /// The thresholds value, if set.
+    pub fn thresholds(&self) -> Option<Vec<f64>> {
+        self.params.double_array_opt("thresholds")
+    }
+
+    /// The weightCol value, if set.
+    pub fn weight_col(&self) -> Option<&str> {
+        self.params.string_opt("weightCol")
+    }
+
+    fn model_from_info(
+        &self,
+        info: proto::ml_command_result::MlOperatorInfo,
+        session: &SparkSession,
+    ) -> spark_connect_core::error::Result<NaiveBayesModel> {
+        let cached = CachedModel::from_info(&info, session, "NaiveBayes")?;
+        Ok(NaiveBayesModel {
+            operator: MlOperator::with_uid(
+                "org.apache.spark.ml.classification.NaiveBayesModel",
+                info.uid.as_deref().unwrap_or(&self.operator.uid),
+                OperatorType::Model,
+            ),
+            params: self.params.clone(),
+            cached,
+        })
+    }
+}
+
+impl Default for NaiveBayes {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl Estimator for NaiveBayes {
+    fn operator(&self) -> &MlOperator {
+        &self.operator
+    }
+    fn operator_mut(&mut self) -> &mut MlOperator {
+        &mut self.operator
+    }
+    fn params(&self) -> &Params {
+        &self.params
+    }
+    fn params_mut(&mut self) -> &mut Params {
+        &mut self.params
+    }
+
+    fn fit_impl(&mut self, df: &DataFrame) -> 
spark_connect_core::error::Result<Box<dyn Model>> {
+        let info = fit_via_command(&self.operator, &self.params, df)?;
+        Ok(Box::new(self.model_from_info(info, &df.session)?))
+    }
+}
+
+/// A Naive Bayes classification model fitted by Spark Connect.
+///
+/// Obtain it through [`Estimator::fit`]. The model, its clones and transformed
+/// DataFrames retain the cached server model until the last owner is dropped.
+#[derive(Debug, Clone)]
+pub struct NaiveBayesModel {
+    operator: MlOperator,
+    params: Params,
+    cached: CachedModel,
+}
+
+impl Transformer for NaiveBayesModel {
+    fn operator(&self) -> &MlOperator {
+        &self.operator
+    }
+    fn operator_mut(&mut self) -> &mut MlOperator {
+        &mut self.operator
+    }
+    fn params(&self) -> &Params {
+        &self.params
+    }
+    fn params_mut(&mut self) -> &mut Params {
+        &mut self.params
+    }
+
+    fn build_ml_relation(
+        &self,
+        input: &DataFrame,
+    ) -> spark_connect_core::error::Result<proto::MlRelation> {
+        self.cached.build_ml_relation(input, &self.params)
+    }
+
+    fn transform_impl(&mut self, df: &DataFrame) -> 
spark_connect_core::error::Result<DataFrame> {
+        self.cached.transform(df, &self.params)
+    }
+}
+
+impl Model for NaiveBayesModel {
+    fn clone_box(&self) -> Box<dyn Model> {
+        Box::new(self.clone())
+    }
+}
+
 /// Gradient-boosted binary classification using Spark's JVM implementation 
and ML vectors.
 ///
 /// Labels must be 0 or 1. Unset parameters use Spark's defaults. A seed 
controls row sampling
@@ -5578,6 +5786,155 @@ mod tests {
             .starts_with("DecisionTreeClassifier_"));
     }
 
+    #[test]
+    fn naive_bayes_getters_follow_defaults_builders_and_mutable_params() {
+        let mut estimator = NaiveBayes::default();
+        assert_eq!(estimator.feature_col(), "features");
+        assert_eq!(estimator.label_col(), "label");
+        assert_eq!(estimator.prediction_col(), "prediction");
+        assert_eq!(estimator.probability_col(), "probability");
+        assert_eq!(estimator.raw_prediction_col(), "rawPrediction");
+        assert_eq!(estimator.smoothing(), 1.0);
+        assert_eq!(estimator.model_type(), "multinomial");
+        assert_eq!(estimator.thresholds(), None);
+        assert_eq!(estimator.weight_col(), None);
+        let built = NaiveBayes::new()
+            .set_feature_col("input")
+            .set_label_col("target")
+            .set_prediction_col("class")
+            .set_probability_col("probs")
+            .set_raw_prediction_col("scores")
+            .set_smoothing(0.5)
+            .set_model_type("gaussian")
+            .set_thresholds(vec![0.5, 1.5])
+            .set_weight_col("weight");
+        *estimator.params_mut() = estimator
+            .params()
+            .clone()
+            .set_param_string("featuresCol", "input");
+        assert_eq!(estimator.feature_col(), "input");
+        assert_eq!(built.feature_col(), estimator.feature_col());
+        *estimator.params_mut() = estimator
+            .params()
+            .clone()
+            .set_param_string("labelCol", "target");
+        assert_eq!(estimator.label_col(), "target");
+        assert_eq!(built.label_col(), estimator.label_col());
+        *estimator.params_mut() = estimator
+            .params()
+            .clone()
+            .set_param_string("predictionCol", "class");
+        assert_eq!(estimator.prediction_col(), "class");
+        assert_eq!(built.prediction_col(), estimator.prediction_col());
+        *estimator.params_mut() = estimator
+            .params()
+            .clone()
+            .set_param_string("probabilityCol", "probs");
+        assert_eq!(estimator.probability_col(), "probs");
+        assert_eq!(built.probability_col(), estimator.probability_col());
+        *estimator.params_mut() = estimator
+            .params()
+            .clone()
+            .set_param_string("rawPredictionCol", "scores");
+        assert_eq!(estimator.raw_prediction_col(), "scores");
+        assert_eq!(built.raw_prediction_col(), estimator.raw_prediction_col());
+        *estimator.params_mut() = estimator
+            .params()
+            .clone()
+            .set_param_double("smoothing", 0.5);
+        assert_eq!(estimator.smoothing(), 0.5);
+        assert_eq!(built.smoothing(), estimator.smoothing());
+        *estimator.params_mut() = estimator
+            .params()
+            .clone()
+            .set_param_string("modelType", "gaussian");
+        assert_eq!(estimator.model_type(), "gaussian");
+        assert_eq!(built.model_type(), estimator.model_type());
+        *estimator.params_mut() = estimator
+            .params()
+            .clone()
+            .set_param_double_array("thresholds", vec![0.5, 1.5]);
+        assert_eq!(estimator.thresholds(), Some(vec![0.5, 1.5]));
+        assert_eq!(built.thresholds(), estimator.thresholds());
+        *estimator.params_mut() = estimator
+            .params()
+            .clone()
+            .set_param_string("weightCol", "weight");
+        assert_eq!(estimator.weight_col(), Some("weight"));
+        assert_eq!(built.weight_col(), estimator.weight_col());
+        assert_eq!(built.params().to_proto(), estimator.params().to_proto());
+        assert!(estimator.operator_mut().uid.starts_with("NaiveBayes_"));
+    }
+
+    #[test]
+    fn naive_bayes_validates_fitted_references_and_model_metadata() {
+        let session = offline_session();
+        let estimator = NaiveBayes::default().set_prediction_col("class");
+        assert_eq!(
+            estimator.operator().name,
+            "org.apache.spark.ml.classification.NaiveBayes"
+        );
+        assert_eq!(estimator.operator().op_type, OperatorType::Estimator);
+        for kind in [
+            None,
+            Some(proto::ml_command_result::ml_operator_info::Type::Name(
+                "model".into(),
+            )),
+            Some(proto::ml_command_result::ml_operator_info::Type::ObjRef(
+                proto::ObjectRef::default(),
+            )),
+        ] {
+            assert!(estimator
+                .model_from_info(
+                    proto::ml_command_result::MlOperatorInfo {
+                        r#type: kind,
+                        ..Default::default()
+                    },
+                    &session
+                )
+                .is_err());
+        }
+        let info = |uid| proto::ml_command_result::MlOperatorInfo {
+            r#type: 
Some(proto::ml_command_result::ml_operator_info::Type::ObjRef(
+                proto::ObjectRef {
+                    id: "trained-naive-bayes".into(),
+                },
+            )),
+            uid,
+            ..Default::default()
+        };
+        let mut model = estimator
+            .model_from_info(info(Some("returned-uid".into())), &session)
+            .unwrap();
+        assert_eq!(model.operator().uid, "returned-uid");
+        assert_eq!(
+            model.operator().name,
+            "org.apache.spark.ml.classification.NaiveBayesModel"
+        );
+        assert_eq!(model.operator().op_type, OperatorType::Model);
+        let fallback = estimator.model_from_info(info(None), 
&session).unwrap();
+        assert_eq!(fallback.operator().uid, estimator.operator().uid);
+        let df = session.range(2).unwrap();
+        let proto::ml_relation::MlType::Transform(t) =
+            model.build_ml_relation(&df).unwrap().ml_type.unwrap()
+        else {
+            panic!("transform")
+        };
+        assert_eq!(
+            t.operator,
+            Some(proto::ml_relation::transform::Operator::ObjRef(
+                proto::ObjectRef {
+                    id: "trained-naive-bayes".into()
+                }
+            ))
+        );
+        assert_eq!(*t.input.unwrap(), df.relation().unwrap());
+        assert_eq!(t.params.unwrap(), estimator.params().to_proto());
+        assert!(model
+            .transform(&session.new_session().range(2).unwrap())
+            .is_err());
+        assert!(model.clone_box().transform(&df).is_ok());
+    }
     #[test]
     fn 
decision_tree_classifier_validates_fitted_references_and_model_metadata() {
         let session = offline_session();
diff --git a/crates/spark-connect/tests/e2e_naive_bayes.rs 
b/crates/spark-connect/tests/e2e_naive_bayes.rs
new file mode 100644
index 00000000..d50d2fb1
--- /dev/null
+++ b/crates/spark-connect/tests/e2e_naive_bayes.rs
@@ -0,0 +1,264 @@
+//! Native NaiveBayes behaviors. Set SPARK_REMOTE to use a live Connect server.
+mod common;
+
+use common::live_session;
+use spark_connect::column::{col, lit_double, lit_string};
+use spark_connect::expression::Expression;
+use spark_connect::ml::{Estimator, NaiveBayes};
+use spark_connect::{Column, DataFrame, SparkSession};
+
+fn vectors(s: &SparkSession, sql: &str, name: &str) -> DataFrame {
+    s.sql(sql).unwrap().with_column(
+        name,
+        Column::new(Expression::function(
+            "array_to_vector",
+            vec![col("xs").expression().clone()],
+        )),
+    )
+}
+
+fn vector_array(name: &str) -> Column {
+    Column::new(Expression::function(
+        "vector_to_array",
+        vec![
+            col(name).expression().clone(),
+            lit_string("float64").expression().clone(),
+        ],
+    ))
+}
+
+fn predictions(df: DataFrame, name: &str) -> Vec<f64> {
+    df.order_by(vec![col("id").asc().expression().clone()])
+        .select([col(name)])
+        .collect()
+        .unwrap()
+        .into_iter()
+        .map(|r| r.get(0).unwrap().as_f64().unwrap())
+        .collect()
+}
+
+fn list(value: &spark_connect::row::Value) -> &[spark_connect::row::Value] {
+    let spark_connect::row::Value::List(values) = value else {
+        panic!("array result")
+    };
+    values
+}
+
+fn weighted_training(s: &SparkSession) -> DataFrame {
+    vectors(s, "SELECT array(1.0D,1.0D) xs, label, weight FROM VALUES 
(0.0D,1.0D),(1.0D,9.0D) AS t(label,weight)", "features")
+}
+
+#[test]
+fn 
naive_bayes_model_types_learn_multiclass_labels_and_keep_independent_cached_models()
 {
+    let Some(s) = live_session() else {
+        return;
+    };
+    for model_type in ["multinomial", "bernoulli", "complement", "gaussian"] {
+        let (training_sql, test_sql) = match model_type {
+            "gaussian" => (
+                "SELECT target, array(x,y) xs, 1.0D weight FROM VALUES 
(0.0D,-3.0D,-2.0D),(0.0D,-2.0D,-3.0D),(1.0D,2.0D,3.0D),(1.0D,3.0D,2.0D),(2.0D,7.0D,8.0D),(2.0D,8.0D,7.0D)
 AS t(target,x,y)",
+                "SELECT id, array(x,y) xs FROM VALUES 
(0,-2.5D,-2.5D),(1,2.5D,2.5D),(2,7.5D,7.5D) AS t(id,x,y)"),
+            "bernoulli" => (
+                "SELECT target, array(x,y,z) xs, 1.0D weight FROM VALUES 
(0.0D,1.0D,0.0D,0.0D),(0.0D,1.0D,1.0D,0.0D),(1.0D,0.0D,1.0D,0.0D),(1.0D,0.0D,1.0D,1.0D),(2.0D,0.0D,0.0D,1.0D),(2.0D,1.0D,0.0D,1.0D)
 AS t(target,x,y,z)",
+                "SELECT id, array(x,y,z) xs FROM VALUES 
(0,1.0D,0.0D,0.0D),(1,0.0D,1.0D,0.0D),(2,0.0D,0.0D,1.0D) AS t(id,x,y,z)"),
+            _ => (
+                "SELECT target, array(x,y,z) xs, 1.0D weight FROM VALUES 
(0.0D,4.0D,1.0D,0.0D),(0.0D,5.0D,0.0D,1.0D),(1.0D,0.0D,4.0D,1.0D),(1.0D,1.0D,5.0D,0.0D),(2.0D,1.0D,0.0D,4.0D),(2.0D,0.0D,1.0D,5.0D)
 AS t(target,x,y,z)",
+                "SELECT id, array(x,y,z) xs FROM VALUES 
(0,4.0D,0.0D,0.0D),(1,0.0D,4.0D,0.0D),(2,0.0D,0.0D,4.0D) AS t(id,x,y,z)"),
+        };
+        let training = vectors(&s, training_sql, "input");
+        let held_out = vectors(&s, test_sql, "input");
+        let mut estimator = NaiveBayes::new()
+            .set_feature_col("input")
+            .set_label_col("target")
+            .set_prediction_col("class")
+            .set_probability_col("probs")
+            .set_raw_prediction_col("scores")
+            .set_smoothing(0.5)
+            .set_model_type(model_type)
+            .set_thresholds([1.0, 1.0, 1.0])
+            .set_weight_col("weight");
+        let mut first = estimator.fit(&training).unwrap();
+        let mut second = estimator
+            .fit(&training.with_column("target", lit_double(2.0) - 
col("target")))
+            .unwrap();
+        let object_id = |model: &dyn spark_connect::ml::Model| {
+            let spark_connect_proto::ml_relation::MlType::Transform(t) =
+                model.build_ml_relation(&held_out).unwrap().ml_type.unwrap()
+            else {
+                panic!("transform")
+            };
+            let 
Some(spark_connect_proto::ml_relation::transform::Operator::ObjRef(r)) = 
t.operator
+            else {
+                panic!("cached model")
+            };
+            r.id
+        };
+        assert_ne!(object_id(first.as_ref()), object_id(second.as_ref()));
+        assert!(first.transform(&s.new_session().range(1).unwrap()).is_err());
+        let mut cloned = first.clone_box();
+        let lazy = cloned.transform(&held_out).unwrap();
+        drop(first);
+        drop(cloned);
+        assert_eq!(
+            predictions(lazy.clone(), "class"),
+            vec![0.0, 1.0, 2.0],
+            "{model_type}"
+        );
+        assert_eq!(
+            predictions(second.transform(&held_out).unwrap(), "class"),
+            vec![2.0, 1.0, 0.0],
+            "{model_type}"
+        );
+        let rows = lazy
+            .select([vector_array("probs"), vector_array("scores")])
+            .collect()
+            .unwrap();
+        for row in rows {
+            let probabilities = list(row.get(0).unwrap());
+            let raw = list(row.get(1).unwrap());
+            assert_eq!(probabilities.len(), 3);
+            assert_eq!(raw.len(), 3);
+            let values: Vec<f64> = probabilities.iter().map(|v| 
v.as_f64().unwrap()).collect();
+            assert!(values
+                .iter()
+                .all(|p| p.is_finite() && (0.0..=1.0).contains(p)));
+            assert!((values.iter().sum::<f64>() - 1.0).abs() < 1e-10);
+            assert!(raw.iter().all(|v| v.as_f64().unwrap().is_finite()));
+        }
+    }
+}
+
+#[test]
+fn naive_bayes_weights_and_smoothing_produce_the_expected_priors() {
+    let Some(s) = live_session() else {
+        return;
+    };
+    let data = weighted_training(&s);
+    for smoothing in [0.0, 1.0, 10.0] {
+        for weighted in [false, true] {
+            let mut estimator = NaiveBayes::new().set_smoothing(smoothing);
+            if weighted {
+                estimator = estimator.set_weight_col("weight");
+            }
+            let mut model = estimator.fit(&data).unwrap();
+            let rows = model
+                .transform(&data)
+                .unwrap()
+                .select([
+                    col("prediction"),
+                    vector_array("probability"),
+                    vector_array("rawPrediction"),
+                ])
+                .collect()
+                .unwrap();
+            let prior: f64 = if weighted {
+                (1.0 + smoothing) / (10.0 + 2.0 * smoothing)
+            } else {
+                0.5
+            };
+            assert_eq!(
+                rows[0].get(0).unwrap().as_f64().unwrap(),
+                if weighted { 1.0 } else { 0.0 }
+            );
+            let p = list(rows[0].get(1).unwrap());
+            let r = list(rows[0].get(2).unwrap());
+            for (i, expected) in [prior, 1.0 - prior].into_iter().enumerate() {
+                assert!((p[i].as_f64().unwrap() - expected).abs() < 1e-10);
+                assert!(
+                    (r[i].as_f64().unwrap() - (expected.ln() - 2.0 * 
2.0_f64.ln())).abs() < 1e-10
+                );
+            }
+        }
+    }
+}
+
+#[test]
+fn naive_bayes_thresholds_and_optional_vector_outputs() {
+    let Some(s) = live_session() else {
+        return;
+    };
+    let data = weighted_training(&s);
+    let mut normal = NaiveBayes::new()
+        .set_weight_col("weight")
+        .fit(&data)
+        .unwrap();
+    let mut adjusted = NaiveBayes::new()
+        .set_weight_col("weight")
+        .set_thresholds([0.1, 1.0])
+        .fit(&data)
+        .unwrap();
+    let outputs = |model: &mut dyn spark_connect::ml::Model| {
+        model
+            .transform(&data)
+            .unwrap()
+            .select([
+                col("prediction"),
+                vector_array("probability"),
+                vector_array("rawPrediction"),
+            ])
+            .collect()
+            .unwrap()
+    };
+    let a = outputs(normal.as_mut());
+    let b = outputs(adjusted.as_mut());
+    assert_eq!(a[0].get(0).unwrap().as_f64(), Some(1.0));
+    assert_eq!(b[0].get(0).unwrap().as_f64(), Some(0.0));
+    assert_eq!(a[0].get(1), b[0].get(1));
+    assert_eq!(a[0].get(2), b[0].get(2));
+    let mut model = NaiveBayes::new()
+        .set_weight_col("weight")
+        .set_prediction_col("class")
+        .set_probability_col("")
+        .set_raw_prediction_col("")
+        .fit(&data)
+        .unwrap();
+    let transformed = model.transform(&data).unwrap();
+    let names = transformed.columns().unwrap();
+    assert!(!names
+        .iter()
+        .any(|n| n == "probability" || n == "rawPrediction"));
+    assert_eq!(
+        transformed.select([col("class")]).collect().unwrap()[0]
+            .get(0)
+            .unwrap()
+            .as_f64(),
+        Some(1.0)
+    );
+}
+
+#[test]
+fn naive_bayes_rejects_invalid_parameters_and_data() {
+    let Some(s) = live_session() else {
+        return;
+    };
+    let data = weighted_training(&s);
+    for mut estimator in [
+        NaiveBayes::new().set_smoothing(-1.0),
+        NaiveBayes::new().set_model_type("unknown"),
+        NaiveBayes::new().set_thresholds([1.0]),
+    ] {
+        match estimator.fit(&data) {
+            Err(_) => (),
+            Ok(mut model) => assert!(model.transform(&data).and_then(|df| 
df.collect()).is_err()),
+        }
+    }
+    for (model_type, values) in [
+        ("multinomial", "array(-1.0D,1.0D)"),
+        ("complement", "array(-1.0D,1.0D)"),
+        ("bernoulli", "array(2.0D,1.0D)"),
+    ] {
+        let invalid = vectors(
+            &s,
+            &format!("SELECT {values} xs, label FROM VALUES (0.0D),(1.0D) AS 
t(label)"),
+            "features",
+        );
+        assert!(NaiveBayes::new()
+            .set_model_type(model_type)
+            .fit(&invalid)
+            .is_err());
+    }
+    assert!(NaiveBayes::new()
+        .set_weight_col("weight")
+        .fit(&data.with_column("weight", lit_double(-1.0)))
+        .is_err());
+}
diff --git a/crates/spark-connect/tests/naive_bayes_golden.rs 
b/crates/spark-connect/tests/naive_bayes_golden.rs
new file mode 100644
index 00000000..c8768045
--- /dev/null
+++ b/crates/spark-connect/tests/naive_bayes_golden.rs
@@ -0,0 +1,29 @@
+//! Match all NaiveBayes parameters and model types to official PySpark.
+use base64::{engine::general_purpose::STANDARD, Engine};
+use prost::Message;
+use spark_connect::ml::{Estimator, NaiveBayes};
+
+#[test]
+fn naive_bayes_parameters_match_official_pyspark() {
+    let fixture: serde_json::Value =
+        
serde_json::from_str(include_str!("../../../tests/golden/naive_bayes.json")).unwrap();
+    for case in fixture["cases"].as_array().unwrap() {
+        let model_type = case["model_type"].as_str().unwrap();
+        let bytes = STANDARD
+            .decode(case["params_b64"].as_str().unwrap())
+            .unwrap();
+        let expected = 
spark_connect_proto::MlParams::decode(bytes.as_slice()).unwrap();
+        let estimator = NaiveBayes::new()
+            .set_feature_col("input")
+            .set_label_col("target")
+            .set_prediction_col("class")
+            .set_probability_col("probs")
+            .set_raw_prediction_col("scores")
+            .set_smoothing(0.25)
+            .set_model_type(model_type)
+            .set_thresholds([0.25, 0.5, 1.0])
+            .set_weight_col("weight");
+        assert_eq!(estimator.params().to_proto(), expected, "{model_type}");
+    }
+    assert!(NaiveBayes::default().params().to_proto().params.is_empty());
+}
diff --git a/docs/compatibility.md b/docs/compatibility.md
index 29cd5d6b..1a323813 100644
--- a/docs/compatibility.md
+++ b/docs/compatibility.md
@@ -494,3 +494,30 @@ protobuf and prost stop at 100 nested messages. Its Rust 
client enables prost's
 decodes server responses deeper than 100 nested messages, such as the schema 
of a struct nested
 34 levels deep, which PySpark's client rejects with "Exception deserializing 
response!". The
 server is trusted, as SECURITY.md sets out, so this is not a bound on the 
responses.
+
+## Native NaiveBayes
+
+The Rust `ml::NaiveBayes` and `ml::NaiveBayesModel` train and predict through 
Spark
+Connect's cached-model protocol. The Rust-backed Python API exports 
`NaiveBayes`
+from `pyspark.ml.connect` and `pyspark.ml.connect.classification`; `fit` 
returns the
+shared native `MLModel`, whose `transform` produces DataFrame predictions.
+
+All nine PySpark constructor parameters and named setters are supported:
+`featuresCol`, `labelCol`, `predictionCol`, `probabilityCol`, 
`rawPredictionCol`,
+`smoothing`, `modelType`, `thresholds` and `weightCol`. Rust exposes 
corresponding
+builder setters and getters. Unset parameters are omitted so the server uses 
its
+defaults. The Python constructor is keyword-only and converts values with
+PySpark's parameter converters.
+
+All four model types are covered by live tests: `multinomial`, `bernoulli`,
+`complement` and `gaussian`. Multinomial/complement inputs must be nonnegative;
+Bernoulli inputs must be binary; Gaussian inputs may contain continuous 
negative
+values. Tests also cover multiclass dense/sparse inputs, probability/raw score
+columns, smoothing and instance weights, threshold decisions, suppressed vector
+outputs, independent fits, session isolation and lazy model lifetime. A golden
+fixture captures all nine parameters for each model type from official PySpark.
+
+This native surface covers construction, parameter setters, fit and DataFrame
+transform. Model coefficient/statistic inspection, single-vector prediction and
+persistence are outside this surface. The vendored `pyspark.ml.classification`
+API continues to use its existing implementation.
diff --git a/python/pyspark/ml/connect/__init__.py 
b/python/pyspark/ml/connect/__init__.py
index 36e37ea6..167fbfa3 100644
--- a/python/pyspark/ml/connect/__init__.py
+++ b/python/pyspark/ml/connect/__init__.py
@@ -16,6 +16,7 @@ from pyspark.ml.connect.classification import (
     DecisionTreeClassifier,
     LinearSVC,
     LogisticRegression,
+    NaiveBayes,
     RandomForestClassifier,
 )
 from pyspark.ml.connect.regression import (
@@ -56,6 +57,7 @@ __all__ = [
     "StringIndexer",
     "VectorAssembler",
     "LogisticRegression",
+    "NaiveBayes",
     "LinearSVC",
     "DecisionTreeClassifier",
     "GBTClassifier",
diff --git a/python/pyspark/ml/connect/classification.py 
b/python/pyspark/ml/connect/classification.py
index f7ee44f5..45d2b567 100644
--- a/python/pyspark/ml/connect/classification.py
+++ b/python/pyspark/ml/connect/classification.py
@@ -4,7 +4,8 @@ from pyspark._pyspark import (
     GBTClassifier,
     LinearSVC,
     LogisticRegression,
+    NaiveBayes,
     RandomForestClassifier,
 )
 
-__all__ = ["GBTClassifier", "DecisionTreeClassifier", "LinearSVC", 
"LogisticRegression", "RandomForestClassifier"]
+__all__ = ["NaiveBayes", "GBTClassifier", "DecisionTreeClassifier", 
"LinearSVC", "LogisticRegression", "RandomForestClassifier"]
diff --git a/python/tests/test_ml_e2e.py b/python/tests/test_ml_e2e.py
index 2d5af620..c709678d 100644
--- a/python/tests/test_ml_e2e.py
+++ b/python/tests/test_ml_e2e.py
@@ -255,6 +255,7 @@ def _native_estimators():
         LinearSVC,
         LogisticRegression,
         MaxAbsScaler,
+        NaiveBayes,
         RandomForestClassifier,
         RandomForestRegressor,
         StandardScaler,
@@ -263,6 +264,7 @@ def _native_estimators():
 
     ml = "org.apache.spark.ml."
     return [
+        (NaiveBayes(), ml + "classification.NaiveBayesModel"),
         (GBTRegressor(maxIter=2), ml + "regression.GBTRegressionModel"),
         (GBTClassifier(maxIter=2), ml + 
"classification.GBTClassificationModel"),
         (DecisionTreeRegressor(), ml + 
"regression.DecisionTreeRegressionModel"),
diff --git a/python/tests/test_ml_offline.py b/python/tests/test_ml_offline.py
index 4e4d280b..68292648 100644
--- a/python/tests/test_ml_offline.py
+++ b/python/tests/test_ml_offline.py
@@ -483,6 +483,11 @@ _NATIVE_PARAMS = {
         solver="str", weightCol="str", aggregationDepth="int", loss="str", 
epsilon="float",
         maxBlockSizeInMB="float",
     ),
+    "NaiveBayes": dict(
+        featuresCol="str", labelCol="str", predictionCol="str", 
probabilityCol="str",
+        rawPredictionCol="str", smoothing="float", modelType="str",
+        thresholds="float_list", weightCol="str",
+    ),
     "DecisionTreeClassifier": dict(
         featuresCol="str", labelCol="str", predictionCol="str", 
probabilityCol="str",
         rawPredictionCol="str", maxDepth="int", maxBins="int", 
minInstancesPerNode="int",
@@ -2741,6 +2746,64 @@ def 
test_decision_tree_regressor_native_parameters_match_official_fixture(ml_moc
         assert params == 
pb2.MlParams.FromString(base64.b64decode(case["params_b64"]))
 
 
[email protected]("use_setters", [False, True], ids=["constructor", 
"setters"])
+def test_naive_bayes_native_parameters_match_official_fixture(ml_mock, 
use_setters):
+    import base64
+    import inspect
+    import json
+    from pathlib import Path
+
+    from pyspark import _pyspark as native
+    from pyspark.ml.connect import NaiveBayes as exported
+    from pyspark.ml.connect.classification import NaiveBayes
+
+    assert exported is NaiveBayes is native.NaiveBayes
+    defaults = dict(
+        featuresCol="features",
+        labelCol="label",
+        predictionCol="prediction",
+        probabilityCol="probability",
+        rawPredictionCol="rawPrediction",
+        smoothing=1.0,
+        modelType="multinomial",
+        thresholds=None,
+        weightCol=None,
+    )
+    signature = inspect.signature(NaiveBayes)
+    assert list(signature.parameters) == list(defaults)
+    for name, value in defaults.items():
+        assert signature.parameters[name].kind == 
inspect.Parameter.KEYWORD_ONLY
+        assert signature.parameters[name].default == value
+    fixture = json.loads(
+        (Path(__file__).resolve().parents[2] / 
"tests/golden/naive_bayes.json").read_text()
+    )
+    spark, service = ml_mock
+    models = []
+    _, params = _native_request(spark, service, NaiveBayes(), models)
+    assert params == pb2.MlParams()
+    for case in fixture["cases"]:
+        values = dict(
+            featuresCol="input",
+            labelCol="target",
+            predictionCol="class",
+            probabilityCol="probs",
+            rawPredictionCol="scores",
+            smoothing=0.25,
+            modelType=case["model_type"],
+            thresholds=[0.25, 0.5, 1.0],
+            weightCol="weight",
+        )
+        if use_setters:
+            estimator = NaiveBayes()
+            for name, value in values.items():
+                assert getattr(estimator, "set" + name[0].upper() + 
name[1:])(value) is estimator
+        else:
+            estimator = NaiveBayes(**values)
+        operator, params = _native_request(spark, service, estimator, models)
+        assert operator.name == "org.apache.spark.ml.classification.NaiveBayes"
+        assert params == 
pb2.MlParams.FromString(base64.b64decode(case["params_b64"]))
+
+
 @pytest.mark.parametrize("use_setters", [False, True], ids=["constructor", 
"setters"])
 def test_gbt_regressor_native_parameters_match_official_fixture(ml_mock, 
use_setters):
     import base64
diff --git a/python/tests/test_naive_bayes_e2e.py 
b/python/tests/test_naive_bayes_e2e.py
new file mode 100644
index 00000000..a63aa886
--- /dev/null
+++ b/python/tests/test_naive_bayes_e2e.py
@@ -0,0 +1,218 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License.  You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+"""Native NaiveBayes behaviors; the same cases run with official PySpark."""
+
+import gc
+import math
+import os
+
+import pytest
+from pyspark.ml.connect.functions import array_to_vector, vector_to_array
+from pyspark.ml.linalg import Vectors
+from pyspark.sql import SparkSession
+from pyspark.sql import functions as F
+
+
[email protected]
+def session():
+    remote = os.environ.get("SPARK_REMOTE")
+    if not remote:
+        pytest.skip("SPARK_REMOTE is required for live-server tests")
+    spark = SparkSession.builder.remote(remote).getOrCreate()
+    try:
+        yield spark
+    finally:
+        spark.stop()
+
+
+def _classifier():
+    try:
+        from pyspark.ml.connect.classification import NaiveBayes
+    except ImportError:
+        from pyspark.ml.classification import NaiveBayes
+    return NaiveBayes
+
+
+def _vectors(session, sql, name="features"):
+    return session.sql(sql).withColumn(name, array_to_vector("xs"))
+
+
+def _weighted_training(session):
+    return _vectors(
+        session,
+        "SELECT array(1.0D,1.0D) xs, label, weight FROM VALUES "
+        "(0.0D,1.0D),(1.0D,9.0D) AS t(label,weight)",
+    )
+
+
+def _outputs(model, data, prediction="prediction", probability="probability", 
raw="rawPrediction"):
+    return (
+        model.transform(data)
+        .select(
+            prediction, vector_to_array(probability).alias("p"), 
vector_to_array(raw).alias("r")
+        )
+        .collect()
+    )
+
+
[email protected]("model_type", ["multinomial", "bernoulli", 
"complement", "gaussian"])
[email protected]("use_setters", [False, True], ids=["constructor", 
"setters"])
+def test_naive_bayes_learns_multiclass_dense_and_sparse_vectors(session, 
model_type, use_setters):
+    NaiveBayes = _classifier()
+    if model_type == "gaussian":
+        sql = (
+            "SELECT label, array(x,y) xs, 1.0D weight FROM VALUES "
+            + "(0.0D,-3.0D,-2.0D),(0.0D,-2.0D,-3.0D),(1.0D,2.0D,3.0D),"
+            + "(1.0D,3.0D,2.0D),(2.0D,7.0D,8.0D),(2.0D,8.0D,7.0D) AS 
t(label,x,y)"
+        )
+        points = [[-2.5, -2.5], [2.5, 2.5], [7.5, 7.5]]
+    else:
+        values = (
+            
"(0.0D,1.0D,0.0D,0.0D),(0.0D,1.0D,1.0D,0.0D),(1.0D,0.0D,1.0D,0.0D),"
+            + 
"(1.0D,0.0D,1.0D,1.0D),(2.0D,0.0D,0.0D,1.0D),(2.0D,1.0D,0.0D,1.0D)"
+            if model_type == "bernoulli"
+            else 
"(0.0D,4.0D,1.0D,0.0D),(0.0D,5.0D,0.0D,1.0D),(1.0D,0.0D,4.0D,1.0D),"
+            + 
"(1.0D,1.0D,5.0D,0.0D),(2.0D,1.0D,0.0D,4.0D),(2.0D,0.0D,1.0D,5.0D)"
+        )
+        sql = (
+            "SELECT label, array(x,y,z) xs, 1.0D weight FROM VALUES "
+            + values
+            + " AS t(label,x,y,z)"
+        )
+        v = 1.0 if model_type == "bernoulli" else 4.0
+        points = [[v, 0.0, 0.0], [0.0, v, 0.0], [0.0, 0.0, v]]
+    training = _vectors(session, sql, "input").withColumnRenamed("label", 
"target")
+    held_out = session.createDataFrame(
+        [
+            (i, Vectors.sparse(len(x), {j: v for j, v in enumerate(x) if v}))
+            if i % 2
+            else (i, Vectors.dense(x))
+            for i, x in enumerate(points)
+        ],
+        ["id", "input"],
+    )
+    values = dict(
+        featuresCol="input",
+        labelCol="target",
+        predictionCol="class",
+        probabilityCol="probs",
+        rawPredictionCol="scores",
+        smoothing=0.5,
+        modelType=model_type,
+        thresholds=[1.0, 1.0, 1.0],
+        weightCol="weight",
+    )
+    if use_setters:
+        estimator = NaiveBayes()
+        for name, value in values.items():
+            assert getattr(estimator, "set" + name[0].upper() + 
name[1:])(value) is estimator
+    else:
+        estimator = NaiveBayes(**values)
+    model = estimator.fit(training)
+    lazy = (
+        model.transform(held_out)
+        .orderBy("id")
+        .select("class", vector_to_array("probs").alias("p"), 
vector_to_array("scores").alias("r"))
+    )
+    del model, estimator
+    gc.collect()
+    rows = lazy.collect()
+    assert [r[0] for r in rows] == [0.0, 1.0, 2.0]
+    for row in rows:
+        assert len(row.p) == len(row.r) == 3
+        assert all(math.isfinite(x) and 0.0 <= x <= 1.0 for x in row.p)
+        assert all(math.isfinite(x) for x in row.r)
+        assert sum(row.p) == pytest.approx(1.0)
+        assert max(range(3), key=row.p.__getitem__) == row[0]
+
+
[email protected]("smoothing", [0.0, 1.0, 10.0])
+def test_naive_bayes_weights_and_smoothing_change_class_priors(session, 
smoothing):
+    NaiveBayes = _classifier()
+    training = _weighted_training(session)
+    plain = NaiveBayes(smoothing=smoothing).fit(training)
+    weighted = NaiveBayes(smoothing=smoothing, 
weightCol="weight").fit(training)
+    assert _outputs(plain, training)[0].p == pytest.approx([0.5, 0.5])
+    row = _outputs(weighted, training)[0]
+    prior = (1.0 + smoothing) / (10.0 + 2 * smoothing)
+    assert row.p == pytest.approx([prior, 1.0 - prior])
+    assert row[0] == 1.0
+    assert row.r == pytest.approx(
+        [math.log(prior) - 2 * math.log(2), math.log(1 - prior) - 2 * 
math.log(2)]
+    )
+
+
+def 
test_naive_bayes_thresholds_change_prediction_without_changing_probabilities(session):
+    NaiveBayes = _classifier()
+    training = _weighted_training(session)
+    normal = _outputs(NaiveBayes(weightCol="weight").fit(training), 
training)[0]
+    adjusted = _outputs(
+        NaiveBayes(weightCol="weight", thresholds=[0.1, 1.0]).fit(training), 
training
+    )[0]
+    assert normal[0] == 1.0 and adjusted[0] == 0.0
+    assert adjusted.p == pytest.approx(normal.p)
+    assert adjusted.r == pytest.approx(normal.r)
+
+
+def test_naive_bayes_can_disable_vector_outputs(session):
+    training = _weighted_training(session)
+    transformed = (
+        _classifier()(
+            weightCol="weight", predictionCol="class", probabilityCol="", 
rawPredictionCol=""
+        )
+        .fit(training)
+        .transform(training)
+    )
+    assert "probability" not in transformed.columns and "rawPrediction" not in 
transformed.columns
+    assert [r[0] for r in transformed.select("class").collect()] == [1.0, 1.0]
+
+
+def test_naive_bayes_repeated_fits_keep_independent_models(session):
+    training = _weighted_training(session)
+    estimator = _classifier()(weightCol="weight")
+    first = estimator.fit(training)
+    second = estimator.fit(training.withColumn("label", F.lit(1.0) - 
F.col("label")))
+    estimator.setModelType("bernoulli")
+    assert _outputs(first, training)[0][0] == 1.0
+    assert _outputs(second, training)[0][0] == 0.0
+
+
[email protected](
+    "case", ["smoothing", "model_type", "thresholds", "negative", "binary", 
"weight"]
+)
+def test_naive_bayes_rejects_invalid_parameters_and_training_data(session, 
case):
+    NaiveBayes = _classifier()
+    training = _weighted_training(session)
+    estimator = NaiveBayes()
+    if case == "smoothing":
+        estimator.setSmoothing(-1.0)
+    elif case == "model_type":
+        estimator.setModelType("unknown")
+    elif case == "thresholds":
+        estimator.setThresholds([1.0])
+    elif case == "negative":
+        training = training.withColumn(
+            "features", array_to_vector(F.array(F.lit(-1.0), F.lit(1.0)))
+        )
+    elif case == "binary":
+        estimator.setModelType("bernoulli")
+        training = training.withColumn("features", 
array_to_vector(F.array(F.lit(2.0), F.lit(1.0))))
+    else:
+        estimator.setWeightCol("weight")
+        training = training.withColumn("weight", F.lit(-1.0))
+    with pytest.raises(Exception):
+        estimator.fit(training).transform(training).collect()
diff --git a/scripts/capture_naive_bayes_golden.py 
b/scripts/capture_naive_bayes_golden.py
new file mode 100644
index 00000000..359db760
--- /dev/null
+++ b/scripts/capture_naive_bayes_golden.py
@@ -0,0 +1,59 @@
+#!/usr/bin/env python3
+"""Capture NaiveBayes wire parameters using official PySpark 4.3.0."""
+
+import argparse
+import base64
+import json
+from pathlib import Path
+
+from pyspark.ml.classification import NaiveBayes
+from pyspark.ml.connect.serialize import serialize_ml_params
+from pyspark.sql import SparkSession
+
+
+def main():
+    parser = argparse.ArgumentParser(description=__doc__)
+    parser.add_argument("--remote", default="sc://localhost:15002")
+    parser.add_argument("--out", type=Path, 
default=Path("tests/golden/naive_bayes.json"))
+    args = parser.parse_args()
+    spark = SparkSession.builder.remote(args.remote).getOrCreate()
+    spark.release_session_on_close = False
+    try:
+        cases = []
+        for model_type in ["multinomial", "bernoulli", "complement", 
"gaussian"]:
+            estimator = NaiveBayes(
+                featuresCol="input",
+                labelCol="target",
+                predictionCol="class",
+                probabilityCol="probs",
+                rawPredictionCol="scores",
+                smoothing=0.25,
+                modelType=model_type,
+                thresholds=[0.25, 0.5, 1.0],
+                weightCol="weight",
+            )
+            params = serialize_ml_params(estimator, spark.client)
+            cases.append(
+                {
+                    "model_type": model_type,
+                    "params_b64": base64.b64encode(
+                        params.SerializeToString(deterministic=True)
+                    ).decode(),
+                }
+            )
+        args.out.write_text(
+            json.dumps(
+                {
+                    "source": "apache/spark v4.3.0 
pyspark.ml.classification.NaiveBayes",
+                    "cases": cases,
+                },
+                indent=2,
+            )
+            + "\n"
+        )
+    finally:
+        spark.stop()
+
+
+if __name__ == "__main__":
+    main()
diff --git a/tests/golden/naive_bayes.json b/tests/golden/naive_bayes.json
new file mode 100644
index 00000000..f8639972
--- /dev/null
+++ b/tests/golden/naive_bayes.json
@@ -0,0 +1,21 @@
+{
+  "source": "apache/spark v4.3.0 pyspark.ml.classification.NaiveBayes",
+  "cases": [
+    {
+      "model_type": "multinomial",
+      "params_b64": 
"ChYKC2ZlYXR1cmVzQ29sEgdqBWlucHV0ChQKCGxhYmVsQ29sEghqBnRhcmdldAoaCgltb2RlbFR5cGUSDWoLbXVsdGlub21pYWwKGAoNcHJlZGljdGlvbkNvbBIHagVjbGFzcwoZCg5wcm9iYWJpbGl0eUNvbBIHagVwcm9icwocChByYXdQcmVkaWN0aW9uQ29sEghqBnNjb3JlcwoWCglzbW9vdGhpbmcSCVkAAAAAAADQPwo2Cgp0aHJlc2hvbGRzEiiyASUKAkoAEglZAAAAAAAA0D8SCVkAAAAAAADgPxIJWQAAAAAAAPA/ChUKCXdlaWdodENvbBIIagZ3ZWlnaHQ="
+    },
+    {
+      "model_type": "bernoulli",
+      "params_b64": 
"ChYKC2ZlYXR1cmVzQ29sEgdqBWlucHV0ChQKCGxhYmVsQ29sEghqBnRhcmdldAoYCgltb2RlbFR5cGUSC2oJYmVybm91bGxpChgKDXByZWRpY3Rpb25Db2wSB2oFY2xhc3MKGQoOcHJvYmFiaWxpdHlDb2wSB2oFcHJvYnMKHAoQcmF3UHJlZGljdGlvbkNvbBIIagZzY29yZXMKFgoJc21vb3RoaW5nEglZAAAAAAAA0D8KNgoKdGhyZXNob2xkcxIosgElCgJKABIJWQAAAAAAANA/EglZAAAAAAAA4D8SCVkAAAAAAADwPwoVCgl3ZWlnaHRDb2wSCGoGd2VpZ2h0"
+    },
+    {
+      "model_type": "complement",
+      "params_b64": 
"ChYKC2ZlYXR1cmVzQ29sEgdqBWlucHV0ChQKCGxhYmVsQ29sEghqBnRhcmdldAoZCgltb2RlbFR5cGUSDGoKY29tcGxlbWVudAoYCg1wcmVkaWN0aW9uQ29sEgdqBWNsYXNzChkKDnByb2JhYmlsaXR5Q29sEgdqBXByb2JzChwKEHJhd1ByZWRpY3Rpb25Db2wSCGoGc2NvcmVzChYKCXNtb290aGluZxIJWQAAAAAAANA/CjYKCnRocmVzaG9sZHMSKLIBJQoCSgASCVkAAAAAAADQPxIJWQAAAAAAAOA/EglZAAAAAAAA8D8KFQoJd2VpZ2h0Q29sEghqBndlaWdodA=="
+    },
+    {
+      "model_type": "gaussian",
+      "params_b64": 
"ChYKC2ZlYXR1cmVzQ29sEgdqBWlucHV0ChQKCGxhYmVsQ29sEghqBnRhcmdldAoXCgltb2RlbFR5cGUSCmoIZ2F1c3NpYW4KGAoNcHJlZGljdGlvbkNvbBIHagVjbGFzcwoZCg5wcm9iYWJpbGl0eUNvbBIHagVwcm9icwocChByYXdQcmVkaWN0aW9uQ29sEghqBnNjb3JlcwoWCglzbW9vdGhpbmcSCVkAAAAAAADQPwo2Cgp0aHJlc2hvbGRzEiiyASUKAkoAEglZAAAAAAAA0D8SCVkAAAAAAADgPxIJWQAAAAAAAPA/ChUKCXdlaWdodENvbBIIagZ3ZWlnaHQ="
+    }
+  ]
+}


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

Reply via email to