如何找到 KNNClassifier() 的“特征重要性”或变量重要性图

Sim*_*ran 6 python knn scikit-learn

我正在使用 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'))
Run Code Online (Sandbox Code Playgroud)

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

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

但是,我无法为 KNN 分类器找到合适的参数。

小智 8

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

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


ASH*_*ASH 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")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

下面列出了所有详细信息。

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