What you will be able to do
- Lay out the stages of a Databricks model training pipeline: load and featurize, train and tune, evaluate on held-out data, log, register
- Explain why imputers, encoders and scalers must be fitted inside a scikit-learn Pipeline, and spot the fixes that leave leakage in place
- Combine numeric and categorical preprocessing in a ColumnTransformer that forms the first step of a single Pipeline
- Write a hyperparameter grid that targets nested pipeline steps with the step_name__param syntax, then refit and log the winning pipeline
Key concept
Leakage-safe training pipeline — A training pipeline that chains every preprocessing step and the final predictor into one object. Fitting that object learns the preprocessing statistics from training data only, and the same fitted transforms are then reused on validation, test and inference data.
1.What a training pipeline does on Databricks
A training pipeline is code that turns a table into a logged, evaluated model, and that runs the same way every time. It is different from exploratory work. In the notebook phase a data scientist pokes at the data and starts to decide on data preparation and featurization steps, but that ad hoc exploration is not normally deployed. The deliverable from development is pipeline code that can be run again in staging and production on that environment's own tables.
Databricks splits the model training pipeline into two tasks. Training and tuning fits the model, searches hyperparameters, and logs parameters, metrics and artifacts to the MLflow Tracking server. When it finishes, the final model artifact is logged so that the model is linked to the input data and the code that produced it. Evaluation then tests the model on held-out data and logs those results as well. The goal is to find out whether the new model beats the one currently in production.
| Stage | What happens | Output |
|---|---|---|
| Load and featurize | Read tables from the dev or prod catalog and apply data preparation and featurization | Training data with features and label |
| Training and tuning | Fit the model and tune hyperparameters, logging parameters, metrics and artifacts | Final model artifact logged to the MLflow Tracking server |
| Evaluation | Test on held-out data and log the results | Metrics that compare the new model with the production model |
| Register | Register the model to the catalog of the environment the pipeline ran in | A model version and a model URI for the validation task |
In code, the featurize and train stages become one scikit-learn Pipeline object, and tuning is a search over that object. This is what lets the evaluation and inference stages trust their inputs. Inputs can come from a feature table, which is covered in training with feature store tables. Registering the result belongs to registering models in Unity Catalog. The rest of this page is about what goes inside the training step and the order things happen in.
Checkpoint 1 of 9· Check yourself
A data scientist has finished developing a churn model in the dev workspace. Under the Databricks MLOps workflow, what should they hand off so the model can be produced in staging and production?
Development produces rerunnable pipeline code, which is then run in staging and production on that environment's tables. Exploratory notebook work is not normally deployed, and the trained dev model is not what moves forward.
“The output of the development process is ML pipeline code that can include feature computation, model training, inference, and monitoring.”Source: docs.databricks.com
Sources1
2.Fit preprocessing on training data only
Every imputer, encoder and scaler learns something from the data it is fitted on. A median imputer stores a median, StandardScaler stores a mean and a standard deviation, and a one-hot encoder stores the set of categories it saw. If those statistics are computed on rows the model will later be scored against, the score has already seen the answers. That is data leakage, and it makes cross-validation scores unreliable.
The fix is structural. Chain the preprocessing and the predictor into one sklearn.pipeline.Pipeline and hand the whole object to cross_val_score, GridSearchCV or fit. On each fold, cross-validation calls fit on the pipeline with that fold's training rows only. The scaler learns its mean and deviation from those rows, and the held-out fold is transformed with those stored statistics, never with its own. The arrangement relies on a rule from estimators vs transformers (fit / transform / predict): every step except the last has to be a transformer, and the last step is the predictor that produces output.
Each of the tempting alternatives leaves the leak in place. With ten folds instead of five, the scaler has still seen every row before any fold is held out, so the leak just gets spread differently. Fitting on an 80% subsample means the scaler has still seen most of the rows that will become held-out folds, and preprocessing now sits outside the reusable object. MinMaxScaler fitted on everything leaks the minimum and maximum just as StandardScaler leaks the mean. Changing the scaler does not change where its statistics come from.
The benefit continues after training. A fitted pipeline carries the statistics it learned, so validation, test and inference data go through exactly the transforms the model was trained behind. When the whole pipeline is logged as the model, serving cannot fall back on a slightly different hand-written preprocessing script. Databricks advises using MLflow tracking to verify reproducibility and avoid training-serving skew, and a single logged pipeline is the simplest way to do that.
Checkpoint 2 of 9· Check yourself
Your fitted pipeline chains a median imputer, a StandardScaler and a classifier. When the model is served, how should incoming rows be preprocessed so they match what the model was trained on?
A fitted pipeline stores the statistics it learned from training data. Logging the whole pipeline means serving uses exactly those transforms. Refitting on inference batches, or reimplementing preprocessing by hand, lets serving drift from training and causes training-serving skew.
“leverage MLflow tracking to record dependencies, verify reproducibility, and avoid training-serving skew”Source: docs.databricks.com
Checkpoint 3 of 9· Exam question
A data scientist is building a training pipeline for a scikit-learn classifier on Databricks. To evaluate the model, they fit StandardScaler on the entire training DataFrame, transform it, and then run cross_val_score on the classifier using the scaled features. A colleague reviewing the pipeline flags this as a data leakage risk. Which change most directly fixes the leakage while keeping the workflow inside a single reusable notebook cell?
Correct answer: A — Wrap the StandardScaler and classifier in a sklearn.pipeline.Pipeline and pass that pipeline to cross_val_score, so scaling is refit on only the training fold each iteration.
- A. A
Pipelinerefits every preprocessing step on only the training fold during each cross-validation iteration, so scaling statistics never see the held-out fold. This is the documented scikit-learn pattern for eliminating leakage from transformers used before an estimator. - B. Adding more folds changes how the data is split but does not stop the scaler from having already seen the full dataset, including every future test fold. The leaked statistics are baked into the scaler regardless of how many folds are used afterward.
- C. Fitting on a random subsample still exposes the scaler to rows that later end up in test folds, since the subsample and the cross-validation splits are drawn independently. This narrows the leakage without closing it.
- D. Swapping the scaling method does not change when the transformer is fit; a
MinMaxScalerfit on the full DataFrame leaks the same way aStandardScalerdoes because both compute statistics from every row up front.
3.Preprocessing numeric and categorical columns with ColumnTransformer
Real training tables mix column types, and each type needs its own preparation. Numeric columns might need imputation and then scaling. Categorical columns need one-hot encoding. Running a single transformer across the whole DataFrame cannot do both. If you one-hot encode everything first and then impute and scale the indicator columns as though they were continuous features, you encode the numerics as categories and then distort the 0/1 indicators. ColumnTransformer exists to send different columns through different transformers, and it lives inside a Pipeline that stays safe from leakage and can be parametrized.
>>> from sklearn.compose import ColumnTransformer
>>> from sklearn.feature_extraction.text import CountVectorizer
>>> from sklearn.preprocessing import OneHotEncoder
>>> column_trans = ColumnTransformer(
... [('categories', OneHotEncoder(dtype='int'), ['city']),
... ('title_bow', CountVectorizer(), 'title')],
... remainder='drop', verbose_feature_names_out=False)Each entry is a name, a transformer and the columns it applies to. The form of the column selector decides the shape of the data the transformer receives. A bare string such as 'title' hands over a single column as 1D data, and a list such as ['city'] hands over a 2D table, even when the list holds one name. CountVectorizer expects a 1D array of text, so it gets the string. OneHotEncoder, like most transformers, expects 2D data, so it gets the list. Passing 'city' to the encoder, or ['title'] to the vectorizer, gives the transformer the wrong shape. Any transformer slot can hold a whole Pipeline. For a numeric-plus-categorical table, the layout is a ColumnTransformer with two entries. One is an imputer-then-scaler Pipeline applied to the numeric columns, and the other is OneHotEncoder applied to the categorical columns. That ColumnTransformer becomes the first step of an outer Pipeline that ends in the classifier, for example RandomForestClassifier. The result is one object that GridSearchCV can fit, refit and score.
Two other designs fail for different reasons. The first builds a separate Pipeline per column type and concatenates their predict outputs. That produces two partial models instead of one model trained on all its features, and there is no single object to tune or log. The second drops the categorical columns. That throws away signal to make preprocessing easier; whether one-hot encoding suits a particular model type is a separate question, covered in when one-hot encoding is appropriate. ColumnTransformer also accepts arrays, sparse matrices and pandas DataFrames, so the pandas data you collect from a Spark table can go straight in.
Checkpoint 4 of 9· Check yourself
A churn table has numeric columns with missing values and a categorical plan_type column. Which design gives a single model you can tune with GridSearchCV and log as one final artifact?
Inside an outer Pipeline, ColumnTransformer gives each column type its own transformer, so you get one object that GridSearchCV can fit, refit and score, and that you can log as the final model artifact. Encoding everything first treats numeric columns as categories and then distorts the 0/1 indicators. Separate pipelines produce two partial models and no single object to tune. Dropping the column throws away signal.
“After training and tuning hyperparameters, the final model artifact is logged to the tracking server”Source: docs.databricks.com
Checkpoint 5 of 9· Exam question
A training pipeline needs to preprocess a DataFrame containing both numeric columns (impute and scale) and categorical columns (one-hot encode) before fitting a RandomForestClassifier. Which approach correctly composes this into a single scikit-learn object that can be passed to GridSearchCV?
Correct answer: A — Define a ColumnTransformer applying an imputer+scaler pipeline to numeric columns and OneHotEncoder to categorical columns, as the first step of an outer Pipeline ending in the classifier.
- A. A
ColumnTransformeris built specifically to route different column subsets to different transformers and concatenate the results, and nesting it as the first step of an outerPipelinegivesGridSearchCVone composite object to fit and score end to end. - B. One-hot encoding first turns categorical values into binary indicator columns; running an imputer and scaler over those columns afterward misapplies numeric preprocessing to columns whose values are not continuous, which distorts what the encoding represents.
- C. Fitting two pipelines that each only see part of the columns and then combining
predictoutputs does not produce a single feature matrix for the classifier; it discards the classifier's ability to learn from both column types jointly and cannot be scored as one estimator. - D. Tree-based models like
RandomForestClassifiercan consume one-hot encoded categorical features without issue, so dropping those columns throws away potentially predictive information rather than solving a real compatibility problem.
4.Tuning nested pipeline parameters and refitting
Tuning is one step of the training pipeline. You run it on the training data, and the held-out evaluation set stays untouched. Because the preprocessors sit inside the Pipeline, their parameters can join the search next to the model's. An imputer strategy can be tuned alongside the classifier's regularization, and every candidate is fitted fold by fold without leakage.
>>> pipe[:1]
Pipeline(steps=[('reduce_dim', PCA())])
>>> pipe[-1:]
Pipeline(steps=[('clf', SVC())])A search reaches a parameter inside a step through the step's name, a double underscore, and the parameter name: <step_name>__<param>. For a Pipeline whose steps are reduce_dim (a PCA) and clf (an SVC), the grid is {'reduce_dim__n_components': [...], 'clf__C': [...]}. The names involved are the step names, which you chose, not the class names. 'PCA__n_components' points to a step that does not exist. Bare 'n_components' and 'C' do not say which step they belong to. A dot, as in 'clf.C', is not the separator. If you build the pipeline with make_pipeline, it fills in step names automatically, and they are lowercase: ('pca', PCA()) and ('svc', SVC()). Check pipe.steps before writing the grid. The same names are also how set_params replaces or changes individual steps.
'svc__C'. make_pipeline names each step after its class in lowercase, so the step is called 'svc', and the key is that name, a double underscore, and the parameter.
The search itself can be a grid search or a Bayesian search such as Hyperopt fmin (objective, search space, algo, max_evals). Whichever you use, the search only chooses parameters. The pipeline's last tuning action is to refit the full Pipeline, preprocessing included, on the training data with the best parameters. That refitted object is the one you evaluate and log. Databricks now recommends Optuna for single-node tuning or Ray Tune for distributed tuning, and Hyperopt is not included in Databricks Runtime ML after 16.4 LTS ML.
Production retraining usually searches far less. Data scientists may try many algorithms and settings during development, but production training code typically considers only the top-performing options. That saves time and reduces run-to-run variance in automated retraining. If the best hyperparameters are already known, the production pipeline runs with them, typically supplied through a configuration file instead of a fresh search.
Checkpoint 6 of 9· Check yourself
In development, a team tried dozens of algorithm and hyperparameter combinations before settling on one. Their production pipeline now retrains every week on prod catalog tables. How should the tuning step in that production pipeline be set up?
Production training code usually considers only the top-performing options, or runs with hyperparameters already chosen and supplied in a configuration file. This saves time and reduces run-to-run variance from tuning in automated retraining. Code is promoted between environments, not the dev model.
“the model training pipeline deployed in production can be executed using the selected set of hyperparameters, typically included in the pipeline as a configuration file.”Source: docs.databricks.com
Checkpoint 7 of 9· Match them up
You are choosing a tuning library for a new training pipeline on current Databricks Runtime ML. Match each library to how Databricks positions it.
Tap a term, then the definition that fits it.
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.
“Databricks recommends using either Optuna for single-node optimization or RayTune for a similar experience to the deprecated Hyperopt distributed hyperparameter tuning functionality.”Source: docs.databricks.com
Checkpoint 8 of 9· Exam question
A team wants GridSearchCV to search over both n_components for a PCA step and C for an SVC step inside the same Pipeline, where those steps are named reduce_dim and clf respectively. Which param_grid correctly targets these nested parameters?
Correct answer: A — Use {'reduce_dim__n_components': [...], 'clf__C': [...]}, since Pipeline exposes nested step parameters with the <step_name>__<param> double-underscore syntax.
- A. Pipeline's
set_paramsandget_paramsexpose every nested estimator's parameters through the<step_name>__<param>convention, andGridSearchCVrelies on exactly that convention to route grid values to the right step. - B. The prefix must match the name assigned to the step when the pipeline was constructed, not the underlying estimator's class name;
PCA__n_componentswill raise an error unless a step happens to also be namedPCA. - C. Bare parameter names are ambiguous once a pipeline has multiple steps, and
GridSearchCVdoes not infer which step a bare name belongs to, so this raises an invalid-parameter error at fit time. - D. A single dot is not the separator scikit-learn's parameter routing recognizes; the library specifically reserves the double underscore for nested parameter access, so a dot-separated key is treated as an unknown parameter.
5.Evaluating, logging and reproducing the pipeline
Evaluation scores the refitted pipeline on held-out data that played no part in fitting or tuning. Because preprocessing travels inside the pipeline, a single predict call on raw held-out rows applies the training-time imputation, encoding and scaling. Base metrics such as accuracy, AUC or RMSE should be logged to the MLflow run, which links them to the model they describe. Which metric to choose is covered in choosing an evaluation metric.
Logging the whole pipeline as the model records full provenance: the dataset, the code and the environment that produced it. On Databricks the tracking server is hosted. Runs go to the notebook experiment by default, or to a shared workspace experiment once you set one. MLflow autologging can capture scikit-learn training automatically, and manual MLflow logging covers adding extra artifacts by hand.
# Set experiment in the tracking server
mlflow.set_experiment("/Shared/my-experiment")Rerunning the pipeline should give the same model, and there are two separate sources of drift. Many algorithms have random elements such as sampling or random initial conditions, and those are fixed by setting the library's seed. Some algorithms are also sensitive to data order, and distributed ones to partitioning, which a seed does not control. When the training data arrives through Spark, call repartition and sortWithinPartitions before collecting it, so the pipeline sees rows in a stable order.
Checkpoint 9 of 9· Fill the gap
Your training pipeline runs as a scheduled job, and the team wants every run to go to one shared workspace experiment, not the default notebook experiment. Which MLflow call completes this line?
mlflow. ? ("/Shared/my-experiment")mlflow.set_experiment chooses which experiment on the tracking server receives the runs. If no experiment is set, runs go to the notebook experiment. set_tracking_uri chooses the server, not the experiment. start_run opens a run, and autolog turns on automatic logging. Neither one chooses where the runs are stored.
Source: docs.databricks.comSources
(5)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.
“the data scientist begins identifying data preparation and featurization steps for model training”
↩︎ What a training pipeline does on Databricks“After training and tuning hyperparameters, the final model artifact is logged to the tracking server”
↩︎ What a training pipeline does on Databricks“The purpose of evaluation is to determine if the newly developed model performs better than the current production model.”
↩︎ What a training pipeline does on Databricks“When the model training is complete, register the model to Unity Catalog.”
↩︎ What a training pipeline does on Databricks“The output of the development process is ML pipeline code that can include feature computation, model training, inference, and monitoring.”
↩︎ Preprocessing numeric and categorical columns with ColumnTransformer“In the production training code, it's common to consider only the top-performing options.”
↩︎ Tuning nested pipeline parameters and refitting“executed using the selected set of hyperparameters, typically included in the pipeline as a configuration file”
↩︎ Tuning nested pipeline parameters and refitting“Evaluate model quality by testing on held-out data.”
↩︎ Evaluating, logging and reproducing the pipeline“Limiting tuning in this way saves time and can reduce the variance from tuning in automated retraining.”
↩︎ Exam trap 4“The output of the development process is ML pipeline code that can include feature computation, model training, inference, and monitoring.”
↩︎ Checkpoint“After training and tuning hyperparameters, the final model artifact is logged to the tracking server”
↩︎ Checkpoint“the model training pipeline deployed in production can be executed using the selected set of hyperparameters, typically included in the pipeline as a configuration file.”
↩︎ Checkpoint - 2.https://scikit-learn.org/stable/modules/compose.htmlSecondary source
“Incorporating statistics from test data into the preprocessors makes cross-validation scores unreliable (known as data leakage)”
↩︎ Fit preprocessing on training data only“The ColumnTransformer helps performing different transformations for different columns of the data”
↩︎ Preprocessing numeric and categorical columns with ColumnTransformer“OneHotEncoder as most of other transformers expects 2D data”
↩︎ Preprocessing numeric and categorical columns with ColumnTransformer“the CountVectorizer expects a 1D array as input and therefore the columns were specified as a string ('title')”
↩︎ Preprocessing numeric and categorical columns with ColumnTransformer“ColumnTransformer works on arrays, sparse matrices, and pandas DataFrames.”
↩︎ Preprocessing numeric and categorical columns with ColumnTransformer“You may want to include the parameters of the preprocessors in a parameter search.”
↩︎ Tuning nested pipeline parameters and refitting“Like Pipeline, individual steps may be replaced using set_params”
↩︎ Tuning nested pipeline parameters and refitting“Incorporating statistics from test data into the preprocessors makes cross-validation scores unreliable (known as data leakage)”
↩︎ Key concept“Incorporating statistics from test data into the preprocessors makes cross-validation scores unreliable (known as data leakage)”
↩︎ Exam trap 1“it takes a variable number of estimators and returns a pipeline, filling in the names automatically”
↩︎ Exam trap 2“within a Pipeline that is safe from data leakage and that can be parametrized”
↩︎ Prediction - 3.
“leverage MLflow tracking to record dependencies, verify reproducibility, and avoid training-serving skew.”
↩︎ Fit preprocessing on training data only“For all metrics, log metrics in MLflow runs to link them to their corresponding models.”
↩︎ Evaluating, logging and reproducing the pipeline“Log models with MLflow to store model artifacts with full provenance: which dataset, which code, and which environment produced this model.”
↩︎ Evaluating, logging and reproducing the pipeline“leverage MLflow tracking to record dependencies, verify reproducibility, and avoid training-serving skew”
↩︎ Checkpoint - 4.
“Databricks recommends using either Optuna for single-node optimization or RayTune for a similar experience to the deprecated Hyperopt distributed hyperparameter tuning functionality.”
↩︎ Tuning nested pipeline parameters and refitting“Hyperopt is not included in Databricks Runtime for Machine Learning after 16.4 LTS ML.”
↩︎ Exam trap 3 - 5.https://docs.databricks.com/aws/en/mlflow/trackingOfficial docs
“MLflow can automatically log training code written in many machine learning and deep learning frameworks.”
↩︎ Evaluating, logging and reproducing the pipeline“Many libraries offer a seeding mechanism to fix the initial conditions for these stochastic elements.”
↩︎ Evaluating, logging and reproducing the pipeline“To control variation caused by differences in ordering and partitioning, use the PySpark functions repartition and sortWithinPartitions.”
↩︎ Evaluating, logging and reproducing the pipeline