Grid search and random search

Created
TagsMetrics

Grid search builds a model for every combination of hyperparameters specified and evaluates each model.

Random search is similar to grid search but only uses a random subset of all parameter combinations.

Grid search and random search are techniques used for hyperparameter tuning in machine learning models, particularly in the context of optimizing the performance of a model by finding the best combination of hyperparameters.

Grid Search:

Random Search:

Comparison:

Python Implementation (using scikit-learn):

from sklearn.model_selection import GridSearchCV, RandomizedSearchCV
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import make_classification

# Create a random forest classifier
rf_classifier = RandomForestClassifier()

# Define hyperparameter grids
param_grid = {
    'n_estimators': [50, 100, 200],
    'max_depth': [None, 10, 20],
    'min_samples_split': [2, 5, 10],
    'min_samples_leaf': [1, 2, 4]
}

# Grid search
grid_search = GridSearchCV(rf_classifier, param_grid, cv=5)
grid_search.fit(X_train, y_train)

# Random search
random_search = RandomizedSearchCV(rf_classifier, param_distributions=param_grid, n_iter=10, cv=5)
random_search.fit(X_train, y_train)

# Best parameters and score from grid search
print("Grid Search - Best Parameters:", grid_search.best_params_)
print("Grid Search - Best Score:", grid_search.best_score_)

# Best parameters and score from random search
print("Random Search - Best Parameters:", random_search.best_params_)
print("Random Search - Best Score:", random_search.best_score_)

In this example, we perform grid search and random search for hyperparameter tuning of a random forest classifier using scikit-learn's GridSearchCV and RandomizedSearchCV classes, respectively. We define a hyperparameter grid, specify the number of iterations for random search, and fit the search objects to the training data. Finally, we print the best parameters and scores obtained from both grid search and random search.