Skip to main content
Albero Academy

Hyperparameter Tuning

Search for the best settings with grid and randomized search.

Model Selection & Unsupervised9 min

Models have hyperparameters you set before training (tree depth, regularisation strength, k). Tuning them — searching for the combination that cross-validates best — often turns a decent model into a strong one.

GridSearchCV

exhaustive search over a grid
from sklearn.model_selection import GridSearchCV
param_grid = {"n_estimators": [100, 300], "max_depth": [5, 10, None]}
search = GridSearchCV(RandomForestClassifier(), param_grid, cv=5, scoring="f1")
search.fit(X_train, y_train)
search.best_params_ # the winning combination
search.best_estimator_ # the model refit on all training data with those params

RandomizedSearchCV

Key takeaways

  1. 01Hyperparameters are set before training (depth, alpha, k) — tuning them boosts performance.
  2. 02GridSearchCV exhaustively tries every combination via cross-validation.
  3. 03RandomizedSearchCV samples combinations — faster for large search spaces.
  4. 04best_params_/best_estimator_ give the winning settings and refit model; tune on a pipeline.

Finished this chapter?

Mark it complete to track your progress through Scikit-learn.