KNN与RFECV的返回结果:“分类器不提供‘coef_’或‘feature_importances_’属性”

我试图在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像每个线性模型一样 – 提供了这样的信息。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注