gpt4 book ai didi

python - 具有 RFECV 的 KNN 返回 : "The classifier does not expose "coef _"or "feature_importances _"attributes"

转载 作者:行者123 更新时间:2023-11-30 08:54:40 25 4
gpt4 key购买 nike

我正在尝试在 KNeighborsClassifier 上应用 RFECV 来消除无关紧要的特征。为了使问题可重复,以下是虹膜数据的示例:

from sklearn.datasets import load_iris
from sklearn.feature_selection import RFECV
from sklearn.neighbors import KNeighborsClassifier
iris = load_iris()
y = iris.target
X = iris.data
estimator = 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_iris
from sklearn.feature_selection import RFECV
from sklearn.svm import SVC
iris = load_iris()
y = iris.target
X = iris.data
estimator = SVC(kernel="linear")
selector = RFECV(estimator, step=1, cv=5)
selector = selector.fit(X, y)

它会工作得很好。关于如何解决这个问题有什么建议吗?

注意:我昨天更新了 Anaconda,它也更新了 sklearn。

最佳答案

错误是非常不言自明的 - knn 不提供进行特征选择的逻辑。你不能使用它(sklearn 的实现)来实现这样的目标,除非你为 KNN 定义了自己的特征重要性度量。据我所知 - 没有这样的通用对象,因此 - scikit-learn 没有实现它。另一方面,SVM 与每个线性模型一样 - 提供此类信息。

关于python - 具有 RFECV 的 KNN 返回 : "The classifier does not expose "coef _"or "feature_importances _"attributes",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37780139/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com