如何为KNN分类器查找'特征重要性'或变量重要性图表

6

我正在使用sklearn包的KNN分类器处理数字数据集。

在预测完成后,应该用条形图显示前4个重要的变量。

这是我尝试过的解决方案,但它报错说feature_importances不是KNNClassifier的属性:

neigh = KNeighborsClassifier(n_neighbors=3)
neigh.fit(X_train, y_train)
y_pred = neigh.predict(X_test)

(pd.Series(neigh.feature_importances_, index=X_test.columns)
   .nlargest(4)
   .plot(kind='barh'))

现在展示决策树的变量重要性图表:传递给 pd.series() 的参数是 classifier.feature_importances_。

对于 SVM、线性判别分析,传递给 pd.series() 的参数是 classifier.coef_[0]。

然而,我无法找到 KNN 分类器的适当参数。

2个回答

8

KNN分类算法没有定义特征重要性。在这里,没有简单的方法来计算分类结果的特征。您可以使用具有feature_importances_属性的随机森林分类器。即使在这种情况下,feature_importances_属性也只告诉您整个模型中最重要的特征,而不是特定于您正在预测的样本。

如果您一定要使用KNN,则估计特征重要性的最佳方法是获取要预测的样本,并计算每个特征与其最近邻之间的距离(称为neighb_dist)。然后针对几个随机点进行相同的计算(将其称为rand_dist),而不是最近的邻居。然后对于每个特征,您需要取neighb_dist/rand_dist的比率,比率越小,该特征就越重要。


1
这是一个好的、通用的例子。
#importing libraries
from sklearn.datasets import load_boston
import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
import statsmodels.api as sm
%matplotlib inline
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.feature_selection import RFE
from sklearn.linear_model import RidgeCV, LassoCV, Ridge, Lasso#Loading the dataset
x = load_boston()
df = pd.DataFrame(x.data, columns = x.feature_names)
df["MEDV"] = x.target
X = df.drop("MEDV",1)   #Feature Matrix
y = df["MEDV"]          #Target Variable
df.head()

reg = LassoCV()
reg.fit(X, y)
print("Best alpha using built-in LassoCV: %f" % reg.alpha_)
print("Best score using built-in LassoCV: %f" %reg.score(X,y))
coef = pd.Series(reg.coef_, index = X.columns)

print("Lasso picked " + str(sum(coef != 0)) + " variables and eliminated the other " +  str(sum(coef == 0)) + " variables")

imp_coef = coef.sort_values()
import matplotlib
matplotlib.rcParams['figure.figsize'] = (8.0, 10.0)
imp_coef.plot(kind = "barh")
plt.title("Feature importance using Lasso Model")

enter image description here

所有细节如下列出。

https://towardsdatascience.com/feature-selection-with-pandas-e3690ad8504b

这里有两个同样优秀的例子。

https://www.scikit-yb.org/en/latest/api/features/importances.html

https://github.com/WillKoehrsen/feature-selector/blob/master/Feature%20Selector%20Usage.ipynb


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接