Grid search with Python

Grid search is a technique used to find the best hyperparameters for a machine learning model. It involves searching through a specified grid of hyperparameters and selecting the combination that results in the best performance. Step 1: Define the hyperparameter grid
from sklearn.model_selection import GridSearchCV
from sklearn.ensemble import RandomForestClassifier

param_grid = {
    'n_estimators': [50, 100, 200],
    'max_depth': [None, 10, 20],
    'min_samples_split': [2, 5, 10]
}

Step 2: Instantiate the model and GridSearchCV
rf = RandomForestClassifier()
grid_search = GridSearchCV(estimator=rf, param_grid=param_grid, cv=3, n_jobs=-1)

Step 3: Fit the model to the data
grid_search.fit(X_train, y_train)

Step 4: Get the best hyperparameters and score
best_params = grid_search.best_params_
best_score = grid_search.best_score_

print("Best hyperparameters:", best_params)
print("Best score:", best_score)

Comments

Popular posts from this blog

What is the difference between a module and a package in Python?

What are the different evaluation metrics used in machine learning?

Sorting Algorithms in Python? - with practical example