This is an automated email from the ASF dual-hosted git repository.

HyukjinKwon pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/spark-connect-rust.git


The following commit(s) were added to refs/heads/master by this push:
     new 4553a556 [SPARK-61602][CONNECT] Support native 
GeneralizedLinearRegression training and prediction
4553a556 is described below

commit 4553a556e906aaea43d25af495809cc9f75c76c8
Author: Ruifeng Zheng <[email protected]>
AuthorDate: Fri Nov 13 10:51:21 2026 +0900

    [SPARK-61602][CONNECT] Support native GeneralizedLinearRegression training 
and prediction
    
    ### What changes were proposed in this pull request?
    
    Add `spark_connect::ml::GeneralizedLinearRegression` and its fitted model, 
plus the native Python estimator at 
`pyspark.ml.connect.regression.GeneralizedLinearRegression` (also exported from 
`pyspark.ml.connect`).
    
    The estimator supports all 16 PySpark constructor parameters, typed Rust 
setters/getters, named Python setters, and Spark Connect fitting. Fitted models 
produce DataFrame predictions and the optional `linkPredictionCol`, using the 
shared cached-model ownership and session checks. Add official parameter 
goldens, numerical tests, CI wiring and compatibility documentation.
    
    ### Why are the changes needed?
    
    The native ML APIs lack generalized linear regression. This enables 
Gaussian, binomial, Poisson, Gamma and Tweedie regression, including instance 
weights, offsets and L2 regularization, through Spark's JVM implementation.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes. Rust and native Python users can construct, configure, fit and 
transform with `GeneralizedLinearRegression`. Unset optional parameters 
preserve Spark's family-dependent defaults. Python `fit` returns the existing 
native `MLModel`.
    
    This addition covers estimator construction, parameters, fitting and 
DataFrame transforms. Coefficient/intercept access, summaries, evaluation, 
persistence and single-vector prediction remain outside this native API.
    
    ### How was this patch tested?
    
    - 643 Rust unit tests passed; all integration tests compile with and 
without `wasm-udf`.
    - Five live Rust tests and the official PySpark parameter golden passed 
against Spark 4.3.0.
    - The same 22 numerical cases passed with official PySpark and the native 
Python client, covering all five families, default/explicit links, dense/sparse 
vectors, offsets, weights, regularization, independent models, lazy predictions 
and rejected inputs. Two shared model-lifetime/session tests also passed (24 
native live tests total).
    - 2,087 Python offline tests passed, with 8 skips and 14 passing subtests. 
The native constructor order/defaults and all 16 named setters match official 
PySpark; the SQL API introspection check found zero missing public members 
beyond the documented transport-internal exclusions.
    - Official Spark 4.3 Connect transport suite: 2,638 passed, 589 skipped 
across 87 files; zero unexpected failures.
    - `cargo fmt`, Ruff lint/format and whitespace checks passed. Clippy passed 
for the core library and new Rust test targets. Workspace/Python Clippy still 
reports errors at code unchanged from the base commit; no reported error site 
is changed by this PR.
    
    ### 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 #594 from zhengruifeng/add-generalized-linear-regression.
    
    Lead-authored-by: Ruifeng Zheng <[email protected]>
    Co-authored-by: Hyukjin Kwon <[email protected]>
    Signed-off-by: Hyukjin Kwon <[email protected]>
---
 .github/workflows/build_python_connect.yml         |   4 +-
 crates/pyspark-rs/src/lib.rs                       |   1 +
 crates/pyspark-rs/src/ml.rs                        | 191 +++++++++-
 crates/spark-connect/src/ml.rs                     | 424 +++++++++++++++++++++
 .../tests/e2e_generalized_linear_regression.rs     | 283 ++++++++++++++
 .../tests/generalized_linear_regression_golden.rs  |  39 ++
 docs/compatibility.md                              |  29 +-
 python/pyspark/ml/connect/__init__.py              |   2 +
 python/pyspark/ml/connect/regression.py            |  10 +-
 .../test_generalized_linear_regression_e2e.py      | 209 ++++++++++
 python/tests/test_ml_e2e.py                        |   2 +
 python/tests/test_ml_offline.py                    |  34 ++
 ...capture_generalized_linear_regression_golden.py |  70 ++++
 tests/golden/generalized_linear_regression.json    |  30 ++
 14 files changed, 1320 insertions(+), 8 deletions(-)

diff --git a/.github/workflows/build_python_connect.yml 
b/.github/workflows/build_python_connect.yml
index 8e592076..7fdf98a3 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 -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 -q
 
       - name: Restart Connect server in local-cluster mode
         # Resource profiles and artifact distribution across executors can 
only be
@@ -556,7 +556,7 @@ jobs:
         run: |
           cargo test -p apache-spark-connect \
             --test e2e_functions --test e2e_columns --test e2e_dataframe \
-            --test e2e_coverage --test e2e_linear_svc --test 
e2e_linear_regression --test e2e_kmeans --test e2e_bisecting_kmeans --test 
e2e_gaussian_mixture --test e2e_decision_tree_regressor --test 
e2e_decision_tree_classifier --test e2e_gbt_regressor --test e2e_naive_bayes 
--test e2e_gbt_classifier --test e2e_random_forest --test 
e2e_random_forest_regressor --test e2e_integration \
+            --test e2e_coverage --test e2e_linear_svc --test 
e2e_linear_regression --test e2e_generalized_linear_regression --test 
e2e_kmeans --test e2e_bisecting_kmeans --test e2e_gaussian_mixture --test 
e2e_decision_tree_regressor --test e2e_decision_tree_classifier --test 
e2e_gbt_regressor --test e2e_naive_bayes --test e2e_gbt_classifier --test 
e2e_random_forest --test e2e_random_forest_regressor --test e2e_integration \
             --test arrow_map_input --test array_literal --test 
execute_plan_hook --test raw_relation \
             --test types_roundtrip \
             --test e2e_reattach_drop \
diff --git a/crates/pyspark-rs/src/lib.rs b/crates/pyspark-rs/src/lib.rs
index cad4db41..1a29f76f 100644
--- a/crates/pyspark-rs/src/lib.rs
+++ b/crates/pyspark-rs/src/lib.rs
@@ -245,6 +245,7 @@ fn _pyspark(_py: Python<'_>, m: &Bound<'_, PyModule>) -> 
PyResult<()> {
     m.add_class::<ml::PyLogisticRegression>()?;
     m.add_class::<ml::PyLinearSVC>()?;
     m.add_class::<ml::PyLinearRegression>()?;
+    m.add_class::<ml::PyGeneralizedLinearRegression>()?;
     m.add_class::<ml::PyDecisionTreeClassifier>()?;
     m.add_class::<ml::PyNaiveBayes>()?;
     m.add_class::<ml::PyGBTClassifier>()?;
diff --git a/crates/pyspark-rs/src/ml.rs b/crates/pyspark-rs/src/ml.rs
index 2889b0fb..e66b50e6 100644
--- a/crates/pyspark-rs/src/ml.rs
+++ b/crates/pyspark-rs/src/ml.rs
@@ -18,10 +18,10 @@ use pyo3::PyClass;
 use spark_connect::ml::{
     BinaryClassificationEvaluator, BisectingKMeans, CrossValidator, 
DecisionTreeClassifier,
     DecisionTreeRegressor, Estimator, Evaluator, GBTClassifier, GBTRegressor, 
GaussianMixture,
-    KMeans, LinearRegression, LinearSVC, LogisticRegression, MaxAbsScaler, 
MlOperator, Model,
-    MulticlassClassificationEvaluator, NaiveBayes, Params, Pipeline, 
RandomForestClassifier,
-    RandomForestRegressor, RegressionEvaluator, StandardScaler, StringIndexer, 
Transformer,
-    VectorAssembler,
+    GeneralizedLinearRegression, KMeans, LinearRegression, LinearSVC, 
LogisticRegression,
+    MaxAbsScaler, MlOperator, Model, MulticlassClassificationEvaluator, 
NaiveBayes, Params,
+    Pipeline, RandomForestClassifier, RandomForestRegressor, 
RegressionEvaluator, StandardScaler,
+    StringIndexer, Transformer, VectorAssembler,
 };
 use spark_connect::DataFrame;
 
@@ -1542,6 +1542,188 @@ impl PyLinearRegression {
     }
 }
 
