from mlxtend.data import iris_data
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import RandomizedSearchCV
# Loading the Iris dataset
X, y = iris_data()
# Splitting the dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Defining the hyperparameter space
param_dist = {'n_estimators': [50, 100, 200],
'max_depth': [None, 10, 20, 30],
'min_samples_split': [2, 5, 10],
'min_samples_leaf': [1, 2, 4]}
# Creating the RandomizedSearchCV instance
random_search = RandomizedSearchCV(RandomForestClassifier(), param_distributions=param_dist, n_iter=5, cv=5, n_jobs=-1, random_state=42)
try:
# Fit the model
random_search.fit(X_train, y_train)
# Accessing results
cv_results_ = random_search.cv_results_
best_params_ = random_search.best_params_
best_estimator_ = random_search.best_estimator_
# Printing a concise summary of CV results
print("Summary of CV Results:")
print(f"Best Mean Test Score: {cv_results_['mean_test_score'].max()}")
print(f"Best Parameters: {best_params_}")
print("\nBest Estimator:")
print(best_estimator_)
except Exception as e:
print(f"An error occurred: {e}")