多输出回归器超参数调优疑问:参数针对单目标还是整体?如何获取?
多输出回归器超参数调优问题解答
问题描述
使用MultiOutputRegressor结合XGBRegressor预测三个目标,通过HalvingRandomSearchCV调参时,打印best_params_仅返回一组超参数,疑问如下:
- 对多输出回归器调参时,是针对每个目标单独调参还是针对整个回归器调参?
- 如果是针对每个目标调参,如何获取各目标的调优超参数?
当前代码示例:
hyperparameters = { 'estimator__n_estimators': [100, 300,500, 600,700, 800, 900,1000, 1200], 'estimator__max_depth': [3,4, 5,6, 7, 10, 11, 12, 15], 'estimator__learning_rate': [0.05,0.04, 0.06,0.08, 0.1, 0.2, 0.3,0.4, 0.5] } reg=XGBRegressor() multioutput_regressor = MultiOutputRegressor(reg) ### Wrapping the xgb models kf = KFold(n_splits=10, shuffle=True, random_state=42) search = HalvingRandomSearchCV(multioutput_regressor, hyperparameters, n_jobs=-1, cv=kf, random_state=42) search=search.fit(X_train, y_train) y_pred_train = search.predict(X_train) #predictions on the test set y_pred = search.predict(X_test) ### testing the trained model print('Best hyperparameters:', search.best_params_)
核心结论
当前代码的调参逻辑:
MultiOutputRegressor的默认行为是为每个目标克隆同一套参数的基础模型(这里是XGBRegressor),因此HalvingRandomSearchCV是针对整个多输出回归器的统一参数调优,最终只会返回一组最优参数,所有目标共享这组参数。针对每个目标单独调参的实现方式:
如果需要为每个目标单独调参,不能直接依赖MultiOutputRegressor的默认封装,需要手动为每个目标独立执行调参流程,步骤如下:
- 将多目标数据集拆分为单个目标的数据集
- 对每个目标分别用
HalvingRandomSearchCV调优XGBRegressor - 保存每个目标的最优参数并训练对应模型
- 预测时合并各模型的输出结果
代码示例(单独调参)
import numpy as np from xgboost import XGBRegressor from sklearn.model_selection import HalvingRandomSearchCV, KFold # 拆分多目标为单个目标 y_train_1 = y_train[:, 0] y_train_2 = y_train[:, 1] y_train_3 = y_train[:, 2] # 定义超参数空间 hyperparameters = { 'n_estimators': [100, 300,500, 600,700, 800, 900,1000, 1200], 'max_depth': [3,4, 5,6, 7, 10, 11, 12, 15], 'learning_rate': [0.05,0.04, 0.06,0.08, 0.1, 0.2, 0.3,0.4, 0.5] } kf = KFold(n_splits=10, shuffle=True, random_state=42) # 为每个目标单独调参并训练 models = [] best_params_list = [] # 目标1 search1 = HalvingRandomSearchCV(XGBRegressor(), hyperparameters, n_jobs=-1, cv=kf, random_state=42) search1.fit(X_train, y_train_1) models.append(search1.best_estimator_) best_params_list.append(search1.best_params_) # 目标2 search2 = HalvingRandomSearchCV(XGBRegressor(), hyperparameters, n_jobs=-1, cv=kf, random_state=42) search2.fit(X_train, y_train_2) models.append(search2.best_estimator_) best_params_list.append(search2.best_params_) # 目标3 search3 = HalvingRandomSearchCV(XGBRegressor(), hyperparameters, n_jobs=-1, cv=kf, random_state=42) search3.fit(X_train, y_train_3) models.append(search3.best_estimator_) best_params_list.append(search3.best_params_) # 打印各目标最优参数 for i, params in enumerate(best_params_list): print(f'目标{i+1}的最优超参数:', params) # 预测并合并结果 y_pred = np.column_stack([model.predict(X_test) for model in models])
两种调参方式的对比
- 统一参数调参:实现简单、计算开销小,适合目标之间相关性较高的场景,一套参数能兼顾多个目标的表现。
- 单独参数调参:能针对每个目标的特性优化参数,预测精度可能更高,但计算量是3倍于统一调参,适合目标差异较大的场景。
内容的提问来源于stack exchange,提问作者Elin
相关产品推荐
相关产品推荐

