如何为 KNNClassifier() 找到 'feature importance' 或变量重要性图
How to find 'feature importance' or variable importance graph for KNNClassifier()
我正在使用 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 分类器的参数。
没有为 KNN 分类算法定义特征重要性。这里没有简单的方法来计算负责分类的特征。您可以做的是使用具有 feature_importances_
属性的随机森林分类器。即使在这种情况下,feature_importances_
属性也会告诉您整个模型最重要的特征,而不是具体预测的样本。
不过,如果您打算使用 KNN,那么估计特征重要性的最佳方法是采用样本进行预测,并针对每个特征计算其与每个最近邻的距离(称这些 neighb_dist
).然后对几个随机点(称为 rand_dist
)而不是最近的邻居进行相同的计算。然后对于每个特征,取 neighb_dist / rand_dist
的比率,比率越小,该特征越重要。
Gere 是一个很好的通用示例。
#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")
下面列出了所有详细信息。
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
我正在使用 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 分类器的参数。
没有为 KNN 分类算法定义特征重要性。这里没有简单的方法来计算负责分类的特征。您可以做的是使用具有 feature_importances_
属性的随机森林分类器。即使在这种情况下,feature_importances_
属性也会告诉您整个模型最重要的特征,而不是具体预测的样本。
不过,如果您打算使用 KNN,那么估计特征重要性的最佳方法是采用样本进行预测,并针对每个特征计算其与每个最近邻的距离(称这些 neighb_dist
).然后对几个随机点(称为 rand_dist
)而不是最近的邻居进行相同的计算。然后对于每个特征,取 neighb_dist / rand_dist
的比率,比率越小,该特征越重要。
Gere 是一个很好的通用示例。
#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")
下面列出了所有详细信息。
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