CertSafari
    Databricks Certified Machine Learning Professional· Lessons

    Domain 1 · Lesson 1/11

    Spark ML pipelines: build, tune, evaluate and score

    Using Spark ML

    19 min read
    11% of exam
    13 sources
    Published 21 Oct 2026
    Docs as of 17 Oct 2026

    What you will be able to do

    • Decide from data size, algorithm availability and data location whether a model should be built with Spark ML or a single-node library such as scikit-learn
    • Assemble a Spark ML Pipeline from transformer and estimator stages and explain what Pipeline.fit() returns
    • Tune a pipeline with ParamGridBuilder and CrossValidator or TrainValidationSplit, logging runs with mlflow.pyspark.ml.autolog()
    • Choose the MLlib evaluator that matches a regression, binary or multiclass task
    • Match an inference requirement to batch scoring, Structured Streaming scoring (including spark_udf for single-node models) or a real-time Model Serving endpoint

    Key concept

    Transformer and estimator stages — A Spark ML transformer turns one DataFrame into another by adding columns, while an estimator learns from a DataFrame with fit() and returns a fitted model, which is itself a transformer. A Pipeline chains these stages in order, and fitting it produces a PipelineModel made only of transformers.

    1.When Spark ML beats a single-node library

    Spark MLlib is Apache Spark's machine learning library. It covers classification, regression, clustering, collaborative filtering and dimensionality reduction, and it runs those algorithms on Spark DataFrames spread across a cluster. MLlib exists for data parallelism: it applies the same operation to every partition of a dataset that is too large for one machine. That strength is also the test for when to use it. The pyspark.ml package works on serverless, standard and dedicated compute, so which compute you have is rarely what decides the question.

    Spark ML is the right choice when any of these holds:

    • The data does not fit in memory on one node. If the training set is bigger than the largest driver, the work has to be split across executors.
    • The algorithm exists in MLlib. Gradient-boosted trees, logistic regression and the other pyspark.ml estimators train in a distributed way out of the box. Third-party estimators such as XGBoost can also be embedded in an MLlib pipeline.
    • The data already lives in Spark DataFrames. Training reads the table where it sits instead of collecting it to one process.

    Take a curated table of 800 million rows and 400 features that will not fit on the biggest driver. Calling .toPandas() pulls every row into driver memory, which is the very limit the team is up against. Fitting on a 10% sample avoids the limit by throwing data away, which the requirements do not allow. A GBTClassifier from pyspark.ml.classification inside a Spark ML Pipeline avoids both problems: executors read the table in parallel while the model fits. MLlib also does not require Delta. The R glm API in SparkR, for example, takes any SparkDataFrame, including one read from CSV.

    The opposite case is just as common. Databricks' own getting-started tutorial reads a small wine-quality table from Unity Catalog with toPandas() and fits a scikit-learn GradientBoostingClassifier. With 40,000 rows and 25 columns that fit easily on one node, the deciding factors are memory and tooling: the scikit-learn ecosystem has algorithms and diagnostic plotting libraries that MLlib lacks. MLlib has no minimum dataset size, and neither library is more accurate by nature. The question is whether the data needs distributing and whether the algorithm you need exists in MLlib.

    Distributed tuning and distributed training solve different problems. Tools such as Hyperopt's SparkTrials or Optuna's MlflowSparkStudy spread trials across the cluster, and each trial fits a complete single-node model. If an executor fits its own scikit-learn model on its own slice of rows, you get many separate models, not one model trained on the whole table. Tuning trade-offs are covered in scaling and tuning. On Standard compute, a Spark ML model is cached on the shared driver and can be at most 1 GB, so very large models are a constraint even when the data is not.

    Checkpoint 1 of 9· Check yourself

    A team must train a logistic regression model on every row of a 2-billion-row clickstream table in Unity Catalog. The table is far larger than the biggest driver available. Which approach fits these requirements?

    Checkpoint 2 of 9· Exam question

    A data science team must train a gradient-boosted tree classifier on a curated Unity Catalog Delta table with 800 million rows and roughly 400 feature columns. The full table cannot fit into the memory of the largest available driver node, and the team is not allowed to subsample the data. Which approach lets them train on the complete dataset?

    Checkpoint 3 of 9· Exam question

    A team is deciding whether to build a churn model with Spark MLlib or with single-node scikit-learn. The labeled training set is 40,000 rows and 25 columns, comfortably fitting in the memory of one driver node, and the team wants access to a wide range of scikit-learn-only algorithms and diagnostic plotting libraries. Which factor most strongly favors the single-node approach here?

    Sources123456

    2.Building a pipeline from transformers and estimators

    A Spark ML Pipeline is an ordered list of stages, and each stage is either a transformer or an estimator. A transformer has transform(): it takes a DataFrame and returns a new one with extra columns, such as an assembled feature vector or a prediction column. An estimator has fit(): it learns something from a DataFrame and returns a fitted model, and that model is a transformer. LogisticRegression and GBTClassifier are estimators. So are scalers such as StandardScaler, because they need to learn a mean or a range from the data before they can rescale anything.

    The test for which kind a stage is: does it have to learn anything from the data? VectorAssembler only copies existing columns into one vector, so it is a plain transformer. StringIndexer has to look at the training data to find the categories and assign their indices, so it is an estimator. OneHotEncoder and the classifier at the end of the chain are estimators too. Choose stages by what each column needs. Index and encode categorical columns, scale numeric ones if the algorithm cares about scale, assemble everything into one feature vector, and finish with the estimator for the task.

    pipeline.fit(trainingData) runs the stages one after another, never in parallel, because each stage reads the previous stage's output. A transformer stage transforms the DataFrame and passes it on. An estimator stage is fitted on the DataFrame as it arrives, and its fitted model then transforms that DataFrame for the next stage. The result is a PipelineModel, the fitted version of the pipeline, in which every estimator has been replaced by its fitted model. A pipeline that mixes indexing, encoding, assembling and a classifier is the normal case, not an error. Calling PipelineModel.transform() on test or production data then applies the exact mappings and statistics learned during training.

    How common pipeline building blocks behave under fit() and transform()
    Building blockKindWhat fit() producesWhat transform() does
    StandardScaler / MaxAbsScalerEstimatorA fitted scaler holding the learned statisticsAdds a rescaled feature column
    LogisticRegressionEstimatorA fitted classification modelAdds prediction columns
    PipelineEstimatorA PipelineModelNot available until fitted
    PipelineModelTransformerAlready fittedRuns every fitted stage in order

    When no built-in stage does what you need, write a custom transformer and add it to the stages list like any other. Pipelines are not limited to MLlib's own algorithms either: an XGBoost model can be embedded as a pipeline stage and fitted along with the preprocessing in front of it.

    Checkpoint 4 of 9· Check yourself

    Your churn pipeline needs a domain-specific cleanup step that no built-in MLlib stage provides, and the model at the end must be XGBoost. How should the Spark ML Pipeline be built?

    Checkpoint 5 of 9· Exam question

    A machine learning engineer is assembling a Spark ML Pipeline with a StringIndexer, a OneHotEncoder, a VectorAssembler, and a LogisticRegression estimator as its stages, in that order. What happens when pipeline.fit(trainingData) is called?

    Sources5178

    3.Tuning a pipeline with ParamGridBuilder and CrossValidator

    MLlib tuning wraps an estimator, usually the whole Pipeline, inside another estimator that searches a grid. ParamGridBuilder lists the values to try for each parameter, for example three values of regParam and three of maxIter, and builds every combination. You pass that grid, the pipeline and an evaluator to the tuner and call fit() once. Tuning the pipeline rather than just the classifier means the indexers and scalers are refitted on each training split, so the held-out data never shapes the preprocessing.

    CrossValidator and TrainValidationSplit differ in how many times each combination is fitted. CrossValidator splits the data into numFolds folds. It fits every combination on all folds but one, scores it on the remaining fold, and averages the scores. A 3×3 grid with three folds therefore costs 27 fits before the final refit. TrainValidationSplit makes a single split controlled by trainRatio and fits each combination once. That is cheaper, but each score rests on one validation set instead of an average. Both return a model whose bestModel is the winning pipeline refitted on the full data. The same MLlib cross-validation can also tune an XGBoost model embedded in a pipeline.

    Logging has changed since older runtimes. The old MLlib automated MLflow tracking logged CrossValidator and TrainValidationSplit hyperparameters and metrics on its own, but it is deprecated and disabled by default on Databricks Runtime 10.4 LTS ML and above. Its replacement is mlflow.pyspark.ml.autolog(), which Databricks Autologging enables by default. How the runs nest and how to read them is covered in advanced MLflow usage.

    If you tune MLlib with Hyperopt instead, keep the trials on the driver. MLlib already distributes each fit, so use the default Trials class and not SparkTrials. The driver then runs one trial at a time, and each trial starts distributed training across the cluster. Hyperopt is no longer included in Databricks Runtime ML after 16.4 LTS ML. Databricks recommends Optuna for single-node tuning and Ray Tune for distributed tuning in its place.

    Checkpoint 6 of 9· Check yourself

    Hyperopt is tuning maxDepth and stepSize for a pyspark.ml GBTClassifier on a large cluster. Which trials setup lets every trial use the whole cluster for training?

    Checkpoint 7 of 9· Check yourself

    On Databricks Runtime 15.4 LTS ML, the hyperparameters and metrics of a CrossValidator run appear in MLflow without any logging code in the notebook. What logged them?

    Sources976

    4.Evaluating with the matching MLlib evaluator

    An MLlib evaluator takes the DataFrame returned by model.transform(), compares its prediction column with the label column, and returns one number. That same evaluator object is what CrossValidator and TrainValidationSplit use to rank grid combinations, so choosing the wrong evaluator does more than distort a report: it changes which model wins. Choose the evaluator by the kind of label, then choose a metric with its metricName parameter.

    Choosing the evaluator by task
    TaskEvaluatorTypical use
    Continuous label (price, demand)RegressionEvaluatorError in the label's own units, such as RMSE
    Two classes (churn / no churn)BinaryClassificationEvaluatorRanking quality of the predicted scores
    Three or more classesMulticlassClassificationEvaluatorOverall correctness and per-class averaged scores

    RMSE shows why the unit matters. It is the square root of the mean squared error, so it is in the same unit as the label: a house-price model's RMSE is in dollars. Because the errors are squared, a few large misses raise it sharply. Report the final number on a test set that the tuner never saw. The tuner's best cross-validation score was chosen because it was the highest, so it overstates how well the model will do on new data.

    Checkpoint 8 of 9· Match them up

    Each of these models is tuned with CrossValidator. Match each one to the MLlib evaluator it should pass to the tuner.

    Tap a term, then the definition that fits it.

    Sources35

    5.Scoring in batch, in a stream, or in real time

    The inference type follows from how the predictions are used: on a schedule over a table, continuously as data arrives, or one request at a time inside an application. Each pattern has its own home on Databricks, and Spark appears in only two of them.

    Batch scoring runs over a whole table on a schedule. A Spark ML model scores with PipelineModel.transform() on the DataFrame. A single-node model, such as one from scikit-learn, does not need to be collected to the driver either. Logged in MLflow, it can be wrapped with mlflow.pyfunc.spark_udf and applied with withColumn, and Spark then runs it on the executors across every partition. On Databricks, MLflow models used this way act as transformations: a Spark DataFrame goes in and a Spark DataFrame comes out.

    Wrapping a logged MLflow model as a Spark UDF and applying it to a tablepython
    from pyspark import pipelines as dp
    import mlflow
    
    run_id= "<mlflow-run-id>"
    model_name = "<the-model-name-in-run>"
    model_uri = f"runs:/{run_id}/{model_name}"
    loaded_model_udf = mlflow.pyfunc.spark_udf(spark, model_uri=model_uri)
    
    @dp.materialized_view
    def model_predictions():
      return (
        spark.read.table(<input-data>)
        .withColumn("prediction", loaded_model_udf(<model-features>))
      )

    Two lines do the scoring: mlflow.pyfunc.spark_udf loads the logged model as a UDF, and withColumn applies it to the feature columns. The rest is pipeline scaffolding. dp is pyspark.pipelines, the module for Databricks pipelines, and @dp.materialized_view declares the function's returned DataFrame as a pipeline table that is recomputed on each update. That is how an existing script that calls an MLflow model is adapted to run as a pipeline. Pipelines do not install MLflow by default, so the code imports it explicitly.

    Streaming scoring reuses the same code. Structured Streaming lets you write a computation on streaming data exactly as you would on a static table, so the same PipelineModel.transform() or the same spark_udf works on a DataFrame read with readStream. The results are written out incrementally as new records arrive. Choose this when sensor readings or events keep landing and their scores should follow within seconds, not overnight.

    Real-time scoring is request/response, and it goes to a Model Serving endpoint. Each served model is a REST API that a web or client application can call, and it runs on serverless compute that scales with demand. Spark is built to process large datasets in parallel, which is no advantage when a request carries one row, so a single-node model behind an endpoint is the natural choice here. How endpoints roll out new versions is covered in deployment strategies.

    Matching the inference type to a scoring mechanism
    Inference typeWhen predictions are neededSpark ML modelSingle-node model
    BatchOn a schedule, over a whole tablePipelineModel transform on the DataFramemlflow.pyfunc.spark_udf applied with withColumn
    StreamingContinuously, as new records arriveThe same transform on a streaming DataFrameThe same spark_udf on a streaming DataFrame
    Real-timePer request, while a caller waitsRarely a fit: Spark adds nothing for one rowModel Serving endpoint called through its REST API

    Checkpoint 9 of 9· Check yourself

    Sensor readings now land continuously, and their scores must follow within seconds. A scikit-learn model logged in MLflow already scores the nightly table through mlflow.pyfunc.spark_udf. What is the right change?

    Sources10111213

    Sources

    (13)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 1.
      “machine learning library consisting of common learning algorithms and utilities, including classification, regression, clustering”
      ↩︎ When Spark ML beats a single-node library
      “The pyspark.ml package from Apache Spark MLlib is supported on serverless, standard, and dedicated compute.”
      ↩︎ When Spark ML beats a single-node library
      “This notebook illustrates how to create a custom transformer.”
      ↩︎ Building a pipeline from transformers and estimators
    2. 2.
      “Spark excels at data parallelism - Apply the same operation to each element of a large dataset.”
      ↩︎ When Spark ML beats a single-node library
      “MLlib and SparkML libraries are optimized for large-scale machine learning algorithms and statistical modeling.”
      ↩︎ When Spark ML beats a single-node library
    3. 3.
      “Use Spark ML on Standard compute if you need Spark-level distribution for data”
      ↩︎ When Spark ML beats a single-node library
      “Model size constraints: The maximum model size is 1 GB, so training extremely large models may not be feasible.”
      ↩︎ When Spark ML beats a single-node library
      “Evaluator: pyspark.ml.connect.RegressionEvaluator, pyspark.ml.connect.BinaryClassificationEvaluator and MulticlassClassificationEvaluator”
      ↩︎ Evaluating with the matching MLlib evaluator
      “Use Spark ML on Standard compute if you need Spark-level distribution for data that doesn’t fit in memory on a single node”
      ↩︎ Checkpoint
    4. 6.
      “SparkTrials is designed to distribute trials for algorithms that are not themselves distributed.”
      ↩︎ When Spark ML beats a single-node library
      “Hyperopt is not included in Databricks Runtime for Machine Learning after 16.4 LTS ML.”
      ↩︎ Tuning a pipeline with ParamGridBuilder and CrossValidator
      “With distributed training algorithms, use the default Trials class, which runs on the cluster driver.”
      ↩︎ Tuning a pipeline with ParamGridBuilder and CrossValidator
      “SparkTrials is designed to distribute trials for algorithms that are not themselves distributed.”
      ↩︎ Exam trap 1
      “Hyperopt evaluates each trial on the driver node so that the ML algorithm itself can initiate distributed training.”
      ↩︎ Exam trap 2
      “SparkTrials is designed to distribute trials for algorithms that are not themselves distributed. With distributed training algorithms, use the default Trials class”
      ↩︎ Checkpoint
    5. 7.
      “The first example shows how to embed an XGBoost model into an MLlib ML pipeline.”
      ↩︎ Building a pipeline from transformers and estimators
      “The second example shows how to use MLlib cross validation to tune an XGBoost model.”
      ↩︎ Tuning a pipeline with ParamGridBuilder and CrossValidator
    6. 8.
      “calling fit on each estimator in turn, transform the input and pass it on to the next step”
      ↩︎ Building a pipeline from transformers and estimators
      “calling fit on each estimator in turn, transform the input and pass it on to the next step”
      ↩︎ Key concept
    7. 9.
      “when you run tuning code that uses CrossValidator or TrainValidationSplit, hyperparameters and evaluation metrics are automatically logged in MLflow”
      ↩︎ Tuning a pipeline with ParamGridBuilder and CrossValidator
      “use MLflow PySpark ML autologging by calling mlflow.pyspark.ml.autolog(), which is enabled by default with Databricks Autologging.”
      ↩︎ Tuning a pipeline with ParamGridBuilder and CrossValidator
      “MLlib automated MLflow tracking is deprecated and disabled by default on clusters that run Databricks Runtime 10.4 LTS ML and above.”
      ↩︎ Exam trap 3
      “Instead, use MLflow PySpark ML autologging by calling mlflow.pyspark.ml.autolog(), which is enabled by default with Databricks Autologging.”
      ↩︎ Checkpoint
    8. 10.
      “MLflow models are treated as transformations in Databricks, meaning they act upon a Spark DataFrame input and return results as a Spark DataFrame.”
      ↩︎ Scoring in batch, in a stream, or in real time
      “adapt this code to a pipeline by using the @dp.table or @dp.materialized_view decorator”
      ↩︎ Scoring in batch, in a stream, or in real time
      “Pipelines do not install MLflow by default”
      ↩︎ Scoring in batch, in a stream, or in real time
    9. 11.
      “you can export the model as an Apache Spark UDF to use for scoring on a Spark cluster, either as a batch job”
      ↩︎ Scoring in batch, in a stream, or in real time
    10. 12.
      “Structured Streaming lets you express computation on streaming data in the same way you express a batch computation on static data.”
      ↩︎ Scoring in batch, in a stream, or in real time
      “Apache Spark Structured Streaming is a near real-time processing engine”
      ↩︎ Exam trap 4
    11. 13.
      “Each model you serve is available as a REST API that you can integrate into your web or client application.”
      ↩︎ Scoring in batch, in a stream, or in real time
      “Model Serving provides a highly available and low-latency service for deploying models.”
      ↩︎ Scoring in batch, in a stream, or in real time

    Ready to test yourself?

    Practise the 32 questions on this subdomain.

    Spotted a mistake, or was something unclear? Tell us.