CertSafari
    Databricks Certified Machine Learning Associate· Lessons

    Domain 3 · Lesson 31/48

    Building a leakage-safe training pipeline on Databricks

    Develop a training pipeline

    17 min read
    2.07% of exam
    5 sources
    Published 22 Oct 2026
    Docs as of 17 Oct 2026

    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.

    Stages of a model training pipeline and what each one produces
    StageWhat happensOutput
    Load and featurizeRead tables from the dev or prod catalog and apply data preparation and featurizationTraining data with features and label
    Training and tuningFit the model and tune hyperparameters, logging parameters, metrics and artifactsFinal model artifact logged to the MLflow Tracking server
    EvaluationTest on held-out data and log the resultsMetrics that compare the new model with the production model
    RegisterRegister the model to the catalog of the environment the pipeline ran inA 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?

    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?

    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?

    Sources23

    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.

    A ColumnTransformer that one-hot encodes one column and vectorizes another, dropping the restpython
    >>> 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?

    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?

    Sources21

    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.

    Pipeline steps keep the names you give them: reduce_dim and clf, not PCA and SVCpython
    >>> 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.

    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?

    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.

    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?

    Sources241

    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.

    Pointing a training pipeline's runs at a shared workspace experimentpython
    # 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")

    Sources135

    Sources

    (5)

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

    1. 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. 2.
      “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. 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. 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. 5.
      “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

    Ready to test yourself?

    Practise the 7 questions on this subdomain.

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