我正在训练二元分类器使用python
和流行的scikit-learn
模块的SVM
类。在训练后,我使用predict
方法进行分类,如sci-kit's SVC documentation所示。查找支持向量机分类的最重要功能
我想知道更多关于我的样本特征对经过训练的decision_function
(支持向量)所产生的分类的重要性。欢迎使用这种模型进行预测时评估特征重要性的任何策略。
谢谢! Andre
我正在训练二元分类器使用python
和流行的scikit-learn
模块的SVM
类。在训练后,我使用predict
方法进行分类,如sci-kit's SVC documentation所示。查找支持向量机分类的最重要功能
我想知道更多关于我的样本特征对经过训练的decision_function
(支持向量)所产生的分类的重要性。欢迎使用这种模型进行预测时评估特征重要性的任何策略。
谢谢! Andre
您可以使用SelectFromModel in sklearn来获取模型的最相关特征的名称。 Here is an example提取LassoCV的功能。
您还可以查看this example,它利用SVM中的coef_
属性显示最上面的特征。
那么,我们如何解释给定样本分类的特征显着性?
我认为使用线性内核是首先解决这个问题的最直接的方法,因为训练模型的svc.coef_
属性的重要性/相对简单性。 check out Bitwise's answer。
下面我将使用scikit
训练数据训练线性核SVM。然后我们将看看coef_
属性。我将包含一个简单的图,显示分类器系数和训练特征数据的点积如何划分结果类。
from sklearn import svm
from sklearn.datasets import load_breast_cancer
import numpy as np
import matplotlib.pyplot as plt
data = load_breast_cancer()
X = data.data # training features
y = data.target # training labels
lin_clf = svm.SVC(kernel='linear')
lin_clf.fit(X,y)
scores = np.dot(X, lin_clf.coef_.T)
b0 = y==0 # boolean or "mask" index arrays
b1 = y==1
malignant_scores = scores[b1]
benign_scores = scores[b1]
fig = plt.figure()
fig.suptitle("score breakdown by classification", fontsize=14, fontweight='bold')
score_box_plt = ply.boxplot(
[malignant_scores, benign_scores],
notch=True,
labels=list(data.target_names),
vert=False
)
plt.show(score_box_plt)
正如你可以看到,我们似乎已经访问了适当拦截和系数值。由于我们的评分系统基于线性系数,现在我们可以轻松研究每个特征对最终分类的贡献程度,我们可以很容易地调查每个特征对最终分类的贡献程度。这里我们在该样本的最后得分上显示每个特征效果。
## sample we're using X[2] --> classified benign, lin_clf score~(-20)
lin_clf.predict(X[2].reshape(1,30))
contributions = np.multiply(X[2], lin_clf.coef_.reshape((30,)))
feature_number = np.arange(len(contributions)) +1
plt.bar(feature_number, contributions, align='center')
plt.xlabel('feature index')
plt.ylabel('score contribution')
plt.title('contribution to classification outcome by feature index')
plt.show(feature_contrib_bar)
我们也可以简单地排序此相同的数据获得的功能对于一个给定的分类看贡献排名列表,它的功能贡献最大的score
我们正在评估的组成。
abs_contributions = np.flip(np.sort(np.absolute(contributions)), axis=0)
feat_and_contrib = []
for contrib in abs_contributions:
if contrib not in contributions:
contrib = -contrib
feat = np.where(contributions == contrib)
feat_and_contrib.append((feat[0][0], contrib))
else:
feat = np.where(contributions == contrib)
feat_and_contrib.append((feat[0][0], contrib))
# sorted by max abs value. each row a tuple:;(feature index, contrib)
feat_and_contrib
从这个排名列表我们可以看到,为了最终得分贡献(约-20连同分类“良性”)的五大功能指标均[0, 22, 13, 2, 21]
对应于我们的数据集中的功能名称; ['mean radius', 'worst perimeter', 'area error', 'mean perimeter', 'worst texture']
。