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?
One fit is one estimator trained once, on one set of training rows, with one hyperparameter setting. Each of the 4 settings is trained on 3 different sets of rows, so the job runs 4 × 3 = 12 fits. The question rules out a refit, so there is no 13th fit.
“fitting a model and computing the score 5 consecutive times (with different splits each time)”Source: scikit-learn.org
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.
>>> 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)GridSearchCV runs a grid search, which tries every combination of the listed values. That makes 3 × 2 × 3 = 18 settings, and each one is trained. RandomizedSearchCV samples from the space instead of going through all of it. cross_val_score scores one estimator and does not search. ParamGridBuilder is Spark ML's grid builder, not a scikit-learn search class.
Source: scikit-learn.orgSources1
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.
| Grid | Folds | Fits during search | Refit on full data | Total fits |
|---|---|---|---|---|
| 3 values × 2 values = 6 | 5 | 30 | Yes (+1) | 31 |
| 12 combinations | 4 | 48 | No | 48 |
| 3 × 2 × 3 = 18 | 5 | 90 | Yes (+1) | 91 |
| 4 values × 3 values = 12 | 5 | 60 | No | 60 |
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.
- A single split is like k = 1, so each combination is trained once (12 fits). The best parameter map is then refit on the full data. With CrossValidator and numFolds=3, the same grid would cost 12 × 3 + 1 = 37.
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?
The grid has 4 × 3 = 12 combinations. Each fold trains on different rows, so every combination needs a new model for each of the 3 folds, which gives 36 fits. With refit=False there is no extra fit at the end, so 37 is wrong.
“The following procedure is followed for each of the k “folds”:”Source: scikit-learn.org
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?
Correct answer: A — 31 fits, from 6 hyperparameter combinations evaluated across 5 folds plus one refit on the entire training set
- A. The grid has 3 values for
n_estimatorsand 2 formax_depth, giving 6 combinations, and each combination is trained and validated once per fold undercv=5, producing 6 x 5 = 30 fits during the search. With the defaultrefit=True, scikit-learn then trains one additional model on the entire training set using the best-found parameters, bringing the total to 31. - B. This correctly computes the 30 search fits from 6 combinations times 5 folds, but it wrongly assumes no additional training happens afterward.
GridSearchCVdefaults torefit=True, so a final model is always retrained on the full dataset unless the caller explicitly passesrefit=False. - C. Adding combinations and folds instead of multiplying them misrepresents how cross-validated grid search works. Every hyperparameter combination is evaluated against every fold independently, so the counts multiply rather than sum, making this total far too low.
- D. This treats grid search as if one model were fit per combination and simply scored differently per fold, but that is not how cross-validation works. Each fold requires training a fresh model on that fold's training split, so the fold count is a true multiplier, not a reused artifact.
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?
Correct answer: A — 48 fits, since the 12 combinations are each trained once per fold and no refit model is added because refit is disabled
- A. Every one of the 12 hyperparameter combinations is trained and validated once for each of the 4 folds, giving 12 x 4 = 48 fits. Setting
refit=Falseonly removes the final full-dataset retraining step, so the search-phase count itself is unaffected. - B. This assumes
refit=Falseis ignored, but scikit-learn'sGridSearchCVrespects that flag explicitly and skips the final full-dataset model whenever it is set. No hidden extra fit occurs beyond the 48 search fits, so this total overstates the work performed. - C. This confuses
refit=Falsewith skipping cross-validation entirely, but the flag only controls the optional final model trained on the full dataset. Every fold still requires training a separate model per combination, so far more than 12 fits occur. - D. Combining 12 combinations and 4 folds by addition rather than multiplication misrepresents the nested loop structure of cross-validated grid search, where every combination is retrained from scratch on each fold's training split.
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?
Correct answer: A — 3, because 4 times k times 5 folds must stay at or under 60, and 4 x 3 x 5 = 60 while 4 x 4 x 5 = 80 exceeds the budget
- A. Total fits equal the product of all hyperparameter candidate counts and the fold count, so 4 x k x 5 <= 60 simplifies to k <= 3. Testing k=3 gives exactly 60 fits, while k=4 gives 80 fits and exceeds the stated budget, making 3 the largest value that fits.
- B. This assumes the two hyperparameters must have equal candidate counts to respect the budget, which is not how the arithmetic works. Setting k=4 produces 4 x 4 x 5 = 80 fits, which is well over the 60-fit budget regardless of whether the grid looks balanced.
- C. Treating the fold count as something the budget is divided by rather than multiplied by inverts the actual relationship. Cross-validation folds multiply the combination count to produce total fits, so this approach systematically overestimates how many candidate values fit within the budget.
- D. Multiplying only one hyperparameter's candidate count by the fold count and adding the other ignores that every combination of both hyperparameters is retrained on every fold. The correct relationship multiplies all three quantities together, not two of them with the third added on.
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.
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?
Each of the 20 trials runs 3-fold CV, and each fold trains its own model on k − 1 folds, so the search makes 20 × 3 = 60 fits. fmin returns only the best hyperparameter values, not a fitted model. To get a model you can deploy, you write one more fit on the full data yourself, which makes 61.
“A model is trained using \(k-1\) of the folds as training data;”Source: scikit-learn.org
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?
Parallelism only sets how many fits run at the same time. The search still trains 16 × 5 fits plus the refit, so only the elapsed time drops. The other three changes each alter a term in the formula: the grid size, the fold count, or k fits per combination down to one.
“parallelism: Number of models to fit and evaluate concurrently.”Source: docs.databricks.com
Sources
(4)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.https://docs.databricks.com/aws/en/machine-learning/automl-hyperparam-tuning/hyperopt-conceptsOfficial docs
“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.
“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.https://scikit-learn.org/stable/modules/cross_validation.htmlSecondary source
“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.https://docs.databricks.com/aws/en/machine-learning/automl-hyperparam-tuning/hyperopt-spark-mlflow-integrationOfficial docs
“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