我使用sklearn实现了PCA与朴素贝叶斯的结合,并使用GridSearchCV优化了PCA的组件数量。
我试图找出最佳估计器的特征名称,但没有成功。以下是我尝试过的代码。
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)
### 使用结合了PCA的朴素贝叶斯分类器,并测试其准确性
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 "最佳估计器的组件数量是", clf.best_estimator_.named_steps['pca'].n_components
print "最佳参数:", clf.best_params_
#print "最佳估计器", clf.best_estimator_.get_params(deep=True).gaussian_NB
# best_est = RFE(clf.best_estimator_)
# print "最佳估计器:", best_est
estimator = clf.best_estimator_
print "特征是:", estimator['features'].get_feature_names()
回答:
您似乎混淆了降维和特征选择。PCA是一种降维技术,它并不选择特征,而是寻找一个低维线性投影。您的结果特征并不是原始特征——它们是那些特征的线性组合。因此,如果您的原始特征是“宽度”、“高度”和“年龄”,在将PCA降维到2维后,您得到的特征可能是“0.4 * 宽度 + 0.1 * 高度 – 0.05 * 年龄”和“0.3 * 高度 – 0.2 * 宽度”。