+/// Generalized linear regression fitted and cached by Spark Connect.
+#[pyclass(
+    name = "GeneralizedLinearRegression",
+    module = "pyspark.ml.connect.regression"
+)]
+pub struct PyGeneralizedLinearRegression {
+    inner: GeneralizedLinearRegression,
+    unsendable: Vec<&'static str>,
+}
+
+const GENERALIZED_LINEAR_REGRESSION_PARAMS: &[(&str, Kind)] = &[
+    ("labelCol", Kind::Str),
+    ("featuresCol", Kind::Str),
+    ("predictionCol", Kind::Str),
+    ("family", Kind::Str),
+    ("link", Kind::Str),
+    ("fitIntercept", Kind::Bool),
+    ("maxIter", Kind::Int),
+    ("tol", Kind::Float),
+    ("regParam", Kind::Float),
+    ("weightCol", Kind::Str),
+    ("solver", Kind::Str),
+    ("linkPredictionCol", Kind::Str),
+    ("variancePower", Kind::Float),
+    ("linkPower", Kind::Float),
+    ("offsetCol", Kind::Str),
+    ("aggregationDepth", Kind::Int),
+];
+
+#[pymethods]
+impl PyGeneralizedLinearRegression {
+    #[new]
+    #[pyo3(signature = (*args, **kwargs), text_signature = "(*, 
labelCol='label', featuresCol='features', predictionCol='prediction', 
family='gaussian', link=None, fitIntercept=True, maxIter=25, tol=1e-06, 
regParam=0.0, weightCol=None, solver='irls', linkPredictionCol=None, 
variancePower=0.0, linkPower=None, offsetCol=None, aggregationDepth=2)")]
+    fn new(args: &Bound<'_, PyTuple>, kwargs: Option<&Bound<'_, PyDict>>) -> 
PyResult<Self> {
+        let mut this = Self {
+            inner: GeneralizedLinearRegression::new(),
+            unsendable: Vec::new(),
+        };
+        init_params(
+            &mut this,
+            "GeneralizedLinearRegression",
+            &[],
+            GENERALIZED_LINEAR_REGRESSION_PARAMS,
+            args,
+            kwargs,
+        )?;
+        Ok(this)
+    }
+
+    #[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 = "setFeaturesCol")]
+    fn set_feature_col<'py>(
+        slf: Bound<'py, Self>,
+        value: &Bound<'py, PyAny>,
+    ) -> PyResult<Bound<'py, Self>> {
+        set_param(slf, "featuresCol", Kind::Str, value)
+    }
+
+    #[pyo3(name = "setPredictionCol")]
+    fn set_prediction_col<'py>(
+        slf: Bound<'py, Self>,
+        value: &Bound<'py, PyAny>,
+    ) -> PyResult<Bound<'py, Self>> {
+        set_param(slf, "predictionCol", Kind::Str, value)
+    }
+
+    #[pyo3(name = "setFamily")]
+    fn set_family<'py>(
+        slf: Bound<'py, Self>,
+        value: &Bound<'py, PyAny>,
+    ) -> PyResult<Bound<'py, Self>> {
+        set_param(slf, "family", Kind::Str, value)
+    }
+
+    #[pyo3(name = "setLink")]
+    fn set_link<'py>(
+        slf: Bound<'py, Self>,
+        value: &Bound<'py, PyAny>,
+    ) -> PyResult<Bound<'py, Self>> {
+        set_param(slf, "link", Kind::Str, value)
+    }
+
+    #[pyo3(name = "setFitIntercept")]
+    fn set_fit_intercept<'py>(
+        slf: Bound<'py, Self>,
+        value: &Bound<'py, PyAny>,
+    ) -> PyResult<Bound<'py, Self>> {
+        set_param(slf, "fitIntercept", Kind::Bool, 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 = "setTol")]
+    fn set_tol<'py>(
+        slf: Bound<'py, Self>,
+        value: &Bound<'py, PyAny>,
+    ) -> PyResult<Bound<'py, Self>> {
+        set_param(slf, "tol", Kind::Float, value)
+    }
+
+    #[pyo3(name = "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 = "setWeightCol")]
+    fn set_weight_col<'py>(
+        slf: Bound<'py, Self>,
+        value: &Bound<'py, PyAny>,
+    ) -> PyResult<Bound<'py, Self>> {
+        set_param(slf, "weightCol", Kind::Str, value)
+    }
+
+    #[pyo3(name = "setSolver")]
+    fn set_solver<'py>(
+        slf: Bound<'py, Self>,
+        value: &Bound<'py, PyAny>,
+    ) -> PyResult<Bound<'py, Self>> {
+        set_param(slf, "solver", Kind::Str, value)
+    }
+
+    #[pyo3(name = "setLinkPredictionCol")]
+    fn set_link_prediction_col<'py>(
+        slf: Bound<'py, Self>,
+        value: &Bound<'py, PyAny>,
+    ) -> PyResult<Bound<'py, Self>> {
+        set_param(slf, "linkPredictionCol", Kind::Str, value)
+    }
+
+    #[pyo3(name = "setVariancePower")]
+    fn set_variance_power<'py>(
+        slf: Bound<'py, Self>,
+        value: &Bound<'py, PyAny>,
+    ) -> PyResult<Bound<'py, Self>> {
+        set_param(slf, "variancePower", Kind::Float, value)
+    }
+
+    #[pyo3(name = "setLinkPower")]
+    fn set_link_power<'py>(
+        slf: Bound<'py, Self>,
+        value: &Bound<'py, PyAny>,
+    ) -> PyResult<Bound<'py, Self>> {
+        set_param(slf, "linkPower", Kind::Float, value)
+    }
+
+    #[pyo3(name = "setOffsetCol")]
+    fn set_offset_col<'py>(
+        slf: Bound<'py, Self>,
+        value: &Bound<'py, PyAny>,
+    ) -> PyResult<Bound<'py, Self>> {
+        set_param(slf, "offsetCol", Kind::Str, value)
+    }
+
+    #[pyo3(name = "setAggregationDepth")]
+    fn set_aggregation_depth<'py>(
+        slf: Bound<'py, Self>,
+        value: &Bound<'py, PyAny>,
+    ) -> PyResult<Bound<'py, Self>> {
+        set_param(slf, "aggregationDepth", Kind::Int, value)
+    }
+
+    fn fit(slf: &Bound<'_, Self>, dataset: &Bound<'_, PyAny>) -> 
PyResult<PyMLModel> {
+        fit_native(slf, dataset, None)
+    }
+}
+
 /// Decision tree classifier fitted and cached by Spark Connect.
 #[pyclass(
     name = "DecisionTreeClassifier",
@@ -3657,6 +3839,7 @@ native!(
     PyLogisticRegression => LogisticRegression,
     PyLinearSVC => LinearSVC,
     PyLinearRegression => LinearRegression,
+    PyGeneralizedLinearRegression => GeneralizedLinearRegression,
     PyDecisionTreeClassifier => DecisionTreeClassifier,
     PyNaiveBayes => NaiveBayes,
     PyGBTClassifier => GBTClassifier,
diff --git a/crates/spark-connect/src/ml.rs b/crates/spark-connect/src/ml.rs
index 0835c973..a8740bba 100644
--- a/crates/spark-connect/src/ml.rs
+++ b/crates/spark-connect/src/ml.rs
@@ -1874,6 +1874,296 @@ impl Model for LinearRegressionModel {
     }
 }
 
