RandomForestRegressor使用RandomizedSearchCV 参数调优代码
以下是使用RandomForestRegressor和RandomizedSearchCV进行参数调优的代码示例:
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import RandomizedSearchCV
from scipy.stats import randint as sp_randint
# 准备数据
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 定义模型
rf = RandomForestRegressor(random_state=42)
# 定义参数空间
param_dist = {'n_estimators': sp_randint(10, 1000),
'max_features': sp_randint(1, X_train.shape[1]),
'min_samples_split': sp_randint(2, 50),
'min_samples_leaf': sp_randint(1, 50)}
# 进行随机搜索
n_iter_search = 50
random_search = RandomizedSearchCV(rf, param_distributions=param_dist,
n_iter=n_iter_search, cv=5, iid=False, random_state=42)
# 训练模型并进行预测
random_search.fit(X_train, y_train)
y_pred = random_search.predict(X_test)
# 输出最佳参数和评分
print("Best parameters found: ", random_search.best_params_)
print("Best score found: ", random_search.best_score_)
以上代码中,我们使用了RandomForestRegressor作为模型,使用RandomizedSearchCV进行参数调优。我们定义了参数空间param_dist,然后设置了随机搜索的迭代次数n_iter_search,并进行了训练和预测。最后,我们输出了最佳参数和评分
原文地址: https://www.cveoy.top/t/topic/edKG 著作权归作者所有。请勿转载和采集!