How many times is an SVC model fitted in total when this grid search runs?
from sklearn.model_selection import GridSearchCV
from sklearn.svm import SVC
param_grid = [
{"kernel": ["linear"], "C": [0.1, 1, 10]},
{"kernel": ["rbf"], "C": [0.1, 1, 10], "gamma": [0.01, 0.1]},
]
search = GridSearchCV(SVC(), param_grid, cv=5) # refit=True is the default
search.fit(X_train, y_train)Show the answer and explanation
Correct answer: A, 46 fits: the two dictionaries are separate grids with 3 + 6 = 9 candidates, each fitted on 5 folds, plus one refit of the best one on all training data.
Explanation Combinatorics
When param_grid is a list of dictionaries, scikit-learn expands each dictionary into its own grid and searches the union. This avoids meaningless combinations, for example gamma values for a linear kernel that ignores them.
- Grid 1: 1 kernel × 3 values of C = 3 candidates.
- Grid 2: 1 kernel × 3 values of C × 2 values of gamma = 6 candidates.
- Total: 9 candidates, each trained once per fold: 9 × 5 = 45 fits.
refit=True(the default) then retrains the best candidate on the full training data, so thatbest_estimator_andsearch.predictwork: 46 fits in total.
| Stage | Fits |
|---|---|
| Cross-validation | 9 × 5 = 45 |
| Final refit | 1 |
| Total | 46 |
Why the other answers fail:
- A single merged product (2 × 3 × 2 = 12 candidates) is what one dictionary with both kernels would produce; the list form keeps the grids separate.
- The fold models are not reused as the final estimator; each saw only 80% of the training data, so the refit trains on all of it.
- Cross-validation does not re-score one model: every fold trains a fresh model on the other four folds and scores it on the held-out fold.
Grid sizes multiply fast: 5 hyperparameters with 4 values each give 4⁵ = 1,024 candidates, or 5,120 fits with 5-fold CV. That is why random search, successive halving or Bayesian optimisation are preferred for larger spaces.
Interview tip: estimate the budget out loud as candidates × folds (+ refit) × time per fit before proposing a grid, and mention nested cross-validation if the tuned score must be an unbiased performance estimate.