CertSafari
    Databricks Certified Machine Learning Associate· Lessons

    Domain 3 · Lesson 36/48

    Cross-validation in model fitting with cross_val_score, cross_validate and tuning

    Perform cross-validation as a part of model fitting.

    18 min read
    2.07% of exam
    7 sources
    Published 22 Oct 2026
    Docs as of 30 Sep 2026

    What you will be able to do

    • Run k-fold cross-validation with cross_val_score and cross_validate, and choose their cv and scoring arguments
    • Wrap preprocessing and model in one pipeline so every fold refits it from scratch
    • Pick the splitter that matches the data: StratifiedKFold for imbalanced classes, a time-ordered splitter for temporal data, CrossValidator in Spark
    • Use the mean cross-validated score as the objective in hyperparameter tuning, and count the fits a grid search with cross-validation runs

    Key concept

    Cross-validated score — One number built from k separate fits: each fold is held out once, a model trained on the other folds is scored on it, and the k scores are averaged. That average, not any single fold's score, is the estimate you report and optimise.

    1.How a cross-validated score is computed

    Cross-validation estimates how a model will do on data it has never seen. It does this by fitting the model several times, each time on a different part of the data, and scoring each fit on rows that fit never trained on. Why use rotating folds rather than one fixed holdout? That trade-off is covered in k-fold cross-validation vs a single train-validation split. This page is about running it.

    In k-fold cross-validation the training data is cut into k folds. For each fold, a model is trained on the other k−1 folds, and the resulting model is validated on the remaining part of the data. Every row is held out exactly once, so with cv=5 you get five fits and five scores, and the reported figure is their mean.

    Take a data scientist with only 500 labelled rows. Scoring the model on the rows it was trained on is the classic mistake: a model that memorised the labels would have a perfect score but would fail to predict anything useful on yet-unseen data. A single fixed 90/10 split avoids that mistake but stakes everything on 50 rows, and its result depends on which 50 rows the split happened to pick. Five rotating folds use all 500 rows for both training and scoring, and averaging five scores gives a steadier estimate than any one of them. On a dataset this small, cross-validation does not waste too much data, which is why it beats setting aside a fixed validation set here.

    cross_val_score fits and scores an SVC five times, once per fold, and returns one score per foldpython
    >>> from sklearn.model_selection import cross_val_score
    >>> clf = svm.SVC(kernel='linear', C=1, random_state=42)
    >>> scores = cross_val_score(clf, X, y, cv=5)
    >>> scores
    array([0.96, 1. , 0.96, 0.96, 1. ])

    Report the result as the mean together with its spread across folds. In the example above that comes to scores.mean() of 0.98 and scores.std() of 0.02. A small standard deviation means the folds agree. A large one means the score depends heavily on which rows land in the held-out fold.

    Checkpoint 1 of 9· Fill the gap

    This sample should fit and score the SVC five times: each fold is held out once and scored by a model trained on the other four. Which keyword argument completes the call?

    >>> from sklearn.model_selection import cross_val_score
    >>> clf = svm.SVC(kernel='linear', C=1, random_state=42)
    >>> scores = cross_val_score(clf, X, y,  ? =5)
    >>> scores
    array([0.96, 1. , 0.96, 0.96, 1. ])

    Checkpoint 2 of 9· Exam question

    A data scientist has only 500 labeled rows and wants a robust, low-variance estimate of a scikit-learn classifier's generalization performance without permanently setting aside data as a fixed holdout. Which approach best fits this goal?

    Sources12

    2.The cv and scoring arguments of cross_val_score and cross_validate

    The cv argument controls how the data is split. An integer sets the number of folds and picks the default splitter: KFold for regressors, StratifiedKFold for classifiers. You can also pass a splitter object such as ShuffleSplit(n_splits=5, test_size=0.3, random_state=0), or any iterable that yields (train, test) index arrays. This is how you plug in the data-specific splitters described further down. Databricks' own scikit-learn tuning notebooks start from the same import, from sklearn.model_selection import cross_val_score.

    The scoring argument controls what is measured on each held-out fold. Left unset, it uses the estimator's own score method, which means accuracy for classifiers and R² for regressors. Pass a string such as 'f1_macro' or 'recall_macro' to use a named metric instead. Every scorer follows one convention: higher is better. Error metrics are therefore exposed in negated form, so mean squared error is 'neg_mean_squared_error' and its fold scores come back as negative numbers. A metric that needs extra parameters, such as fbeta_score with beta=2, must first be wrapped with make_scorer. A misspelled scoring name raises an InvalidParameterError.

    cross_validate is the richer sibling. It accepts several metrics at once, as a list of names, a dict of name to scorer, or a callable that returns a dict. It returns a dict rather than an array, with fit_time, score_time and one test_<name> key per metric. Training-set scores are left out unless you set return_train_score=True, because computing them costs time. return_estimator=True keeps the model fitted on each fold, and return_indices=True keeps each fold's row indices.

    cross_validate with two metrics returns timing keys plus one test_ key per metricpython
    >>> from sklearn.model_selection import cross_validate
    >>> from sklearn.metrics import recall_score
    >>> scoring = ['precision_macro', 'recall_macro']
    >>> clf = svm.SVC(kernel='linear', C=1, random_state=0)
    >>> scores = cross_validate(clf, X, y, scoring=scoring)
    >>> sorted(scores.keys())
    ['fit_time', 'score_time', 'test_precision_macro', 'test_recall_macro']

    Checkpoint 3 of 9· Check yourself

    A teammate needs to report how well a regressor will generalise. They run cross_val_predict with cv=5, then compute R² once on the full array of pooled predictions. What is wrong with this approach?

    Checkpoint 4 of 9· Check yourself

    Two regressors are compared with cross_val_score(..., scoring='neg_mean_squared_error'). Model A's mean fold score is -12.4 and model B's is -30.1. Which reading is correct?

    Sources342

    3.Refitting the whole pipeline inside every fold

    A preprocessing step learns parameters, such as a scaler's mean and variance. Those parameters must be learned from training rows only, which is why preprocessing and model belong in one pipeline, as explained in Fit preprocessing on training data only (leakage-safe Pipeline). Cross-validation applies the same rule fold by fold: each fold's "training rows" are the other k−1 folds.

    When you pass a pipeline to cross_val_score, the whole pipeline is refitted inside every fold. In fold one the scaler learns its statistics from folds two to five, then transforms fold one using those statistics. In fold two it starts over. The held-out fold never contributes to any parameter that is used to score it. This applies to every learned transformation, including standardisation and feature selection.

    Passing a scaler-plus-SVC pipeline to cross_val_score refits the scaler on each fold's training rowspython
    >>> from sklearn.pipeline import make_pipeline
    >>> clf = make_pipeline(preprocessing.StandardScaler(), svm.SVC(C=1))
    >>> cross_val_score(clf, X, y, cv=cv)
    array([0.977, 0.933, 0.955, 0.933, 0.977])

    The failure this prevents is easy to commit. Suppose you call StandardScaler().fit_transform(X) on the full dataset and then cross-validate only the SVC. Every fold is now scored on rows whose scaling was computed partly from those same rows, so the reported mean is an optimistic estimate of how the model generalises. The same pattern holds in Spark ML, where pipelines and cross-validation sit side by side in the same tuning toolkit: give the cross-validator the whole pipeline, not just the final model.

    Checkpoint 5 of 9· Fill the gap

    The cross-validated score should come from refitting the StandardScaler on each fold's training rows only, so the held-out fold never influences its own scaling. Which function goes in the blank?

    >>> clf =  ? (preprocessing.StandardScaler(), svm.SVC(C=1))
    >>> cross_val_score(clf, X, y, cv=cv)
    array([0.977, 0.933, 0.955, 0.933, 0.977])

    Sources52

    4.Matching the splitter to the data

    The default splitters assume that rows are independent and that any fold looks like any other. That assumption breaks in three common situations: rare classes, time order and repeated subjects. In each one, a plain split produces folds that misrepresent the data, even though the code runs without complaint.

    StratifiedKFold keeps roughly 1 positive in 10 in every fold; KFold puts all 5 positives into one test foldpython
    >>> from sklearn.model_selection import StratifiedKFold, KFold
    >>> import numpy as np
    >>> X, y = np.ones((50, 1)), np.hstack(([0] * 45, [1] * 5))
    >>> skf = StratifiedKFold(n_splits=3)
    >>> for train, test in skf.split(X, y):
    ...     print('train -  {}   |   test -  {}'.format(
    ...         np.bincount(y[train]), np.bincount(y[test])))
    train -  [30  3]   |   test -  [15  2]
    train -  [30  3]   |   test -  [15  2]
    train -  [30  4]   |   test -  [15  1]
    >>> kf = KFold(n_splits=3)
    >>> for train, test in kf.split(X, y):
    ...     print('train -  {}   |   test -  {}'.format(
    ...         np.bincount(y[train]), np.bincount(y[test])))
    train -  [28  5]   |   test -  [17]
    train -  [28  5]   |   test -  [17]
    train -  [34]   |   test -  [11  5]

    For imbalanced classes, such as a 95/5 fraud or screening dataset, use StratifiedKFold. Each of its folds contains approximately the same percentage of each class as the full set. Without stratification, a fold with no positives makes metrics such as ROC AUC undefined, and the fit can even raise an exception. Plain KFold and ShuffleSplit cannot help, because neither looks at the labels. LeaveOneOut cannot help either: it holds out a single row per fit. Databricks AutoML applies the same idea to its own splits, using a stratified random split for classification so every class is represented in training, validation and test.

    Time-ordered data needs a different splitter. KFold and ShuffleSplit assume independent rows. Shuffled folds would let a model train on next month and be scored on last month, so the estimate looks better than any real forecast could be. TimeSeriesSplit always trains on earlier rows and tests on the rows that follow, and each training set is a superset of the one before it. Databricks AutoML does the same for forecasting: it extends the training window chronologically and validates on later time points.

    Which splitter to pass as cv
    SplitterHow it splitsUse it when
    KFoldk folds of equal size, ignoring labels and groupsRegression or balanced classification on independent rows
    StratifiedKFoldk folds, each keeping the overall class proportionsClassification, especially with a rare class
    ShuffleSplitA chosen number of independent random train/test splitsYou want direct control over the number of iterations and the test fraction
    GroupKFoldThe same group never appears in both a training and a test foldSeveral rows per patient, subject or device
    TimeSeriesSplitTrain on earlier rows, test on the next block; training sets growData collected over time
    LeaveOneOutn fits, each holding out a single rowRarely: it is costly, and 5- or 10-fold is generally preferred

    Checkpoint 6 of 9· Check yourself

    A team is building a model to forecast next month's demand from five years of monthly sales records. They want a cross-validated score that reflects how the model will perform on future months. Which splitter should they pass as cv?

    Checkpoint 7 of 9· Exam question

    A binary classification dataset is severely imbalanced, with 95% negative and 5% positive labels. An engineer wants to run k-fold cross-validation while keeping the same 95/5 class ratio inside every fold. Which cross-validator should they use?

    Sources612

    5.Cross-validation as the objective inside hyperparameter tuning

    Hyperparameter tuning compares candidate settings, and cross-validation provides the number each candidate is judged by. Each candidate is cross-validated in full, and its mean fold score becomes the value the search compares. A noisy score from a single split could favour a candidate that simply drew an easy validation set. A mean over folds makes that much less likely.

    A Hyperopt objective that scores each candidate C by its mean cross-validated accuracy and returns the negated value as the losspython
    def objective(C):
        # Create a support vector classifier model
        clf = SVC(C=C)
    
        # Use the cross-validation accuracy to compare the models' performance
        accuracy = cross_val_score(clf, X, y).mean()
    
        # Hyperopt tries to minimize the objective function. A higher accuracy value means a better model, so you must return the negative accuracy.
        return {'loss': -accuracy, 'status': STATUS_OK}

    Two details in that objective are easy to get wrong. First, .mean() turns five fold scores into a single scalar, which is the only kind of value the optimiser can compare. Second, the sign is flipped. fmin minimises, so an objective that returned accuracy itself would steer the search toward the worst model. With an error metric such as 'neg_mean_squared_error', the scorer has already negated the error, so negate the mean again to get a positive loss. How fmin and search spaces work is covered in Hyperopt's fmin. Note that Hyperopt is not included in Databricks Runtime ML after 16.4 LTS ML.

    scikit-learn's GridSearchCV builds the same loop for you. It takes a param_grid, a cv and a scoring argument, and cross-validates every combination in the grid. That makes the cost easy to work out: each candidate costs one fit per fold. Take a grid of 3 max_depth values × 4 n_estimators values. That is 12 candidates, and with cv=5 the search runs 12 × 5 = 60 fits. Counting 12 fits ignores the folds, while 15 or 20 adds the two dimensions instead of multiplying them. The full counting rules are in counting models in grid search with cross-validation.

    On Spark DataFrames, the equivalent is Spark ML's CrossValidator, which is also available in the pyspark.ml.connect module used with Databricks Connect. It wraps an estimator or pipeline, a parameter grid and an evaluator, and runs the same per-fold refitting on the cluster. To track these tuning runs in MLflow, use PySpark ML autologging (mlflow.pyspark.ml.autolog()), which is enabled by default through Databricks Autologging.

    Checkpoint 8 of 9· Check yourself

    In a Hyperopt objective for a regressor, each candidate is scored with cross_val_score(reg, X, y, scoring='neg_mean_squared_error'). What should the objective return as 'loss' so that fmin moves toward the lowest error?

    Checkpoint 9 of 9· Exam question

    A team configures GridSearchCV with a param_grid covering 3 values for max_depth and 4 values for n_estimators, and sets cv=5. How many individual model fits does this search perform in total?

    Sources3574

    Sources

    (7)

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

    1. 1.
      “Cross-validation provides a robust evaluation of a model's performance over different segments of time.”
      ↩︎ How a cross-validated score is computed
      “This method incrementally extends the training dataset chronologically and performs validation on subsequent time points.”
      ↩︎ Matching the splitter to the data
    2. 2.
      “the resulting model is validated on the remaining part of the data”
      ↩︎ How a cross-validated score is computed
      “would have a perfect score but would fail to predict anything useful on yet-unseen data”
      ↩︎ How a cross-validated score is computed
      “the results can depend on a particular random choice for the pair of (train, validation) sets.”
      ↩︎ How a cross-validated score is computed
      “does not waste too much data (as is the case when fixing an arbitrary validation set)”
      ↩︎ How a cross-validated score is computed
      “It allows specifying multiple metrics for evaluation.”
      ↩︎ The cv and scoring arguments of cross_val_score and cross_validate
      “A Pipeline makes it easier to compose estimators, providing this behavior under cross-validation:”
      ↩︎ Refitting the whole pipeline inside every fold
      “each set contains approximately the same percentage of samples of each target class as the complete set”
      ↩︎ Matching the splitter to the data
      “classical cross-validation techniques such as KFold and ShuffleSplit assume the samples are independent and identically distributed”
      ↩︎ Matching the splitter to the data
      “successive training sets are supersets of those that come before them.”
      ↩︎ Matching the splitter to the data
      “GroupKFold is a variation of K-fold which ensures that the same group is not represented in both testing and training sets.”
      ↩︎ Matching the splitter to the data
      “As a general rule, most authors and empirical evidence suggest that 5 or 10-fold cross validation should be preferred to LOO.”
      ↩︎ Matching the splitter to the data
      “The performance measure reported by k-fold cross-validation is then the average of the values computed in the loop.”
      ↩︎ Key concept
      “Thus, cross_val_predict is not an appropriate measure of generalization error.”
      ↩︎ Exam trap 1
      “Note that KFold is not affected by classes or groups.”
      ↩︎ Exam trap 2
      “should be learnt from a training set and applied to held-out data for prediction”
      ↩︎ Exam trap 4
      “cross_val_score uses the KFold or StratifiedKFold strategies by default, the latter being used if the estimator derives from ClassifierMixin.”
      ↩︎ Prediction
      “cross_val_predict simply returns the labels (or probabilities) from several distinct models undistinguished. Thus, cross_val_predict is not an appropriate measure of generalization error.”
      ↩︎ Checkpoint
      “cross-validation splitting can generate train or validation folds without any occurrence of a particular class.”
      ↩︎ Prediction
    3. 3.
      “from sklearn.model_selection import cross_val_score”
      ↩︎ The cv and scoring arguments of cross_val_score and cross_validate
      “Use the cross-validation accuracy to compare the models' performance”
      ↩︎ Cross-validation as the objective inside hyperparameter tuning
      “Hyperopt is not included in Databricks Runtime for Machine Learning after 16.4 LTS ML.”
      ↩︎ Cross-validation as the objective inside hyperparameter tuning
      “Hyperopt tries to minimize the objective function. A higher accuracy value means a better model, so you must return the negative accuracy.”
      ↩︎ Exam trap 3
    4. 4.
      “All scorer objects follow the convention that higher return values are better than lower return values.”
      ↩︎ The cv and scoring arguments of cross_val_score and cross_validate
      “take a scoring parameter that controls what metric they apply to the estimators evaluated.”
      ↩︎ Cross-validation as the objective inside hyperparameter tuning
      “like metrics.mean_squared_error, are available as ‘neg_mean_squared_error’ which return the negated value of the metric.”
      ↩︎ Checkpoint
    5. 5.
      “The pyspark.ml.connect module consists of common learning algorithms and utilities, including classification, feature transformers, ML pipelines, and cross validation.”
      ↩︎ Refitting the whole pipeline inside every fold
      “Model tuning: pyspark.ml.connect.tuning.CrossValidator”
      ↩︎ Cross-validation as the objective inside hyperparameter tuning
    6. 6.
      “For classification, a stratified random split ensures that each class is adequately represented in the training, validation, and test sets.”
      ↩︎ Matching the splitter to the data
    7. 7.
      “Instead, use MLflow PySpark ML autologging by calling mlflow.pyspark.ml.autolog(), which is enabled by default with Databricks Autologging.”
      ↩︎ Cross-validation as the objective inside hyperparameter tuning

    Ready to test yourself?

    Practise Databricks Certified Machine Learning Associate in quiz mode.

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