+/// Generalized linear regression using Spark's JVM implementation and ML 
vector features.
+///
+/// Supports Gaussian, binomial, Poisson, Gamma and Tweedie families.
+/// Unset parameters, including the family-dependent link, use Spark's 
defaults.
+#[derive(Debug, Clone)]
+pub struct GeneralizedLinearRegression {
+    operator: MlOperator,
+    params: Params,
+}
+
+impl GeneralizedLinearRegression {
+    pub fn new() -> Self {
+        Self {
+            operator: MlOperator::new(
+                "org.apache.spark.ml.regression.GeneralizedLinearRegression",
+                OperatorType::Estimator,
+            ),
+            params: Params::new(),
+        }
+    }
+
+    /// Numeric label column.
+    pub fn set_label_col(mut self, value: &str) -> Self {
+        self.params = self.params.set_param_string("labelCol", value);
+        self
+    }
+
+    /// Feature vector column.
+    pub fn set_feature_col(mut self, value: &str) -> Self {
+        self.params = self.params.set_param_string("featuresCol", value);
+        self
+    }
+
+    /// Prediction output column.
+    pub fn set_prediction_col(mut self, value: &str) -> Self {
+        self.params = self.params.set_param_string("predictionCol", value);
+        self
+    }
+
+    /// Distribution: gaussian, binomial, poisson, gamma or tweedie.
+    pub fn set_family(mut self, value: &str) -> Self {
+        self.params = self.params.set_param_string("family", value);
+        self
+    }
+
+    /// Link function; when unset, Spark chooses the family default.
+    pub fn set_link(mut self, value: &str) -> Self {
+        self.params = self.params.set_param_string("link", value);
+        self
+    }
+
+    /// Whether to fit an intercept.
+    pub fn set_fit_intercept(mut self, value: bool) -> Self {
+        self.params = self.params.set_param_bool("fitIntercept", value);
+        self
+    }
+
+    /// Maximum number of IRLS iterations.
+    pub fn set_max_iter(mut self, value: i32) -> Self {
+        self.params = self.params.set_param_int32("maxIter", value);
+        self
+    }
+
+    /// Convergence tolerance.
+    pub fn set_tol(mut self, value: f64) -> Self {
+        self.params = self.params.set_param_double("tol", value);
+        self
+    }
+
+    /// L2 regularization strength.
+    pub fn set_reg_param(mut self, value: f64) -> Self {
+        self.params = self.params.set_param_double("regParam", 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
+    }
+
+    /// Solver algorithm: irls.
+    pub fn set_solver(mut self, value: &str) -> Self {
+        self.params = self.params.set_param_string("solver", value);
+        self
+    }
+
+    /// Optional output column for the linear predictor.
+    pub fn set_link_prediction_col(mut self, value: &str) -> Self {
+        self.params = self.params.set_param_string("linkPredictionCol", value);
+        self
+    }
+
+    /// Tweedie variance power: 0 or a value at least 1.
+    pub fn set_variance_power(mut self, value: f64) -> Self {
+        self.params = self.params.set_param_double("variancePower", value);
+        self
+    }
+
+    /// Tweedie link power; when unset, Spark uses 1 - variancePower.
+    pub fn set_link_power(mut self, value: f64) -> Self {
+        self.params = self.params.set_param_double("linkPower", value);
+        self
+    }
+
+    /// Optional offset column, added to the linear predictor.
+    pub fn set_offset_col(mut self, value: &str) -> Self {
+        self.params = self.params.set_param_string("offsetCol", value);
+        self
+    }
+
+    /// Tree aggregation depth.
+    pub fn set_aggregation_depth(mut self, value: i32) -> Self {
+        self.params = self.params.set_param_int32("aggregationDepth", value);
+        self
+    }
+
+    /// Numeric label column.
+    pub fn label_col(&self) -> &str {
+        self.params.string_or("labelCol", "label")
+    }
+
+    /// Feature vector column.
+    pub fn feature_col(&self) -> &str {
+        self.params.string_or("featuresCol", "features")
+    }
+
+    /// Prediction output column.
+    pub fn prediction_col(&self) -> &str {
+        self.params.string_or("predictionCol", "prediction")
+    }
+
+    /// Distribution: gaussian, binomial, poisson, gamma or tweedie.
+    pub fn family(&self) -> &str {
+        self.params.string_or("family", "gaussian")
+    }
+
+    /// Link function; when unset, Spark chooses the family default.
+    pub fn link(&self) -> Option<&str> {
+        self.params.string_opt("link")
+    }
+
+    /// Whether to fit an intercept.
+    pub fn fit_intercept(&self) -> bool {
+        self.params.bool_or("fitIntercept", true)
+    }
+
+    /// Maximum number of IRLS iterations.
+    pub fn max_iter(&self) -> i32 {
+        self.params.int_or("maxIter", 25)
+    }
+
+    /// Convergence tolerance.
+    pub fn tol(&self) -> f64 {
+        self.params.double_or("tol", 1e-06)
+    }
+
+    /// L2 regularization strength.
+    pub fn reg_param(&self) -> f64 {
+        self.params.double_or("regParam", 0.0)
+    }
+
+    /// Optional instance weight column.
+    pub fn weight_col(&self) -> Option<&str> {
+        self.params.string_opt("weightCol")
+    }
+
+    /// Solver algorithm: irls.
+    pub fn solver(&self) -> &str {
+        self.params.string_or("solver", "irls")
+    }
+
+    /// Optional output column for the linear predictor.
+    pub fn link_prediction_col(&self) -> Option<&str> {
+        self.params.string_opt("linkPredictionCol")
+    }
+
+    /// Tweedie variance power: 0 or a value at least 1.
+    pub fn variance_power(&self) -> f64 {
+        self.params.double_or("variancePower", 0.0)
+    }
+
+    /// Tweedie link power; when unset, Spark uses 1 - variancePower.
+    pub fn link_power(&self) -> Option<f64> {
+        use proto::expression::literal::LiteralType as L;
+        match self.params.literal("linkPower") {
+            Some(L::Double(value)) => Some(*value),
+            Some(L::Integer(value)) => Some(f64::from(*value)),
+            Some(L::Long(value)) => Some(*value as f64),
+            _ => None,
+        }
+    }
+
+    /// Optional offset column, added to the linear predictor.
+    pub fn offset_col(&self) -> Option<&str> {
+        self.params.string_opt("offsetCol")
+    }
+
+    /// Tree aggregation depth.
+    pub fn aggregation_depth(&self) -> i32 {
+        self.params.int_or("aggregationDepth", 2)
+    }
+
+    fn model_from_info(
+        &self,
+        info: proto::ml_command_result::MlOperatorInfo,
+        session: &SparkSession,
+    ) -> spark_connect_core::error::Result<GeneralizedLinearRegressionModel> {
+        let cached = CachedModel::from_info(&info, session, 
"GeneralizedLinearRegression")?;
+        Ok(GeneralizedLinearRegressionModel {
+            operator: MlOperator::with_uid(
+                
"org.apache.spark.ml.regression.GeneralizedLinearRegressionModel",
+                info.uid.as_deref().unwrap_or(&self.operator.uid),
+                OperatorType::Model,
+            ),
+            params: self.params.clone(),
+            cached,
+        })
+    }
+}
+
+impl Default for GeneralizedLinearRegression {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl Estimator for GeneralizedLinearRegression {
+    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 generalized linear regression model fitted by Spark Connect.
+///
+/// Obtain it through [`Estimator::fit`]. The model, its clones and transformed
+/// DataFrames retain the server-cached object until the last owner is dropped.
+#[derive(Debug, Clone)]
+pub struct GeneralizedLinearRegressionModel {
+    operator: MlOperator,
+    params: Params,
+    cached: CachedModel,
+}
+
+impl Transformer for GeneralizedLinearRegressionModel {
+    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 GeneralizedLinearRegressionModel {
+    fn clone_box(&self) -> Box<dyn Model> {
+        Box::new(self.clone())
+    }
+}
+
 /// Decision tree classification using Spark's JVM implementation and ML 
vector features.
 ///
 /// Supports binary and multiclass labels. Unset parameters use Spark's 
defaults. A single
@@ -5979,6 +6269,140 @@ mod tests {
         assert!(model.clone_box().transform(&df).is_ok());
     }
 
+    #[test]
+    fn 
generalized_linear_regression_model_validates_the_reference_and_retains_its_metadata()
 {
+        let session = offline_session();
+        let estimator = 
GeneralizedLinearRegression::default().set_prediction_col("pred");
+        assert_eq!(
+            estimator.operator().name,
+            "org.apache.spark.ml.regression.GeneralizedLinearRegression"
+        );
+        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 mut model = estimator
+            .model_from_info(
+                proto::ml_command_result::MlOperatorInfo {
+                    r#type: 
Some(proto::ml_command_result::ml_operator_info::Type::ObjRef(
+                        proto::ObjectRef {
+                            id: "trained-model".into(),
+                        },
+                    )),
+                    uid: Some("returned-uid".into()),
+                    ..Default::default()
+                },
+                &session,
+            )
+            .unwrap();
+        assert_eq!(model.operator().uid, "returned-uid");
+        assert_eq!(
+            model.operator().name,
+            "org.apache.spark.ml.regression.GeneralizedLinearRegressionModel"
+        );
+        assert_eq!(model.operator().op_type, OperatorType::Model);
+        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-model".into()
+                }
+            ))
+        );
+        assert_eq!(*t.input.unwrap(), df.relation().unwrap());
+        assert!(t.params.unwrap().params.contains_key("predictionCol"));
+        assert!(model
+            .transform(&session.new_session().range(2).unwrap())
+            .is_err());
+        assert!(model.clone_box().transform(&df).is_ok());
+    }
+
+    #[test]
+    fn generalized_linear_regression_getters_follow_defaults_and_params() {
+        let defaults = GeneralizedLinearRegression::default();
+        assert_eq!(defaults.label_col(), "label");
+        assert_eq!(defaults.feature_col(), "features");
+        assert_eq!(defaults.prediction_col(), "prediction");
+        assert_eq!(defaults.family(), "gaussian");
+        assert_eq!(defaults.link(), None);
+        assert_eq!(defaults.fit_intercept(), true);
+        assert_eq!(defaults.max_iter(), 25);
+        assert_eq!(defaults.tol(), 1e-06);
+        assert_eq!(defaults.reg_param(), 0.0);
+        assert_eq!(defaults.weight_col(), None);
+        assert_eq!(defaults.solver(), "irls");
+        assert_eq!(defaults.link_prediction_col(), None);
+        assert_eq!(defaults.variance_power(), 0.0);
+        assert_eq!(defaults.link_power(), None);
+        assert_eq!(defaults.offset_col(), None);
+        assert_eq!(defaults.aggregation_depth(), 2);
+        let mut configured = GeneralizedLinearRegression::new()
+            .set_label_col("target")
+            .set_feature_col("input")
+            .set_prediction_col("pred")
+            .set_family("tweedie")
+            .set_link("log")
+            .set_fit_intercept(false)
+            .set_max_iter(50)
+            .set_tol(1e-08)
+            .set_reg_param(0.25)
+            .set_weight_col("weight")
+            .set_solver("irls")
+            .set_link_prediction_col("eta")
+            .set_variance_power(1.5)
+            .set_link_power(0.0)
+            .set_offset_col("offset")
+            .set_aggregation_depth(3);
+        assert_eq!(configured.label_col(), "target");
+        assert_eq!(configured.feature_col(), "input");
+        assert_eq!(configured.prediction_col(), "pred");
+        assert_eq!(configured.family(), "tweedie");
+        assert_eq!(configured.link(), Some("log"));
+        assert_eq!(configured.fit_intercept(), false);
+        assert_eq!(configured.max_iter(), 50);
+        assert_eq!(configured.tol(), 1e-08);
+        assert_eq!(configured.reg_param(), 0.25);
+        assert_eq!(configured.weight_col(), Some("weight"));
+        assert_eq!(configured.solver(), "irls");
+        assert_eq!(configured.link_prediction_col(), Some("eta"));
+        assert_eq!(configured.variance_power(), 1.5);
+        assert_eq!(configured.link_power(), Some(0.0));
+        assert_eq!(configured.offset_col(), Some("offset"));
+        assert_eq!(configured.aggregation_depth(), 3);
+        *configured.params_mut() = Params::new()
+            .set_param_string("family", "poisson")
+            .set_param_int("linkPower", -1)
+            .set_param_null("link");
+        assert_eq!(configured.family(), "poisson");
+        assert_eq!(configured.link_power(), Some(-1.0));
+        assert_eq!(configured.link(), None);
+        *configured.params_mut() = Params::new().set_param_int32("linkPower", 
2);
+        assert_eq!(configured.link_power(), Some(2.0));
+        *configured.params_mut() = Params::new().set_param_null("linkPower");
+        assert_eq!(configured.link_power(), None);
+    }
+
     #[test]
     fn bisecting_kmeans_getters_follow_defaults_builders_and_mutable_params() {
         let mut estimator = BisectingKMeans::default();
diff --git a/crates/spark-connect/tests/e2e_generalized_linear_regression.rs 
b/crates/spark-connect/tests/e2e_generalized_linear_regression.rs
new file mode 100644
index 00000000..cbf006f4
--- /dev/null
+++ b/crates/spark-connect/tests/e2e_generalized_linear_regression.rs
@@ -0,0 +1,283 @@
+//! Numerical tests of native GeneralizedLinearRegression. Set SPARK_REMOTE to 
use a live server.
+mod common;
+
+use common::live_session;
+use spark_connect::column::{col, lit};
+use spark_connect::expression::Expression;
+use spark_connect::ml::{Estimator, Evaluator, GeneralizedLinearRegression, 
RegressionEvaluator};
+use spark_connect::{Column, DataFrame};
+
+fn vectorize(df: DataFrame, name: &str) -> DataFrame {
+    df.with_column(
+        name,
+        Column::new(Expression::function(
+            "array_to_vector",
+            vec![col("xs").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 assert_close(actual: Vec<f64>, expected: &[f64], tolerance: f64) {
+    assert_eq!(actual.len(), expected.len());
+    for (a, e) in actual.into_iter().zip(expected) {
+        assert!((a - e).abs() < tolerance, "expected {e}, got {a}");
+    }
+}
+
+#[test]
+fn 
generalized_linear_regression_fits_different_lines_and_keeps_lazy_predictions_alive()
 {
+    let Some(s) = live_session() else {
+        return;
+    };
+    let training = vectorize(
+        s.sql(
+            "SELECT array(CAST(x AS DOUBLE)) AS xs, CAST(2*x+3 AS DOUBLE) AS 
target, 1.0D AS weight
+         FROM VALUES (-4), (-3), (-2), (-1), (1), (2), (3), (4) AS t(x)",
+        )
+        .unwrap(),
+        "input",
+    );
+    let held_out = vectorize(
+        s.sql(
+            "SELECT id, array(CAST(x AS DOUBLE)) AS xs, CAST(2*x+3 AS DOUBLE) 
AS target
+         FROM VALUES (0, -1.5), (1, 0.5), (2, 4.5) AS t(id, x)",
+        )
+        .unwrap(),
+        "input",
+    );
+    let mut estimator = GeneralizedLinearRegression::new()
+        .set_feature_col("input")
+        .set_label_col("target")
+        .set_prediction_col("pred")
+        .set_max_iter(100)
+        .set_reg_param(0.0)
+        .set_tol(1e-8)
+        .set_fit_intercept(true)
+        .set_solver("irls")
+        .set_weight_col("weight")
+        .set_aggregation_depth(2);
+    let mut first = estimator.fit(&training).unwrap();
+    let mut second = estimator
+        .fit(&training.with_column("target", lit(10) - 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()));
+    let mut cloned = first.clone_box();
+    let delayed =
+        first
+            .transform(&held_out)
+            .unwrap()
+            .select([col("id"), col("target"), col("pred")]);
+    drop(first);
+    assert_close(
+        predictions(cloned.transform(&held_out).unwrap(), "pred"),
+        &[0.0, 4.0, 12.0],
+        1e-6,
+    );
+    drop(cloned);
+    assert_close(
+        predictions(delayed.clone(), "pred"),
+        &[0.0, 4.0, 12.0],
+        1e-6,
+    );
+    let rmse = RegressionEvaluator::new()
+        .set_label_col("target")
+        .set_prediction_col("pred")
+        .set_metric_name("rmse")
+        .evaluate(&delayed)
+        .unwrap();
+    assert!(rmse < 1e-6, "RMSE {rmse}");
+    assert_close(
+        predictions(second.transform(&held_out).unwrap(), "pred"),
+        &[10.0, 6.0, -2.0],
+        1e-6,
+    );
+    assert!(second
+        .transform(&s.new_session().range(1).unwrap())
+        .is_err());
+    s.stop().unwrap();
+}
+
+#[test]
+fn generalized_linear_regression_default_columns_and_zero_weight_outlier() {
+    let Some(s) = live_session() else {
+        return;
+    };
+    let training = vectorize(s.sql(
+        "SELECT array(CAST(x AS DOUBLE)) AS xs, CAST(y AS DOUBLE) AS label, 
CAST(w AS DOUBLE) AS weight
+         FROM VALUES (-3, -3, 1), (-2, -1, 1), (2, 7, 1), (3, 9, 1), (100, 
-1000, 0) AS t(x,y,w)"
+    ).unwrap(), "features");
+    let held_out = vectorize(
+        s.sql(
+            "SELECT id, array(CAST(x AS DOUBLE)) AS xs FROM VALUES (0, -1.5), 
(1, 4.5) AS t(id,x)",
+        )
+        .unwrap(),
+        "features",
+    );
+    let mut default_model = GeneralizedLinearRegression::default()
+        .fit(&training.filter(col("weight").gt(lit(0))))
+        .unwrap();
+    let mut weighted_model = GeneralizedLinearRegression::new()
+        .set_weight_col("weight")
+        .fit(&training)
+        .unwrap();
+    assert_close(
+        predictions(default_model.transform(&held_out).unwrap(), "prediction"),
+        &[0.0, 12.0],
+        1e-6,
+    );
+    assert_close(
+        predictions(weighted_model.transform(&held_out).unwrap(), 
"prediction"),
+        &[0.0, 12.0],
+        1e-6,
+    );
+    s.stop().unwrap();
+}
+
+#[test]
+fn generalized_linear_regression_families_offsets_and_link_predictions() {
+    let Some(s) = live_session() else {
+        return;
+    };
+    for (family, response) in [
+        ("gaussian", "eta"),
+        ("binomial", "1.0D / (1.0D + exp(-eta))"),
+        ("poisson", "exp(eta)"),
+        ("gamma", "1.0D / eta"),
+        ("tweedie", "pow(eta, -2.0D)"),
+    ] {
+        let training = vectorize(s.sql(&format!(
+            "SELECT array(x) xs, {response} label, off FROM (SELECT id/5.0D x, 
(id % 3)/10.0D off, 1.0D + 0.3D * (id/5.0D) + (id % 3)/10.0D eta FROM 
range(12))"
+        )).unwrap(), "features");
+        let held_out = vectorize(s.sql(
+            "SELECT id, array(x) xs, off FROM VALUES 
(0,0.7D,0.15D),(1,1.3D,0.25D) AS t(id,x,off)"
+        ).unwrap(), "features");
+        let mut estimator = GeneralizedLinearRegression::new()
+            .set_family(family)
+            .set_max_iter(100)
+            .set_tol(1e-10)
+            .set_offset_col("off")
+            .set_link_prediction_col("eta");
+        if family == "tweedie" {
+            estimator = estimator.set_variance_power(1.5);
+        }
+        let mut model = estimator.fit(&training).unwrap();
+        let output = model.transform(&held_out).unwrap();
+        assert_close(predictions(output.clone(), "eta"), &[1.36, 1.64], 1e-5);
+        let expected: Vec<f64> = [1.36_f64, 1.64]
+            .into_iter()
+            .map(|eta| match family {
+                "gaussian" => eta,
+                "binomial" => 1.0 / (1.0 + (-eta).exp()),
+                "poisson" => eta.exp(),
+                "gamma" => 1.0 / eta,
+                "tweedie" => eta.powi(-2),
+                _ => unreachable!(),
+            })
+            .collect();
+        assert_close(predictions(output, "prediction"), &expected, 1e-5);
+    }
+    s.stop().unwrap();
+}
+
+#[test]
+fn generalized_linear_regression_tweedie_log_link_and_regularization() {
+    let Some(s) = live_session() else {
+        return;
+    };
+    let training = vectorize(
+        s.sql("SELECT array(id/5.0D) xs, exp(0.3D * (id/5.0D)) label FROM 
range(12)")
+            .unwrap(),
+        "features",
+    );
+    let point = vectorize(s.sql("SELECT 0 id, array(1.3D) xs").unwrap(), 
"features");
+    let mut model = GeneralizedLinearRegression::new()
+        .set_family("tweedie")
+        .set_variance_power(1.5)
+        .set_link_power(0.0)
+        .set_fit_intercept(false)
+        .set_max_iter(100)
+        .set_tol(1e-10)
+        .fit(&training)
+        .unwrap();
+    assert_close(
+        predictions(model.transform(&point).unwrap(), "prediction"),
+        &[0.39_f64.exp()],
+        1e-5,
+    );
+    let mut regularized = GeneralizedLinearRegression::new()
+        .set_family("tweedie")
+        .set_variance_power(1.5)
+        .set_link_power(0.0)
+        .set_fit_intercept(false)
+        .set_reg_param(2.0)
+        .fit(&training)
+        .unwrap();
+    let value = predictions(regularized.transform(&point).unwrap(), 
"prediction")[0];
+    assert!(value > 1.0 && value < 0.39_f64.exp());
+    s.stop().unwrap();
+}
+
+#[test]
+fn generalized_linear_regression_rejects_invalid_parameters_and_inputs() {
+    let Some(s) = live_session() else {
+        return;
+    };
+    let training = vectorize(
+        s.sql("SELECT array(id*1.0D) xs, id*1.0D label FROM range(1,5)")
+            .unwrap(),
+        "features",
+    );
+    for mut estimator in [
+        GeneralizedLinearRegression::new().set_family("unknown"),
+        GeneralizedLinearRegression::new()
+            .set_family("poisson")
+            .set_link("logit"),
+        GeneralizedLinearRegression::new().set_solver("unknown"),
+        GeneralizedLinearRegression::new().set_max_iter(-1),
+        GeneralizedLinearRegression::new().set_tol(-1.0),
+        GeneralizedLinearRegression::new().set_reg_param(-1.0),
+        GeneralizedLinearRegression::new().set_aggregation_depth(1),
+        GeneralizedLinearRegression::new()
+            .set_family("tweedie")
+            .set_variance_power(0.5),
+    ] {
+        assert!(estimator.fit(&training).is_err());
+    }
+    assert!(GeneralizedLinearRegression::new()
+        .set_weight_col("weight")
+        .fit(&training.with_column("weight", lit(-1)))
+        .is_err());
+    assert!(GeneralizedLinearRegression::new()
+        .set_family("poisson")
+        .fit(&training.with_column("label", lit(-1)))
+        .is_err());
+    assert!(GeneralizedLinearRegression::new()
+        .fit(&training.with_column("features", lit(1)))
+        .is_err());
+    assert!(GeneralizedLinearRegression::new()
+        .fit(&training.limit(0))
+        .is_err());
+    s.stop().unwrap();
+}
diff --git a/crates/spark-connect/tests/generalized_linear_regression_golden.rs 
b/crates/spark-connect/tests/generalized_linear_regression_golden.rs
new file mode 100644
index 00000000..1ed92bc3
--- /dev/null
+++ b/crates/spark-connect/tests/generalized_linear_regression_golden.rs
@@ -0,0 +1,39 @@
+//! Compare parameter encoding against official PySpark 4.3.0.
+use base64::{engine::general_purpose::STANDARD, Engine};
+use prost::Message;
+use spark_connect::ml::{Estimator, GeneralizedLinearRegression};
+
+#[test]
+fn generalized_linear_regression_parameters_match_official_pyspark() {
+    let fixture: serde_json::Value = serde_json::from_str(include_str!(
+        "../../../tests/golden/generalized_linear_regression.json"
+    ))
+    .unwrap();
+    let configured = GeneralizedLinearRegression::new()
+        .set_label_col("target")
+        .set_feature_col("input")
+        .set_prediction_col("pred")
+        .set_family("tweedie")
+        .set_link("log")
+        .set_fit_intercept(false)
+        .set_max_iter(50)
+        .set_tol(1e-08)
+        .set_reg_param(0.25)
+        .set_weight_col("weight")
+        .set_solver("irls")
+        .set_link_prediction_col("eta")
+        .set_variance_power(1.5)
+        .set_link_power(0.0)
+        .set_offset_col("offset")
+        .set_aggregation_depth(3);
+    for (estimator, case) in [GeneralizedLinearRegression::default(), 
configured]
+        .into_iter()
+        .zip(fixture["cases"].as_array().unwrap())
+    {
+        let bytes = STANDARD
+            .decode(case["params_b64"].as_str().unwrap())
+            .unwrap();
+        let expected = 
spark_connect_proto::MlParams::decode(bytes.as_slice()).unwrap();
+        assert_eq!(estimator.params().to_proto(), expected);
+    }
+}
diff --git a/docs/compatibility.md b/docs/compatibility.md
index fd7aa268..50669bae 100644
--- a/docs/compatibility.md
+++ b/docs/compatibility.md
@@ -581,7 +581,6 @@ 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.
 
-
 ## Native BisectingKMeans
 
 The Rust `ml::BisectingKMeans` and `ml::BisectingKMeansModel` support training 
and
@@ -606,6 +605,34 @@ Cluster-center/summary/cost inspection, single-vector 
prediction and persistence
 are outside this surface. The vendored `pyspark.ml.clustering` API retains its
 existing implementation.
 
+## Native GeneralizedLinearRegression
+
+`spark_connect::ml::GeneralizedLinearRegression` fits Spark's JVM estimator and
+returns a cached `GeneralizedLinearRegressionModel`. Python exposes it from
+`pyspark.ml.connect` and `pyspark.ml.connect.regression`; `fit` returns the 
shared
+native `MLModel`.
+
+All 16 PySpark constructor parameters and named setters are available:
+`labelCol`, `featuresCol`, `predictionCol`, `family`, `link`, `fitIntercept`,
+`maxIter`, `tol`, `regParam`, `weightCol`, `solver`, `linkPredictionCol`,
+`variancePower`, `linkPower`, `offsetCol` and `aggregationDepth`. Rust provides
+builder setters and getters for each parameter. Unset optional parameters stay
+unset: Spark chooses the family default link, or the Tweedie link power from
+`variancePower`.
+
+Fitting accepts ML vector features and numeric labels. Transform produces
+predictions and, when requested, the linear predictor in `linkPredictionCol`.
+Instance weights, offsets and L2 regularization are handled by Spark. The same
+numerical tests run against official PySpark and the native Python client,
+covering all five families (Gaussian, binomial, Poisson, Gamma and Tweedie),
+default and explicit links, dense/sparse features, weights, offsets, 
independent
+fitted models, lazy model ownership and rejected inputs. Official PySpark 
golden
+fixtures verify the parameter encoding, and live Rust tests exercise fitting
+and prediction directly.
+
+This native API covers construction, setters, fitting and DataFrame transforms.
+Coefficient/intercept access, model summaries, evaluation, persistence and
+single-vector prediction are not exposed by this addition.
 
 ## Native GaussianMixture
 
diff --git a/python/pyspark/ml/connect/__init__.py 
b/python/pyspark/ml/connect/__init__.py
index b8b6d778..117928f1 100644
--- a/python/pyspark/ml/connect/__init__.py
+++ b/python/pyspark/ml/connect/__init__.py
@@ -22,6 +22,7 @@ from pyspark.ml.connect.classification import (
 from pyspark.ml.connect.regression import (
     GBTRegressor,
     DecisionTreeRegressor,
+    GeneralizedLinearRegression,
     LinearRegression,
     RandomForestRegressor,
 )
@@ -63,6 +64,7 @@ __all__ = [
     "GBTClassifier",
     "GBTRegressor",
     "RandomForestClassifier",
+    "GeneralizedLinearRegression",
     "LinearRegression",
     "DecisionTreeRegressor",
     "RandomForestRegressor",
diff --git a/python/pyspark/ml/connect/regression.py 
b/python/pyspark/ml/connect/regression.py
index 918851dc..a3741281 100644
--- a/python/pyspark/ml/connect/regression.py
+++ b/python/pyspark/ml/connect/regression.py
@@ -1,9 +1,17 @@
 """Native regression estimators backed by Spark Connect's JVM ML API."""
+
 from pyspark._pyspark import (
     DecisionTreeRegressor,
     GBTRegressor,
+    GeneralizedLinearRegression,
     LinearRegression,
     RandomForestRegressor,
 )
 
-__all__ = ["GBTRegressor", "DecisionTreeRegressor", "LinearRegression", 
"RandomForestRegressor"]
+__all__ = [
+    "GBTRegressor",
+    "DecisionTreeRegressor",
+    "GeneralizedLinearRegression",
+    "LinearRegression",
+    "RandomForestRegressor",
+]
diff --git a/python/tests/test_generalized_linear_regression_e2e.py 
b/python/tests/test_generalized_linear_regression_e2e.py
new file mode 100644
index 00000000..7eb1e6af
--- /dev/null
+++ b/python/tests/test_generalized_linear_regression_e2e.py
@@ -0,0 +1,209 @@
+#
+# 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.
+#
+"""GeneralizedLinearRegression behaviors, also run with official PySpark."""
+
+import gc
+import math
+import os
+
+import pytest
+from pyspark.ml.connect.functions import array_to_vector
+from pyspark.ml.linalg import Vectors
+from pyspark.sql import SparkSession
+from pyspark.sql import functions as F
+
+
[email protected]
+def session():
+    remote = os.environ.get("SPARK_REMOTE")
+    if not remote:
+        pytest.skip("SPARK_REMOTE is required for live tests")
+    spark = SparkSession.builder.remote(remote).getOrCreate()
+    try:
+        yield spark
+    finally:
+        spark.stop()
+
+
+def _estimator():
+    try:
+        from pyspark.ml.connect.regression import GeneralizedLinearRegression
+    except ImportError:
+        from pyspark.ml.regression import GeneralizedLinearRegression
+    return GeneralizedLinearRegression
+
+
+def _vectors(session, sql):
+    return session.sql(sql).withColumn("features", array_to_vector("xs"))
+
+
[email protected](
+    "family,link,power",
+    [
+        ("gaussian", None, None),
+        ("binomial", None, None),
+        ("poisson", None, None),
+        ("gamma", None, None),
+        ("tweedie", None, None),
+        ("tweedie", None, 0.0),
+        ("gaussian", "log", None),
+    ],
+)
+def test_generalized_linear_regression_families_links_and_offsets(session, 
family, link, power):
+    def response(eta):
+        if family == "binomial":
+            return 1.0 / (1.0 + math.exp(-eta))
+        if family == "gamma":
+            return 1.0 / eta
+        if family == "tweedie" and power is None:
+            return eta**-2
+        if family == "poisson" or link == "log" or power == 0.0:
+            return math.exp(eta)
+        return eta
+
+    rows = []
+    for i in range(12):
+        x, offset = i / 5.0, (i % 3) / 10.0
+        rows.append((Vectors.dense([x]), response(1.0 + 0.3 * x + offset), 
offset))
+    training = session.createDataFrame(rows, ["input", "target", "offset"])
+    options = dict(
+        featuresCol="input",
+        labelCol="target",
+        predictionCol="pred",
+        family=family,
+        offsetCol="offset",
+        linkPredictionCol="eta",
+        maxIter=100,
+        tol=1e-10,
+    )
+    if family == "tweedie":
+        options["variancePower"] = 1.5
+    if link is not None:
+        options["link"] = link
+    if power is not None:
+        options["linkPower"] = power
+    model = _estimator()(**options).fit(training)
+    held_out = session.createDataFrame(
+        [
+            (0, Vectors.dense([0.7]), 0.15),
+            (1, Vectors.sparse(1, {0: 1.3}), 0.25),
+            (2, Vectors.sparse(1, {}), 0.0),
+        ],
+        ["id", "input", "offset"],
+    )
+    actual = model.transform(held_out).orderBy("id").select("pred", 
"eta").collect()
+    for row, eta in zip(actual, [1.36, 1.64, 1.0]):
+        assert row[0] == pytest.approx(response(eta), rel=1e-5, abs=1e-6)
+        assert row[1] == pytest.approx(eta, abs=1e-5)
+
+
[email protected]("use_setters", [False, True], ids=["constructor", 
"setters"])
+def 
test_generalized_linear_regression_weights_and_independent_lazy_models(session, 
use_setters):
+    frame = _vectors(
+        session,
+        "SELECT array(CAST(x AS DOUBLE)) xs, CAST(y AS DOUBLE) label, CAST(w 
AS DOUBLE) weight "
+        "FROM VALUES 
(-3,-3,1),(-2,-1,1),(-1,1,1),(1,5,1),(2,7,1),(3,9,1),(100,-1000,0) AS t(x,y,w)",
+    )
+    options = dict(
+        weightCol="weight",
+        predictionCol="pred",
+        family="gaussian",
+        link="identity",
+        fitIntercept=True,
+        maxIter=50,
+        regParam=0.0,
+        tol=1e-9,
+        solver="irls",
+        aggregationDepth=3,
+    )
+    estimator = _estimator()() if use_setters else _estimator()(**options)
+    if use_setters:
+        for name, value in options.items():
+            assert getattr(estimator, "set" + name[0].upper() + 
name[1:])(value) is estimator
+    first = estimator.fit(frame)
+    second = estimator.fit(frame.withColumn("label", F.lit(10.0) - 
F.col("label")))
+    held_out = _vectors(
+        session, "SELECT id,array(x) xs FROM VALUES 
(0,-1.5D),(1,0.5D),(2,4.5D) AS t(id,x)"
+    )
+    lazy = first.transform(held_out).orderBy("id").select("pred")
+    estimator.setPredictionCol("changed")
+    del first, estimator
+    gc.collect()
+    assert [r[0] for r in lazy.collect()] == pytest.approx([0.0, 4.0, 12.0], 
abs=1e-6)
+    assert [
+        r[0] for r in 
second.transform(held_out).orderBy("id").select("pred").collect()
+    ] == pytest.approx([10.0, 6.0, -2.0], abs=1e-6)
+
+
+def 
test_generalized_linear_regression_defaults_no_intercept_and_regularization(session):
+    frame = _vectors(
+        session,
+        "SELECT array(CAST(x AS DOUBLE)) xs, CAST(2*x AS DOUBLE) label FROM 
VALUES (-3),(-2),(-1),(1),(2),(3) AS t(x)",
+    )
+    point = _vectors(session, "SELECT array(2.0D) xs")
+    default = _estimator()().fit(frame).transform(point)
+    assert default.columns == ["xs", "features", "prediction"]
+    assert default.select("prediction").collect()[0][0] == pytest.approx(4.0, 
abs=1e-6)
+    regularized = _estimator()(fitIntercept=False, regParam=2.0).fit(frame)
+    value = regularized.transform(point).select("prediction").collect()[0][0]
+    assert 0.0 < value < 3.9
+
+
[email protected](
+    "case",
+    [
+        "family",
+        "link",
+        "solver",
+        "iterations",
+        "tolerance",
+        "regularization",
+        "aggregation",
+        "variance",
+        "label",
+        "weight",
+        "nonvector",
+        "empty",
+    ],
+)
+def 
test_generalized_linear_regression_rejects_invalid_params_and_data(session, 
case):
+    frame = _vectors(
+        session,
+        "SELECT array(CAST(x AS DOUBLE)) xs, CAST(x AS DOUBLE) label FROM 
VALUES (1),(2),(3),(4) AS t(x)",
+    )
+    options = {
+        "family": dict(family="unknown"),
+        "link": dict(family="poisson", link="logit"),
+        "solver": dict(solver="unknown"),
+        "iterations": dict(maxIter=-1),
+        "tolerance": dict(tol=-1.0),
+        "regularization": dict(regParam=-1.0),
+        "aggregation": dict(aggregationDepth=1),
+        "variance": dict(family="tweedie", variancePower=0.5),
+    }.get(case, {})
+    if case == "label":
+        options["family"] = "poisson"
+        frame = frame.withColumn("label", F.lit(-1.0))
+    elif case == "weight":
+        options["weightCol"] = "weight"
+        frame = frame.withColumn("weight", F.lit(-1.0))
+    elif case == "nonvector":
+        frame = frame.withColumn("features", F.lit(1.0))
+    elif case == "empty":
+        frame = frame.limit(0)
+    with pytest.raises(Exception):
+        _estimator()(**options).fit(frame)
diff --git a/python/tests/test_ml_e2e.py b/python/tests/test_ml_e2e.py
index 9943bc86..33d06c33 100644
--- a/python/tests/test_ml_e2e.py
+++ b/python/tests/test_ml_e2e.py
@@ -252,6 +252,7 @@ def _native_estimators():
         GaussianMixture,
         GBTClassifier,
         GBTRegressor,
+        GeneralizedLinearRegression,
         KMeans,
         LinearRegression,
         LinearSVC,
@@ -275,6 +276,7 @@ def _native_estimators():
         (DecisionTreeClassifier(), ml + 
"classification.DecisionTreeClassificationModel"),
         (KMeans(k=2, seed=1), ml + "clustering.KMeansModel"),
         (LinearSVC(maxIter=2), ml + "classification.LinearSVCModel"),
+        (GeneralizedLinearRegression(maxIter=2), ml + 
"regression.GeneralizedLinearRegressionModel"),
         (LinearRegression(maxIter=2), ml + "regression.LinearRegressionModel"),
         (LogisticRegression(maxIter=2), ml + 
"classification.LogisticRegressionModel"),
         (RandomForestClassifier(numTrees=2), ml + 
"classification.RandomForestClassificationModel"),
diff --git a/python/tests/test_ml_offline.py b/python/tests/test_ml_offline.py
index e0068868..913fbcef 100644
--- a/python/tests/test_ml_offline.py
+++ b/python/tests/test_ml_offline.py
@@ -795,6 +795,7 @@ _NATIVE_PARAMS = {
         tol="float", rawPredictionCol="str", fitIntercept="bool", 
standardization="bool",
         threshold="float", weightCol="str", aggregationDepth="int", 
maxBlockSizeInMB="float",
     ),
+    "GeneralizedLinearRegression": dict(labelCol="str", featuresCol="str", 
predictionCol="str", family="str", link="str", fitIntercept="bool", 
maxIter="int", tol="float", regParam="float", weightCol="str", solver="str", 
linkPredictionCol="str", variancePower="float", linkPower="float", 
offsetCol="str", aggregationDepth="int"),
     "LinearRegression": dict(
         featuresCol="str", labelCol="str", predictionCol="str", maxIter="int", 
regParam="float",
         elasticNetParam="float", tol="float", fitIntercept="bool", 
standardization="bool",
@@ -3413,3 +3414,36 @@ def 
test_gbt_classifier_setter_only_columns_convert_as_pyspark(ml_mock, param):
         with pytest.raises(TypeError) as error:
             getattr(GBTClassifier(), setter)(value)
         assert str(error.value) == f'Invalid param value given for param 
"{param}". {message}'
+
+
[email protected]("use_setters", [False, True], ids=["constructor", 
"setters"])
+def 
test_generalized_linear_regression_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 GeneralizedLinearRegression as exported
+    from pyspark.ml.connect.regression import GeneralizedLinearRegression
+
+    assert exported is GeneralizedLinearRegression is 
native.GeneralizedLinearRegression
+    defaults = {'labelCol': 'label', 'featuresCol': 'features', 
'predictionCol': 'prediction', 'family': 'gaussian', 'link': None, 
'fitIntercept': True, 'maxIter': 25, 'tol': 1e-06, 'regParam': 0.0, 
'weightCol': None, 'solver': 'irls', 'linkPredictionCol': None, 
'variancePower': 0.0, 'linkPower': None, 'offsetCol': None, 'aggregationDepth': 
2}
+    signature = inspect.signature(GeneralizedLinearRegression)
+    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/generalized_linear_regression.json").read_text())
+    spark, service = ml_mock
+    models = []
+    for case in fixture["cases"]:
+        if use_setters:
+            estimator = GeneralizedLinearRegression()
+            for name, value in case["values"].items():
+                assert getattr(estimator, "set" + name[0].upper() + 
name[1:])(value) is estimator
+        else:
+            estimator = GeneralizedLinearRegression(**case["values"])
+        operator, params = _native_request(spark, service, estimator, models)
+        assert operator.name == 
"org.apache.spark.ml.regression.GeneralizedLinearRegression"
+        assert params == 
pb2.MlParams.FromString(base64.b64decode(case["params_b64"]))
diff --git a/scripts/capture_generalized_linear_regression_golden.py 
b/scripts/capture_generalized_linear_regression_golden.py
new file mode 100644
index 00000000..054cc42c
--- /dev/null
+++ b/scripts/capture_generalized_linear_regression_golden.py
@@ -0,0 +1,70 @@
+#!/usr/bin/env python3
+"""Capture native GeneralizedLinearRegression params with official PySpark 
4.3.0."""
+
+import argparse
+import base64
+import json
+from pathlib import Path
+
+from pyspark.ml.connect.serialize import serialize_ml_params
+from pyspark.ml.regression import GeneralizedLinearRegression
+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/generalized_linear_regression.json")
+    )
+    args = parser.parse_args()
+    spark = SparkSession.builder.remote(args.remote).getOrCreate()
+    try:
+        cases = []
+        for values in [
+            {},
+            {
+                "labelCol": "target",
+                "featuresCol": "input",
+                "predictionCol": "pred",
+                "family": "tweedie",
+                "link": "log",
+                "fitIntercept": False,
+                "maxIter": 50,
+                "tol": 1e-08,
+                "regParam": 0.25,
+                "weightCol": "weight",
+                "solver": "irls",
+                "linkPredictionCol": "eta",
+                "variancePower": 1.5,
+                "linkPower": 0.0,
+                "offsetCol": "offset",
+                "aggregationDepth": 3,
+            },
+        ]:
+            estimator = GeneralizedLinearRegression(**values)
+            params = serialize_ml_params(estimator, spark.client)
+            cases.append(
+                {
+                    "values": values,
+                    "params_b64": base64.b64encode(
+                        params.SerializeToString(deterministic=True)
+                    ).decode(),
+                }
+            )
+        args.out.write_text(
+            json.dumps(
+                {
+                    "source": "apache/spark v4.3.0 
pyspark.ml.regression.GeneralizedLinearRegression",
+                    "cases": cases,
+                },
+                indent=2,
+            )
+            + "\n"
+        )
+    finally:
+        spark.stop()
+
+
+if __name__ == "__main__":
+    main()
diff --git a/tests/golden/generalized_linear_regression.json 
b/tests/golden/generalized_linear_regression.json
new file mode 100644
index 00000000..3641fb63
--- /dev/null
+++ b/tests/golden/generalized_linear_regression.json
@@ -0,0 +1,30 @@
+{
+  "source": "apache/spark v4.3.0 
pyspark.ml.regression.GeneralizedLinearRegression",
+  "cases": [
+    {
+      "values": {},
+      "params_b64": ""
+    },
+    {
+      "values": {
+        "labelCol": "target",
+        "featuresCol": "input",
+        "predictionCol": "pred",
+        "family": "tweedie",
+        "link": "log",
+        "fitIntercept": false,
+        "maxIter": 50,
+        "tol": 1e-08,
+        "regParam": 0.25,
+        "weightCol": "weight",
+        "solver": "irls",
+        "linkPredictionCol": "eta",
+        "variancePower": 1.5,
+        "linkPower": 0.0,
+        "offsetCol": "offset",
+        "aggregationDepth": 3
+      },
+      "params_b64": 
"ChYKEGFnZ3JlZ2F0aW9uRGVwdGgSAjADChMKBmZhbWlseRIJagd0d2VlZGllChYKC2ZlYXR1cmVzQ29sEgdqBWlucHV0ChIKDGZpdEludGVyY2VwdBICGAAKFAoIbGFiZWxDb2wSCGoGdGFyZ2V0ChYKCWxpbmtQb3dlchIJWQAAAAAAAAAAChoKEWxpbmtQcmVkaWN0aW9uQ29sEgVqA2V0YQoNCgRsaW5rEgVqA2xvZwoNCgdtYXhJdGVyEgIwMgoVCglvZmZzZXRDb2wSCGoGb2Zmc2V0ChcKDXByZWRpY3Rpb25Db2wSBmoEcHJlZAoVCghyZWdQYXJhbRIJWQAAAAAAANA/ChAKBnNvbHZlchIGagRpcmxzChAKA3RvbBIJWTqMMOKOeUU+ChoKDXZhcmlhbmNlUG93ZXISCVkAAAAAAAD4PwoVCgl3ZWlnaHRDb2wSCGoGd2VpZ2h0"
+    }
+  ]
+}


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

Reply via email to