2017-02-15 48 views
1

我想將PCA和SVM結合到一個流水線中,以查找GridSearch中超參數的最佳組合。在管道中結合主成分分析和支持向量機

下面的代碼

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) 

結果在

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

有可能出錯了我定義和使用svm_grid的方式。我如何正確地將這個參數組合傳遞給GridSearchCV?

回答

2

的問題是,當GridSearchCV試圖給估計的參數:

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

估計這裏是一個管道對象,而不是因爲你的參數網格命名的實際SVM。

我相信它應該是這樣的:

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_ 

輸出:

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

包含所有參數的params_grid並相應地命名他們到指定的步驟。

希望這會有所幫助!祝你好運!