我试图在KNeighborsClassifier上应用RFECV来消除不重要的特征。为了使问题可重复,以下是使用鸢尾花数据的一个示例:
from sklearn.datasets import load_irisfrom sklearn.feature_selection import RFECVfrom sklearn.neighbors import KNeighborsClassifieriris = load_iris()y = iris.targetX = iris.dataestimator = KNeighborsClassifier()selector = RFECV(estimator, step=1, cv=5)selector = selector.fit(X, y)
这会导致以下错误信息:
---------------------------------------------------------------------------RuntimeError Traceback (most recent call last)<ipython-input-27-19f0f2f0f0e7> in <module>() 7 estimator = KNeighborsClassifier() 8 selector = RFECV(estimator, step=1, cv=5)----> 9 selector.fit(X, y)C:...\Anaconda3\lib\site-packages\sklearn\feature_selection\rfe.py in fit(self, X, y) 422 verbose=self.verbose - 1) 423 --> 424 rfe._fit(X_train, y_train, lambda estimator, features: 425 _score(estimator, X_test[:, features], y_test, scorer)) 426 scores.append(np.array(rfe.scores_[::-1]).reshape(1, -1))C:...\Anaconda3\lib\site-packages\sklearn\feature_selection\rfe.py in _fit(self, X, y, step_score) 180 coefs = estimator.feature_importances_ 181 else:--> 182 raise RuntimeError('The classifier does not expose ' 183 '"coef_" or "feature_importances_" ' 184 'attributes')RuntimeError: The classifier does not expose "coef_" or "feature_importances_" attributes
如果我将分类器改为SVC,如下所示:
from sklearn.datasets import load_irisfrom sklearn.feature_selection import RFECVfrom sklearn.svm import SVCiris = load_iris()y = iris.targetX = iris.dataestimator = SVC(kernel="linear")selector = RFECV(estimator, step=1, cv=5)selector = selector.fit(X, y)
它将正常工作。有什么建议来解决这个问题吗?
注意:我昨天更新了Anaconda,这也更新了sklearn。
回答:
错误信息非常明确 – KNN不提供进行特征选择的逻辑。你不能使用它(sklearn的实现)来达到这个目标,除非你为KNN定义自己的特征重要性度量。据我所知 – 没有这样的通用对象,因此 – scikit-learn没有实现它。另一方面,SVM像每个线性模型一样 – 提供了这样的信息。