【问题标题】:Tuning the hyperparameter with gridsearch results in overfitting使用网格搜索调整超参数会导致过拟合
【发布时间】:2019-12-23 13:02:27
【问题描述】:

使用网格搜索调整超参数会导致过度拟合。

训练误差肯定很低,但测试误差很高。不能调整超参数来降低测试误差吗?

def custom_wmae(actual_values, predicted_values):
    weight = actual_values.values / sum(actual_values)
    diff = abs(predicted_values - actual_values.values)
    return np.sum(weight * diff)


param_test1 = { 'max_depth':range(3,10,2),
 'min_child_weight':range(1,6,2)}


xgb1_test1 = xgboost.XGBRegressor(
 learning_rate =0.1,
 n_estimators=140,
 max_depth=5,
 objective ='reg:squarederror',
 min_child_weight = 1,
 subsample=0.8,
 scale_pos_weight=1,
 gamma = 0,
 seed=27)

grid_search = GridSearchCV(estimator=xgb1_test1,param_grid= param_test1, cv=5,
                           scoring=make_scorer(custom_wmae, greater_is_better=False),
                           iid=False,
                           return_train_score=True)


params_result= grid_search.fit(shuffled_train_X, shuffled_train_y)

  • 调整前 train_error: 0.386055, test_error: 0.674069

-调整后 train_error: 0.070645, test_error: 0.708254

【问题讨论】:

  • 调整前和调整后是什么意思?原来的xgb1_test1模型配置不包含在网格搜索中,所以没有试用,也找不到更好的选择。 GridsearchCV 确实使用测试错误而不是训练错误来定义更好的参数集
  • 我使用{'max_defth': 4, 'min_child_weight': 2}。并且我还使用gridsearch找到了gamma、subsamples、colsample_bytree、reg_alpha的超参数,结果的最终模型是下面的代码。 xgb1_2 = xgboost.XGBRegressor(learning_rate =00​​.1,n_estimators=5000,max_defth=4,objective ='reg:squarederror' min_child_weight = 2,subsample=0.9,colsample_bytree=0.75,gamma = 0.1,seed=27)结果= wmae_error(xgb1_2 ,ewm_df) print("train_error: %f, test_error: %f"%(result[0], result[1]))

标签: python xgboost grid-search hyperparameters


【解决方案1】:

这完全取决于您正在训练的数据。如果您用于训练的数据非常少,比如说 500 行和几列,即使如此,您仍试图拆分为训练和测试数据。 XGBoost 最有可能过度拟合训练数据。

为确保您的模型不会过拟合,您可以尝试三件事 -

  1. 确保您有足够的数据用于 XGBoost 训练。否则,过度拟合的趋势将一直存在。

  2. 使用您的参数。尝试使用 L1 和 L2 正则化为您的数据引入正则化。

  3. 在官方 XGBoost API 中,您可以通过 'xgb.train()' 函数中的验证集。因此,您可以在函数的 eval_set 参数中传递您的测试集。

【讨论】:

    猜你喜欢
    • 2019-10-15
    • 2021-06-14
    • 2021-02-07
    • 2019-06-02
    • 2023-03-09
    • 2023-02-09
    • 2021-08-24
    • 2016-07-12
    • 2020-02-10
    相关资源
    最近更新 更多