Oblomov
Oblomov

Reputation: 9645

Combining Principal Component Analysis and Support Vector Machine in a pipeline

I want to combine PCA and SVM to a pipeline, to find the best combination of hyperparameters in a GridSearch.

The following code

from sklearn.svm import SVC
from sklearn import decomposition, datasets
from sklearn.pipeline import Pipeline
from sklearn.model_selection import GridSearchCV

digits = datasets.load_digits()
X_train = digits.data
y_train = digits.target

#Use Principal Component Analysis to reduce dimensionality
# and improve generalization
pca = decomposition.PCA()
# Use a linear SVC 
svm = SVC()
# Combine PCA and SVC to a pipeline
pipe = Pipeline(steps=[('pca', pca), ('svm', svm)])
# Check the training time for the SVC
n_components = [20, 40, 64]
svm_grid = [
  {'C': [1, 10, 100, 1000], 'kernel': ['linear']},
  {'C': [1, 10, 100, 1000], 'gamma': [0.001, 0.0001], 'kernel': ['rbf']},
 ]
estimator = GridSearchCV(pipe,
                         dict(pca__n_components=n_components,
                              svm=svm_grid))
estimator.fit(X_train, y_train)

Results in an

AttributeError: 'dict' object has no attribute 'get_params'

There is probably something wrong with the way I define and use svm_grid. How can I pass this parameter combination to GridSearchCV correctly?

Upvotes: 2

Views: 2497

Answers (1)

mkaran
mkaran

Reputation: 2718

The problem was that when the GridSearchCV tried to give the estimator the parameters:

if parameters is not None:
    estimator.set_params(**parameters) 

the estimator here was a Pipeline object, not the actual svm because of the naming in your parameters grid.

I believe it should be like this:

from sklearn.svm import SVC
from sklearn import decomposition, datasets
from sklearn.pipeline import Pipeline
from sklearn.model_selection import GridSearchCV

digits = datasets.load_digits()
X_train = digits.data
y_train = digits.target

# Use Principal Component Analysis to reduce dimensionality
# and improve generalization
pca = decomposition.PCA()
# Use a linear SVC
svm = SVC()
# Combine PCA and SVC to a pipeline
pipe = Pipeline(steps=[('pca', pca), ('svm', svm)])
# Check the training time for the SVC
n_components = [20, 40, 64]

params_grid = {
    'svm__C': [1, 10, 100, 1000],
    'svm__kernel': ['linear', 'rbf'],
    'svm__gamma': [0.001, 0.0001],
    'pca__n_components': n_components,
}

estimator = GridSearchCV(pipe, params_grid)
estimator.fit(X_train, y_train)

print estimator.best_params_, estimator.best_score_

Output:

{'pca__n_components': 64, 'svm__C': 10, 'svm__kernel': 'rbf', 'svm__gamma': 0.001} 0.976071229827

Incorporating all of your parameters in params_grid and naming them correspondingly to the named steps.

Hope this helps! Good luck!

Upvotes: 3

Related Questions