1

The code for hyperparameter tuning using scikit-learn looks like this:

gs = GridSearchCV(estimator=pipe_svc,
             param_grid=param_grid,
             scoring='accuracy',
             cv=10,
             n_jobs=-1)

gs = gs.fit(X_train, y_train)
clf = gs.best_estimator_
clf.fit(X_train, y_train)

where for each combination of hyperparameters K-fold cross-validation is performed and the the combination that gives the best score is used to train over the entire training data to fit the model and this model will be used to predict on the test (unseen) data.

My question is how can I do the same job using nested cross-validation. The below code performs nested 5x2 cross-validation

gs = GridSearchCV(estimator=pipe_svc,
    param_grid=param_grid,
    scoring='accuracy',
    cv=2)

scores = cross_val_score(gs, X_train, y_train,
                         scoring='accuracy', cv=5)

where GridSearchCV runs the inner loop while cross_val_score() runs the outer loop. Since cv=5 given to cross_val_score(), the result will be five different models (i.e., hyperparameters)

If the model is stable enough, then all the resulting hyperparameters may be same. But if not, one should naturally choose the hyperparameters that correspond to the highest one in the scores array returned by cross_val_score()

I would like to know how to access it so that I can use it to once again fit the model using the entire training data and finally predict on the test dataset.

Espoir Murhabazi
  • 5,973
  • 5
  • 42
  • 73
Royalblue
  • 639
  • 10
  • 22
  • 2
    First gridSearchcv will automatically fit the best_estimator_ with whole data so you need not do it again. Second, `cross_val_score()` only returns the scores so its not possible. Maybe you can make a custom cross_val_score() which will return models instead of scores. – Vivek Kumar Jan 10 '18 at 09:12
  • OK I understood. Thanks Vivek. – Royalblue Jan 10 '18 at 10:06
  • 1
    This question might help you: [How to access Scikit Learn nested cross-validation scores](https://stackoverflow.com/questions/41877731/how-to-access-scikit-learn-nested-cross-validation-scores/41930782#41930782) – Linlin林林 Feb 14 '18 at 16:38

0 Answers0