首页 文章

使用预定义的验证集Sklearn执行网格搜索

提问于
浏览
1

之前已经多次询问过这个问题 . 但是在回答这个问题时我收到了一个错误

首先,我指定哪个部分是训练集和验证集如下 .

my_test_fold = []


for i in range(len(train_x)):
    my_test_fold.append(-1)

 for i in range(len(test_x)):
    my_test_fold.append(0)

然后执行gridsearch .

from sklearn.model_selection import PredefinedSplit
param = {
 'n_estimators':[200],
 'max_depth':[5],
 'min_child_weight':[3],
 'reg_alpha':[6],
    'gamma':[0.6],
    'scale_neg_weight':[1],
    'learning_rate':[0.09]
}




gsearch1 = GridSearchCV(estimator = XGBClassifier( 
    objective= 'reg:linear', 
    seed=1), 
param_grid = param, 
scoring='roc_auc',
cv = PredefinedSplit(test_fold=my_test_fold),
verbose = 1)


gsearch1.fit(new_data_df, df_y)

但是我收到以下错误

object of type 'PredefinedSplit' has no len()

2 回答

  • 0

    尝试更换

    cv = PredefinedSplit(test_fold=my_test_fold)
    

    cv = list(PredefinedSplit(test_fold=my_test_fold).split(new_data_df, df_y))
    

    原因是您可能需要应用split method来实际分割为训练和测试(然后将其从可迭代对象转换为列表对象) .

  • 1

    使用我作为作者的 hypopt Python包( pip install hypopt ) . 它是专为使用验证集进行参数优化而创建的专业软件包 . 它适用于任何开箱即用的scikit-learn模型,也可以与Tensorflow,PyTorch,Caffe2等一起使用 .

    # Code from https://github.com/cgnorthcutt/hypopt
    # Assuming you already have train, test, val sets and a model.
    from hypopt import GridSearch
    param_grid = [
      {'C': [1, 10, 100], 'kernel': ['linear']},
      {'C': [1, 10, 100], 'gamma': [0.001, 0.0001], 'kernel': ['rbf']},
     ]
    # Grid-search all parameter combinations using a validation set.
    opt = GridSearch(model = SVR(), param_grid = param_grid)
    opt.fit(X_train, y_train, X_val, y_val)
    print('Test Score for Optimized Parameters:', opt.score(X_test, y_test))
    

相关问题