代码之家  ›  专栏  ›  技术社区  ›  Pubudu

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

  •  2
  • Pubudu  · 技术社区  · 7 年前

    这个问题以前已经被问过好几次了。但我在回答问题时出错了

    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)
    

    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 回复  |  直到 7 年前
        1
  •  1
  •   Miriam Farber    7 年前

    尝试替换

    cv = PredefinedSplit(test_fold=my_test_fold)
    

    具有

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

    split method

        2
  •  -2
  •   cgnorthcutt zwol    3 年前

    这个 hypopt Python package ( pip install hypopt ),我是作者之一,它的创建正是为了这个目的:使用验证集进行参数优化。它与scikit学习模型一起工作,可以与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))