pythonscikit-learnsvmgrid-searchsvc

Grid search for SVC : IndexError: too many indices for array


I'm trying to use GridSearchCV to find the best params for SVC.

from sklearn.svm import SVC
from sklearn import svm, grid_search
from sklearn.model_selection import GridSearchCV

param_grid = [
        {'C': [1,5,10,100]},
        ]
algo = SVC(kernel="poly",  degree=5, coef0=2)
grid_search = GridSearchCV(algo, param_grid, cv=3, scoring='neg_mean_squared_error')
grid_search.fit(X_train, y_train)
print(grid_search.best_params_) #line 162

I get the following error:

  File "main.py", line 162, in <module>
  IndexError: too many indices for array

When I don't use GridSearchCV it works:

from sklearn.svm import SVC
from sklearn import svm, grid_search
from sklearn.model_selection import GridSearchCV

algo = SVC(kernel="poly", C=1, degree=5, coef0=2)
algo.fit(X_train, y_train)
predict_test = algo.predict(X_test)
mse = mean_squared_error(y_test, predict_test)
rmse = np.sqrt(mse)
print(rmse)

I get a score.


Solution

  • GridSearchCV.fit() accepts target values as an array-like y of shape [n_samples] or [n_samples, n_output].

    In your case, (892,). Therefore, reshape y_train:

    y_train = y_train.reshape(892,)