以下是使用RandomizedSearchCV进行参数调优的示例代码:

from sklearn.svm import SVR
from sklearn.model_selection import RandomizedSearchCV
from scipy.stats import uniform, loguniform

# 准备数据
X_train, y_train, X_test, y_test = ...  # 略

# 定义参数空间
param_dist = {
    'C': loguniform(1e-3, 1e3),
    'gamma': loguniform(1e-4, 1e1),
    'epsilon': uniform(0, 1)
}

# 定义模型
svr = SVR(kernel='rbf')

# 定义搜索器
searcher = RandomizedSearchCV(
    estimator=svr,
    param_distributions=param_dist,
    n_iter=50,
    cv=5,
    n_jobs=-1,
    verbose=1
)

# 开始调优
searcher.fit(X_train, y_train)

# 输出结果
print(f'Best params: {searcher.best_params_}')
print(f'Train score: {searcher.best_score_:.4f}')
print(f'Test score: {searcher.score(X_test, y_test):.4f}')

代码中的param_dist定义了参数空间,包括Cgammaepsilon三个参数。Cgamma使用了loguniform分布,epsilon使用了uniform分布。这里使用了对数分布是因为对于Cgamma这两个参数,它们的取值范围通常是一个指数级别的范围,使用对数分布可以更好地覆盖这个范围。

然后定义了一个SVR模型,和一个RandomizedSearchCV搜索器,将模型和参数空间传给搜索器。n_iter指定了搜索器要进行多少次随机搜索,cv指定了交叉验证的折数,n_jobs指定了使用多少个CPU核心进行并行搜索,verbose指定了搜索过程是否要输出详细信息。

最后调用fit方法开始进行参数搜索。搜索完毕后,可以通过best_params_属性获取最佳参数组合,通过best_score_属性获取最佳得分,通过score方法计算测试集上的得分


原文地址: https://www.cveoy.top/t/topic/eew8 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录