Grid Search and Random Search
GridSearchCV, RandomizedSearchCV, param_grid design, refitting on best params.
Grid Search and Random Search is a free Learn AI with Python lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Learn AI with Python learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why Tune Hyperparameters
Models have hyperparameters (like max_depth or C) that are not learned from data but set before training. The right values can hugely improve performance, so we search for them systematically.
Manual Tuning Is Error-Prone
Trying values by hand is slow and easy to bias. Automated search combined with cross-validation evaluates each candidate fairly and finds the best combination reproducibly.
GridSearchCV Basics
GridSearchCV tries every combination in a parameter grid, scoring each with cross-validation. It is exhaustive and guarantees the best point in the grid.
from sklearn.model_selection import GridSearchCV
from sklearn.ensemble import RandomForestClassifier
param_grid = {
"n_estimators": [100, 200, 300],
"max_depth": [4, 8, None],
}
gs = GridSearchCV(RandomForestClassifier(), param_grid, cv=5)
gs.fit(X, y)The Combinatorial Explosion
Grid search cost grows with the product of all option counts times the number of folds. Three params with 5 values each at 5-fold CV is 5*5*5*5 = 625 fits. Grids get expensive fast.
Scoring in GridSearchCV
The scoring parameter chooses the metric to optimize. For imbalanced data pick f1 or roc_auc instead of the default accuracy.
from sklearn.model_selection import GridSearchCV
gs = GridSearchCV(
RandomForestClassifier(),
param_grid,
cv=5,
scoring="roc_auc",
)
gs.fit(X, y)Parallelizing with n_jobs
Each candidate fit is independent, so set n_jobs=-1 to run them across all CPU cores. This dramatically cuts wall-clock time for large grids.
from sklearn.model_selection import GridSearchCV
gs = GridSearchCV(
RandomForestClassifier(),
param_grid,
cv=5,
n_jobs=-1,
verbose=1,
)Reading the Best Results
After fitting, inspect best_params_ for the winning combination, best_score_ for its CV score, and best_estimator_ for the refit model ready to predict.
gs.fit(X, y)
print("Best params:", gs.best_params_)
print("Best CV score:", gs.best_score_)
best_model = gs.best_estimator_
best_model.predict(X_new)Inspecting All Results
cv_results_ is a dict (great as a DataFrame) showing every candidate score and rank. Use it to understand which parameters matter and how stable the scores are.
import pandas as pd
results = pd.DataFrame(gs.cv_results_)
print(results[["params", "mean_test_score", "rank_test_score"]].head())RandomizedSearchCV
When the search space is huge, RandomizedSearchCV samples a fixed number of random combinations instead of all of them. You control the budget with n_iter.
from sklearn.model_selection import RandomizedSearchCV
from scipy.stats import randint
param_dist = {
"n_estimators": randint(100, 500),
"max_depth": randint(3, 20),
}
rs = RandomizedSearchCV(
RandomForestClassifier(), param_dist,
n_iter=30, cv=5, random_state=0,
)
rs.fit(X, y)Why Random Search Often Wins
For many problems only a few hyperparameters truly matter. Random search explores those important dimensions more efficiently than a rigid grid, finding good solutions with far fewer trials.
Grid vs Random: Guidance
Use GridSearchCV for a small, discrete set of candidates. Use RandomizedSearchCV for large or continuous spaces where you set an n_iter budget. Both refit the best model automatically when refit=True.
Quick Check
Test your hyperparameter search knowledge.
Recap
Recap: GridSearchCV exhaustively tests every combination in a param_grid; cost explodes with size. RandomizedSearchCV samples n_iter combinations for large spaces. Set scoring for your metric, n_jobs=-1 for speed, and read best_params_, best_score_, and best_estimator_ after fitting.
Frequently asked questions
Is the “Grid Search and Random Search” lesson free?
Yes — the full text of “Grid Search and Random Search” is free to read here on the web, and the Learn AI with Python course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Learn AI with Python course, upgrade to CoddyKit PRO.
What will I learn in “Grid Search and Random Search”?
GridSearchCV, RandomizedSearchCV, param_grid design, refitting on best params. You practise Learn AI with Python with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Learn AI with Python?
No prior experience is required. Learn AI with Python on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Grid Search and Random Search” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Learn AI with Python lesson?
Yes. Every Learn AI with Python lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Cross-Validation Strategies
- Classification Metrics Deep Dive
- Grid Search and Random Search
- Bayesian Optimization with Optuna