我有一个数据集,我想在这些数据上训练我的模型。在训练之后,我需要知道SVM分类器分类中主要贡献者的特征。
对森林算法有一些称为特征重要性的东西,有什么类似的吗?
是的,SVM分类器有属性coef_
,但它仅适用于具有线性内核的SVM。对于其他内核,它是不可能的,因为数据被内核方法转换到另一个与输入空间无关的空间,请检查explanation。
from matplotlib import pyplot as plt
from sklearn import svm
def f_importances(coef, names):
imp = coef
imp,names = zip(*sorted(zip(imp,names)))
plt.barh(range(len(names)), imp, align='center')
plt.yticks(range(len(names)), names)
plt.show()
features_names = ['input1', 'input2']
svm = svm.SVC(kernel='linear')
svm.fit(X, Y)
f_importances(svm.coef_, features_names)
只需一行代码:
适合SVM模型:
from sklearn import svm
svm = svm.SVC(gamma=0.001, C=100., kernel = 'linear')
并实施如下图:
pd.Series(abs(svm.coef_[0]), index=features.columns).nlargest(10).plot(kind='barh')
结果将是:
the most contributing features of the SVM model in absolute values
我创建了一个适用于Python 3的解决方案,它基于Jakub Macina的代码片段。
from matplotlib import pyplot as plt
from sklearn import svm
def f_importances(coef, names, top=-1):
imp = coef
imp, names = zip(*sorted(list(zip(imp, names))))
# Show all features
if top == -1:
top = len(names)
plt.barh(range(top), imp[::-1][0:top], align='center')
plt.yticks(range(top), names[::-1][0:top])
plt.show()
# whatever your features are called
features_names = ['input1', 'input2', ...]
svm = svm.SVC(kernel='linear')
svm.fit(X_train, y_train)
# Specify your top n features you want to visualize.
# You can also discard the abs() function
# if you are interested in negative contribution of features
f_importances(abs(clf.coef_[0]), feature_names, top=10)