Lesson 3 of 9
Exhaustive Grid Search (GridSearchCV): Mechanics, Parallelism & Limitations
GridSearchCV performs exhaustive brute-force evaluation across an explicitly defined Cartesian grid of hyperparameters. For every combination, it executes K-fold cross-validation, computing mean and standard deviation of validation metrics. While exhaustive and deterministic, Grid Search suffers from the Curse of Dimensionality: evaluating 5 parameters with 4 values each requires 4^5 = 1,024 configurations. With 5-fold CV, this requires fitting 5,120 models, making it inefficient for continuous search spaces.
Parallel GridSearchCV on Pipelines in Scikit-Learn
import numpy as np
import pandas as pd
from sklearn.model_selection import GridSearchCV, StratifiedKFold
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import make_classification
# Generate classification dataset
X, y = make_classification(n_samples=800, n_features=12, random_state=42)
pipeline = Pipeline([
('scaler', StandardScaler()),
('clf', RandomForestClassifier(random_state=42))
])
# Define Cartesian Grid Search space using double-underscore step syntax
param_grid = {
'clf__n_estimators': [50, 100],
'clf__max_depth': [3, 5, 8],
'clf__min_samples_leaf': [1, 5],
'clf__max_features': ['sqrt', 'log2']
}
# Total Combinations = 2 * 3 * 2 * 2 = 24 candidates
# With 5-Fold CV = 120 model fits
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
grid_search = GridSearchCV(
estimator=pipeline,
param_grid=param_grid,
cv=cv,
scoring='roc_auc',
n_jobs=-1, # Parallel execution across all CPU cores
return_train_score=True
)
grid_search.fit(X, y)
print("=== GRID SEARCH CV EXECUTION AUDIT ===")
print(f"Total Candidate Parameter Sets : {len(grid_search.cv_results_['params'])}")
print(f"Best 5-Fold CV ROC-AUC Score : {grid_search.best_score_:.4f}")
print("Optimal Hyperparameter Configuration:")
for param, val in grid_search.best_params_.items():
print(f" {param:25s}: {val}")Pro Tip: Inspecting `cv_results_` for Overfitting
Always check `grid_search.cv_results_['mean_train_score']` vs `mean_test_score`. If the best parameter combination has a training score of 1.0 and a test score of 0.82, it is severely overfitting. Pick a simpler parameter set with a smaller train-test gap to improve production robustness.
MlGridSearchCV Visual Representation
Hands-On Challenge: Coarse-to-Fine Grid Search
Implement a two-stage coarse-to-fine search: Run an initial broad grid over powers of 10 (`[0.001, 0.1, 10.0]`), find the best region, and run a second fine grid centered tightly around that winner (`[0.05, 0.1, 0.2]`).
Quick Quiz & Key Concept Checks
Common Pitfall: The Combinatorial Explosion Trap
Adding just 2 more candidate values across 5 hyperparameters increases total trials from 3^5 = 243 to 5^5 = 3,125 trials. Training will stall for hours. Use RandomizedSearchCV or Optuna for search spaces larger than 50 combinations.