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.mlestimators 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?
The data does not fit on one node and the algorithm exists in MLlib, so distributed training with a pyspark.ml estimator is the right fit. toPandas() runs into the driver's memory limit, sampling breaks the all-rows requirement, and SparkTrials spreads tuning trials across workers rather than training one model on the whole table.
“Use Spark ML on Standard compute if you need Spark-level distribution for data that doesn’t fit in memory on a single node”Source: docs.databricks.com
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?
Correct answer: A — Train a GBTClassifier from pyspark.ml.classification inside a Spark ML Pipeline, so executors process the Delta table in parallel while the model fits.
- A. Spark ML estimators such as
GBTClassifierdistribute both feature access and gradient computation across executors, so the full 800-million-row table is used without ever collecting it onto one machine. This is exactly the workload Spark MLlib is built for. - B. Pulling the entire Delta table into a pandas DataFrame forces it into driver memory, which is the out-of-memory failure the team is trying to avoid in the first place. A single-node library cannot process data that does not fit on one machine.
- C. Sampling down to 10% of the rows before fitting discards most of the labeled data, which violates the requirement to train without subsampling even though it avoids the memory limit.
- D.
MlflowSparkStudyparallelizes independent hyperparameter trials, but each trial still trains a separate single-node model on only its own shard rather than one model learning from the full table.
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?
Correct answer: A — The dataset fits comfortably in memory on one node, and the team needs algorithms and tooling that exist only in the single-node ecosystem.
- A. When data comfortably fits on one machine and the team specifically needs single-node-only algorithms or plotting tools, the cost of distributed execution buys nothing, making single-node the pragmatic choice.
- B. Spark MLlib estimators can fit on small datasets; there is no minimum row-count floor below which MLlib refuses to train, so this claim is false.
- C. Accuracy depends on the algorithm and data, not on whether the implementation is distributed; neither approach has an inherent accuracy advantage over the other.
- D. A Spark
Pipelinecan be fit on any Spark DataFrame, including one read from CSV or Parquet in memory; Delta storage is not a prerequisite for training.
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.
| Building block | Kind | What fit() produces | What transform() does |
|---|---|---|---|
| StandardScaler / MaxAbsScaler | Estimator | A fitted scaler holding the learned statistics | Adds a rescaled feature column |
| LogisticRegression | Estimator | A fitted classification model | Adds prediction columns |
| Pipeline | Estimator | A PipelineModel | Not available until fitted |
| PipelineModel | Transformer | Already fitted | Runs 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.
The PipelineModel holds the category indices, scaling statistics and model weights learned from the training data, so new rows are encoded the same way the model saw during training. Refitting on new data would learn new mappings and a new model.
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?
A custom transformer goes into the stages list like any other stage, and an XGBoost model can be embedded as a pipeline stage and fitted along with the preprocessing in front of it. Stages run one after another, never in parallel.
“The first example shows how to embed an XGBoost model into an MLlib ML pipeline.”Source: docs.databricks.com
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?
Correct answer: A — Each stage runs in order: Transformer stages transform immediately, Estimator stages fit and are replaced by fitted transformers, giving a PipelineModel.
- A.
Pipeline.fit()runs each stage in sequence: transformer stages likeOneHotEncoderandVectorAssemblerapply their transform immediately, while estimator stages likeStringIndexerandLogisticRegressionare fit on the data produced by prior stages and become fitted transformers inside the returnedPipelineModel. - B. Every stage in the list actually executes; the earlier stages are not skipped or treated as inert configuration, since each one produces the transformed columns the next stage depends on.
- C. Pipeline stages run sequentially because each stage typically consumes the output column of the previous one, so they cannot be executed in parallel as independent, unrelated steps.
- D. Mixing indexing, encoding, assembling, and a classifier in one
Pipelineis the standard pattern the API is designed for, so no exception is raised for combining these stage types.
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?
MLlib already distributes each fit. The default Trials class keeps the trials on the driver, so each trial can start distributed training across the cluster. SparkTrials is for algorithms that are not distributed themselves.
“SparkTrials is designed to distribute trials for algorithms that are not themselves distributed. With distributed training algorithms, use the default Trials class”Source: docs.databricks.com
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?
MLlib automated MLflow tracking is deprecated and off by default on Databricks Runtime 10.4 LTS ML and above. Its replacement is MLflow PySpark ML autologging, which Databricks Autologging enables by default.
“Instead, use MLflow PySpark ML autologging by calling mlflow.pyspark.ml.autolog(), which is enabled by default with Databricks Autologging.”Source: docs.databricks.com
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.
| Task | Evaluator | Typical use |
|---|---|---|
| Continuous label (price, demand) | RegressionEvaluator | Error in the label's own units, such as RMSE |
| Two classes (churn / no churn) | BinaryClassificationEvaluator | Ranking quality of the predicted scores |
| Three or more classes | MulticlassClassificationEvaluator | Overall 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.
Pick the evaluator by the kind of label: continuous, two classes, or three or more classes. Then set the metric with metricName. CrossValidator uses this same evaluator to rank the grid combinations, so the wrong evaluator changes which model wins.
“Evaluator: pyspark.ml.connect.RegressionEvaluator, pyspark.ml.connect.BinaryClassificationEvaluator and MulticlassClassificationEvaluator”Source: docs.databricks.com
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.
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.
| Inference type | When predictions are needed | Spark ML model | Single-node model |
|---|---|---|---|
| Batch | On a schedule, over a whole table | PipelineModel transform on the DataFrame | mlflow.pyfunc.spark_udf applied with withColumn |
| Streaming | Continuously, as new records arrive | The same transform on a streaming DataFrame | The same spark_udf on a streaming DataFrame |
| Real-time | Per request, while a caller waits | Rarely a fit: Spark adds nothing for one row | Model 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?
Structured Streaming lets you write a computation on streaming data exactly as you would on a static table. The same spark_udf that scores the batch table works on a DataFrame read with readStream, and Spark writes the results out incrementally. Neither retraining nor collecting data to the driver is needed.
“Structured Streaming lets you express computation on streaming data in the same way you express a batch computation on static data.”Source: docs.databricks.com
Sources
(13)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 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.
“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.https://docs.databricks.com/aws/en/machine-learning/train-model/distributed-training/distributed-ml-for-spark-connectOfficial docs
“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.
“Load data from Unity Catalog as Pandas dataframes”
↩︎ When Spark ML beats a single-node library - 5.
“data: Any SparkDataFrame”
↩︎ When Spark ML beats a single-node library“Output: MLlib PipelineModel”
↩︎ Building a pipeline from transformers and estimators“Calculate RMSE”
↩︎ Evaluating with the matching MLlib evaluator - 6.https://docs.databricks.com/aws/en/machine-learning/automl-hyperparam-tuning/hyperopt-distributed-mlOfficial docs
“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 - 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 - 8.https://scikit-learn.org/stable/modules/compose.htmlSecondary source
“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 - 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 - 10.https://docs.databricks.com/aws/en/ldp/transformOfficial docs
“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 - 11.https://docs.databricks.com/aws/en/mlflow/modelsOfficial docs
“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 - 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 - 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