from skopt import BayesSearchCV
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
# Load dataset
= load_iris(return_X_y=True)
X, y = train_test_split(X, y, test_size=0.2, random_state=42)
X_train, X_val, y_train, y_val
# Define the model
= RandomForestClassifier()
rf
# Define the search space
= {
search_spaces 'n_estimators': (10, 200),
'max_depth': (1, 50),
'min_samples_split': (2, 20),
'min_samples_leaf': (1, 20),
'bootstrap': [True, False]
}
# Initialize BayesSearchCV
= BayesSearchCV(
opt =rf,
estimator=search_spaces,
search_spaces=32,
n_iter='accuracy',
scoring=3,
cv=42
random_state
)
# Perform the search
opt.fit(X_train, y_train)
# Best parameters
print("Best Parameters:", opt.best_params_)
print("Best Score:", opt.best_score_)
BayesSearchCV(cv=3, estimator=RandomForestClassifier(), n_iter=32, random_state=42, scoring='accuracy', search_spaces={'bootstrap': [True, False], 'max_depth': (1, 50), 'min_samples_leaf': (1, 20), 'min_samples_split': (2, 20), 'n_estimators': (10, 200)})In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
BayesSearchCV(cv=3, estimator=RandomForestClassifier(), n_iter=32, random_state=42, scoring='accuracy', search_spaces={'bootstrap': [True, False], 'max_depth': (1, 50), 'min_samples_leaf': (1, 20), 'min_samples_split': (2, 20), 'n_estimators': (10, 200)})
RandomForestClassifier(max_depth=10, min_samples_split=20, n_estimators=200)
RandomForestClassifier(max_depth=10, min_samples_split=20, n_estimators=200)
Best Parameters: OrderedDict([('bootstrap', True), ('max_depth', 10), ('min_samples_leaf', 1), ('min_samples_split', 20), ('n_estimators', 200)])
Best Score: 0.9666666666666667