CertSafari
    Databricks Certified Machine Learning Associate· Lessons

    Domain 3 · Lesson 37/48

    Counting models in grid search with cross-validation

    Identify the number of models being trained in conjunction with a grid-search and cross-validation process.

    14 min read
    2.07% of exam
    4 sources
    Published 22 Oct 2026
    Docs as of 30 Sep 2026

    What you will be able to do

    • Compute the number of hyperparameter combinations in a grid as the product of each parameter's list length
    • Compute the total model fits for a grid search with k-fold cross-validation, with and without the final refit
    • Work backwards from a fit budget to the largest grid that stays within it
    • Count the models trained when cross-validation runs inside a Hyperopt objective
    • Tell apart the settings that change the model count from the settings that only change wall-clock time

    Key concept

    Model-fit count — The number of times an estimator is trained during tuning. With grid search and k-fold cross-validation it is (product of the grid's list lengths) × k, plus one more fit when the best combination is refit on the full training data.

    1.Why the number of fits is the cost of tuning

    Every hyperparameter search is a loop that trains models, and the number of trips through that loop decides what the search costs. A gradient-boosted model that takes four minutes to fit costs two hours over 30 fits and more than six hours over 100. Before you start a search on a shared cluster, count the fits. Going by intuition gets it wrong by a factor of five or ten, because two of the multipliers are hidden in default arguments.

    The unit you count is one fit: one estimator trained once, on one set of training rows, with one setting of hyperparameters. Hyperopt uses the same unit for a trial. Its max_evals argument is the number of settings to try, and each setting produces at least one model. Each layer of a search multiplies that unit. The grid sets how many settings there are, cross-validation sets how many times each setting is trained, and a final refit can add one more model at the end.

    Checkpoint 1 of 8· Check yourself

    A tuning job tries 4 hyperparameter combinations. Each combination is trained on 3 different sets of training rows, and no final refit is done. Counting the way this lesson does, how many fits does the job run?

    Sources1

    2.Grid size is the product of the list lengths

    A grid search tries every combination of the candidate values you list, so a grid is a Cartesian product. Random and Bayesian search sample from a space instead of enumerating it, and Grid vs random vs Bayesian hyperparameter search explains when each one fits. For counting, the rule for a grid is simple: multiply the length of each parameter's list. Two values of one parameter and three of another give 2 × 3 = 6 combinations. Adding a third parameter with four values gives 24. Each new parameter multiplies the count. It never adds to it.

    A GridSearchCV grid over a pipeline: 3 reduction options × 2 classifiers × 3 values of Cpython
    >>> param_grid = dict(reduce_dim=['passthrough', PCA(5), PCA(10)],
    ...                   clf=[SVC(), LogisticRegression()],
    ...                   clf__C=[0.1, 10, 100])
    >>> grid_search = GridSearchCV(pipe, param_grid=param_grid)

    The grid has 3 × 2 × 3 = 18 combinations. Each one is a separate setting that has to be trained. None of them can borrow a fitted model from another. Spark ML builds grids the same way: every addGrid call on a ParamGridBuilder multiplies the number of parameter maps that build() returns. The size of a grid never depends on which library made it.

    Checkpoint 2 of 8· Fill the gap

    This search has to train every one of the 3 × 2 × 3 combinations rather than sample only some of them. Which class completes the last line?

    >>> param_grid = dict(reduce_dim=['passthrough', PCA(5), PCA(10)],
    ...                   clf=[SVC(), LogisticRegression()],
    ...                   clf__C=[0.1, 10, 100])
    >>> grid_search =  ? (pipe, param_grid=param_grid)

    Sources1

    3.Folds multiply the grid; refit adds one

    Cross-validation trains a new model for every fold. In k-fold CV, each fold's model is trained on the other k − 1 folds and scored on the fold that was held out. The benefits and costs of this compared with a single split are covered in k-fold cross-validation vs a single train-validation split. The part that matters for counting is that no model is reused across folds. Each combination in the grid is therefore trained k times, and the search performs combinations × k fits.

    After the search, one more model is usually trained. With refit=True, which is the default, scikit-learn's GridSearchCV retrains the winning combination on the whole training set, so it has a model to predict with. That adds exactly one fit, not one per fold and not one per combination. With refit=False the search stops when scoring ends and there is no extra fit. A team might turn refit off because a separate holdout set will choose the deployment model. In Spark ML, CrossValidator always refits the best parameter map on the full dataset to produce its bestModel. numFolds, which defaults to 3, plays the role of k.

    Total fits = grid size × folds, plus one when the best combination is refit
    GridFoldsFits during searchRefit on full dataTotal fits
    3 values × 2 values = 6530Yes (+1)31
    12 combinations448No48
    3 × 2 × 3 = 18590Yes (+1)91
    4 values × 3 values = 12560No60

    The same formula, run backwards, fits a search to a budget. Say you can afford at most 60 fits in the search phase with 5-fold CV. One parameter has 4 candidate values and the other has k. You need 4 × k × 5 ≤ 60, so 20k ≤ 60 and k ≤ 3. With three values the search uses exactly 60 fits. A fourth value takes it to 4 × 4 × 5 = 80. Dividing the budget by the fold count first (60 / 5 = 12 combinations) and then by the known list length (12 / 4 = 3) gives the same answer quickly.

    Checkpoint 3 of 8· Check yourself

    With refit=False, GridSearchCV searches learning_rate: [0.01, 0.05, 0.1, 0.3] and max_depth: [3, 6, 9] using cv=3. How many models does it train in total?

    Checkpoint 4 of 8· Exam question

    A data scientist configures a scikit-learn GridSearchCV on Databricks with a parameter grid containing n_estimators: [100, 200, 300] and max_depth: [4, 8], using cv=5 and the default refit=True. How many total model fits does this search perform, including the final refit on the full training set?

    Checkpoint 5 of 8· Exam question

    A data scientist runs GridSearchCV with a grid producing 12 hyperparameter combinations, cv=4, and refit=False because a separate holdout set will be used to pick the deployment model. How many total model fits occur during this search?

    Checkpoint 6 of 8· Exam question

    A data scientist has a fixed compute budget of at most 60 model fits for a search phase using 5-fold cross-validation, and wants to tune two hyperparameters where one has 4 candidate values and the other has an unknown number of candidate values k. What is the largest integer value of k that keeps the total number of search fits within the budget?

    Sources23

    4.Cross-validation inside a Hyperopt objective

    The multiplication still applies when the search is not a grid. Hyperopt's fmin calls the objective function max_evals times. If the objective runs cross-validation, every one of those calls trains k models. How to write CV into an objective is covered in Running cross-validation (cross_val_score, cross_validate, CV inside tuning). For counting, the Databricks SVM example below is a useful case: cross_val_score is called with no cv argument, so it uses scikit-learn's default of 5 folds.

    An objective that scores each Hyperopt trial with cross-validation, so every trial trains one model per foldpython
    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()

    That notebook runs fmin with max_evals=16, so the search trains 16 × 5 = 80 models. fmin returns only the best hyperparameter values and keeps no fitted model. To get a model you can deploy, you train once more on the full data, which makes 81 fits in total. Here the refit is a step you write yourself, not a default that happens for you. Hyperopt is no longer included in Databricks Runtime ML after 16.4 LTS ML. The counting is the same for any tuner that runs CV inside each trial: trials × k, plus the final refit.

    Checkpoint 7 of 8· Check yourself

    Your Hyperopt objective scores each trial with cross_val_score(clf, X, y, cv=3), and fmin runs with max_evals=20. After the search, you need a model you can deploy. How many fits does the whole job take?

    Sources42

    5.Parallelism changes the time, not the count

    Parallelism settings decide how many fits run at once, not how many there are. SparkTrials(parallelism=...), the parallelism parameter on Spark ML's CrossValidator, and n_jobs in scikit-learn all spread a fixed set of fits across more workers. A 91-fit search with parallelism 8 is still 91 fits. It finishes sooner and uses more slots while it runs. If a question asks how many models are trained, ignore the parallelism value. It belongs in the wall-clock estimate, which is roughly total fits ÷ parallelism × time per fit.

    Some settings do change the count, and each one maps to a term in the formula. A value added to a parameter's list grows the grid. Raising the fold count from 3 to 5 multiplies every combination's cost by 5/3. Turning refit on or off adds or removes one fit. Raising max_evals adds trials. Switching from CrossValidator to TrainValidationSplit cuts the per-combination cost from k fits to one. This is the main reason to make that switch on a large grid when the data is big enough that one validation split is reliable.

    Checkpoint 8 of 8· Check yourself

    A Spark ML CrossValidator search over a 4 × 4 grid with numFolds=5 is training too many models. Which change leaves the number of models trained the same?

    Sources14

    Sources

    (4)

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

    1. 1.
      “In Hyperopt, a trial generally corresponds to fitting one model on one setting of hyperparameters.”
      ↩︎ Why the number of fits is the cost of tuning
      “Number of hyperparameter settings to try (the number of models to fit).”
      ↩︎ Grid size is the product of the list lengths
      “For a fixed max_evals, greater parallelism speeds up calculations”
      ↩︎ Parallelism changes the time, not the count
      “Number of hyperparameter settings to try (the number of models to fit).”
      ↩︎ Exam trap 3
    2. 2.
      “when you run tuning code that uses CrossValidator or TrainValidationSplit, hyperparameters and evaluation metrics are automatically logged in MLflow”
      ↩︎ Folds multiply the grid; refit adds one
      “Hyperopt is not included in Databricks Runtime for Machine Learning after 16.4 LTS ML.”
      ↩︎ Cross-validation inside a Hyperopt objective
    3. 3.
      “the resulting model is validated on the remaining part of the data”
      ↩︎ Folds multiply the grid; refit adds one
      “the resulting model is validated on the remaining part of the data”
      ↩︎ Exam trap 1
      “This approach can be computationally expensive, but does not waste too much data”
      ↩︎ Exam trap 2
      “fitting a model and computing the score 5 consecutive times (with different splits each time)”
      ↩︎ Checkpoint
      “splitting the data, fitting a model and computing the score 5 consecutive times (with different splits each time)”
      ↩︎ Prediction
      “The following procedure is followed for each of the k “folds”:”
      ↩︎ Checkpoint
      “A model is trained using \(k-1\) of the folds as training data;”
      ↩︎ Checkpoint
    4. 4.
      “Set max_evals to the maximum number of points in hyperparameter space to test, that is, the maximum number of models to fit and evaluate.”
      ↩︎ Cross-validation inside a Hyperopt objective
      “parallelism: Number of models to fit and evaluate concurrently.”
      ↩︎ Parallelism changes the time, not the count
      “Set max_evals to the maximum number of points in hyperparameter space to test, that is, the maximum number of models to fit and evaluate.”
      ↩︎ Key concept
      “parallelism: Number of models to fit and evaluate concurrently.”
      ↩︎ Exam trap 4

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