2016-04-24 45 views
0

我使用sklearn實現了使用樸素貝葉斯的PCA,並使用GridSearchCV優化了PCA組件數。如何從gridSearchCV的輸出中獲取功能名稱

我試圖找出最佳評估者的功能名稱,但我無法做到。這是我嘗試過的代碼。

from sklearn.cross_validation import train_test_split 
features_train, features_test, labels_train, labels_test = \ 
train_test_split(features, labels, test_size=0.3, random_state=42) 
### A Naive Bayes classifier combined with PCA is used and its accuracy is tested 

pca = decomposition.PCA() 
#clf = GaussianNB() 
clf = Pipeline(steps=[('pca', pca), ('gaussian_NB', GaussianNB())]) 
n_components = [3, 5, 7, 9] 
clf = GridSearchCV(clf, 
         dict(pca__n_components=n_components)) 

# from sklearn.tree import DecisionTreeClassifier 
#clf = DecisionTreeClassifier(random_state=0, min_samples_split=20) 
clf = clf.fit(features_train, labels_train) 
features_pred = clf.predict(features_test) 
print "The number of components of the best estimator is ", clf.best_estimator_.named_steps['pca'].n_components 
print "The best parameters:", clf.best_params_ 
#print "The best estimator", clf.best_estimator_.get_params(deep=True).gaussian_NB 
# best_est = RFE(clf.best_estimator_) 
# print "The best estimator:", best_est 
estimator = clf.best_estimator_ 
print "The features are:", estimator['features'].get_feature_names() 

回答

1

你似乎混淆降維特徵選擇。 PCA是降維技術,它不選擇特徵,它尋找較低維的線性投影。您的結果功能不是您的原始功能 - 它們是這些功能的線性組合。因此,如果您的原始特徵是在PCA變暗2之後的「寬度」,「高度」和「年齡」,則最終會出現「0.4 *寬度+ 0.1 *高度--0.05 *時間」和「0.3 *高度 - 0.2寬度」。

+0

我想這就是爲什麼它不按我期望的方式工作。 –

0

看起來好像this answer可能是你以後。它也包含一個非常好的和詳盡的例子!

相關問題