我有一个数据集,我想在这些数据上训练我的模型。在训练之后,我需要知道SVM分类器分类中主要贡献者的特征。
对于森林算法有一些称为特征重要性的东西,有什么相似之处吗?
答案 0 :(得分:16)
是的,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)
答案 1 :(得分:0)
仅一行代码:
适合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
答案 2 :(得分:0)
我创建了一个基于Jakub Macina的代码段的解决方案,该解决方案也适用于Python 3。
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)
答案 3 :(得分:0)
如果您使用 rbf
(径向基函数)核,您可以使用 sklearn.inspection.permutation_importance
如下获取特征重要性。 [source]
from sklearn.inspection import permutation_importance
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
svc = SVC(kernel='rbf', C=2)
svc.fit(X_train, y_train)
perm_importance = permutation_importance(svc, X_test, y_test)
feature_names = ['feature1', 'feature2', 'feature3', ...... ]
features = np.array(feature_names)
sorted_idx = perm_importance.importances_mean.argsort()
plt.barh(features[sorted_idx], perm_importance.importances_mean[sorted_idx])
plt.xlabel("Permutation Importance")