如何绘制无概率(svm)的二进制分类器的ROC并计算AUC?

时间:2019-12-07 14:48:48

标签: python machine-learning scikit-learn svm roc

我有一些SVM分类器(LinearSVC)输出测试集中每个样本的最终分类,例如

1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1

以此类推。

“真相”标签也类似

1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1

我想用一些参数运行该svm,为roc曲线生成点,并计算auc。

我可以自己做,但是我敢肯定在这种情况下有人在我之前做过。

不幸的是,我能找到的一切都是针对分类器返回概率的情况,而不是像herehere这样的硬估计

我认为this可以工作,但是找不到from sklearn.metrics import plot_roc_curve

任何适合我情况的在线内容?

谢谢

2 个答案:

答案 0 :(得分:1)

您可以通过使用sklearn.svm.SVC并将probability参数设置为True来解决此问题。

您可以阅读:

  

概率:布尔值,可选(默认= False)

     

是否启用概率估计。必须先启用   调用fit,会减慢该方法的速度,因为它内部使用5倍   交叉验证,并且predict_proba可能与predict不一致。   在《用户指南》中了解更多信息。

作为示例(详细信息省略):

from sklearn.svm import SVC
from sklearn.metrics import roc_curve
from sklearn.metrics import roc_auc_score

.
.
.

model = SVC(kernel="linear", probability=True)
model.fit(X_train, y_train)

.
.
.

decision_scores = model.decision_function(X_test)
fpr, tpr, thres = roc_curve(y_test, decision_scores)
print('AUC: {:.3f}'.format(roc_auc_score(y_test, decision_scores)))

# roc curve
plt.plot(fpr, tpr, "b", label='Linear SVM')
plt.plot([0,1],[0,1], "k--", label='Random Guess')
plt.xlabel("false positive rate")
plt.ylabel("true positive rate")
plt.legend(loc="best")
plt.title("ROC curve")
plt.show()

您应该得到类似这样的东西:

enter image description here


注意LinearSVCSVC(kernel="linear")快得多,尤其是在训练集非常大或功能丰富的情况下。

答案 1 :(得分:1)

您可以在此处使用决策功能

from sklearn.svm import LinearSVC
from sklearn.datasets import make_classification
X, y = make_classification(n_features=4, random_state=0)
clf = LinearSVC(random_state=0, tol=1e-5)
clf.fit(X, y)
LinearSVC(C=1.0, class_weight=None, dual=True, fit_intercept=True,
     intercept_scaling=1, loss='squared_hinge', max_iter=1000,
     multi_class='ovr', penalty='l2', random_state=0, tol=1e-05, verbose=0)

print(clf.predict([[0, 0, 0, 0]]))
#>>[1]
print(clf.decision_function([[0, 0, 0, 0]]))
#>>[ 0.2841757]

最干净的方法是使用Platt缩放将decision_function给定的超平面距离转换为概率。

但是又快又脏

[math.tanh(v)/2+0.5 for v in clf.decision_function([[0, 0, 0, 0],[1,1,1,1]])]
#>>[0.6383826839666699, 0.9635586809605969]

由于Platts缩放比例保持示例的顺序,因此roc曲线中的结果将保持一致。

此外: 普拉特的方法也存在理论问题。如果需要置信度得分,但不一定非要是概率,则建议将概率设置为False,并使用Decision_function而不是predict_proba。

相关问题