![]() |
VOOZH | about |
Hyperparameters are configuration settings defined before training that control how a model learns and performs. Choosing the right values is essential for achieving good performance and generalization.
Grid search is a hyperparameter optimization technique that evaluates all possible combinations of given parameter values.
Randomized search is a hyperparameter optimization technique that samples values from given distributions instead of testing all combinations.
Import the necessary libraries for dataset generation, model creation and hyperparameter tuning. A synthetic classification dataset is created using make_classification() for demonstration purposes.
Define the range of hyperparameters to be explored. Grid Search uses fixed parameter values, while Randomized Search samples random values from defined distributions.
Both methods train multiple models using 5-fold cross-validation to identify the best hyperparameter combination based on model performance.
Output:
Grid Search Best Params: {'bootstrap': True, 'max_depth': None, 'min_samples_split': 10, 'n_estimators': 50} Score: 0.8800000000000001
Randomized Search Best Params: {'bootstrap': True, 'max_depth': None, 'min_samples_split': 5, 'n_estimators': 153} Score: 0.8699999999999999
Grid Search achieved a slightly higher score by exhaustively evaluating all possible parameter combinations, while Randomized Search produced near-optimal results with fewer evaluations and lower computational cost. This demonstrates that Randomized Search is more efficient for large search spaces, whereas Grid Search is more suitable for precise hyperparameter tuning.
You can download the source code from here.
RandomizedSearchCV is often preferred when the search space is large or continuous, as it samples only a subset of possible combinations instead of trying all of them.