绘制最近质心的ROC曲线

时间:2017-11-30 11:28:36

标签: python matplotlib plot scikit-learn

我想绘制一条ROC曲线,用于评估经过训练的最近质心分类器。 我的代码适用于朴素贝叶斯,SVM,kNN和DT,但每当我尝试绘制最近质心的曲线时我都会遇到异常,因为估算器没有.predict_proba()方法:

AttributeError: 'NearestCentroid' object has no attribute 'predict_proba'

绘制曲线的代码是

def plot_roc(self):
        plt.clf()

        for label, estimator in self.roc_estimators.items():
            estimator.fit(self.data_train, self.target_train)
            proba_for_each_class = estimator.predict_proba(self.data_test)

            fpr, tpr, thresholds = roc_curve(self.target_test, proba_for_each_class[:, 1])

            plt.plot(fpr, tpr, label=label)

        plt.plot([0, 1], [0, 1], linestyle='--', lw=2, color='r', label='Luck', alpha=.8)

        plt.ylabel('True Positive Rate')
        plt.xlabel('False Positive Rate')
        plt.legend()
        plt.show()

self.roc_estimators是一个字典,我将经过训练的估算器与分类器的标签存储在一起

cl_label = "kNN"
knn_estimator = KNeighborsClassifier(algorithm='ball_tree', p=2, n_neighbors=5)
knn_estimator.fit(self.data_train, self.target_train)
self.roc_estimators[cl_label] = knn_estimator
分别为

和最近的质心

cl_label = "Nearest Centroid"
nc_estimator = NearestCentroid(metric='euclidean', shrink_threshold=6)
nc_estimator.fit(self.data_train, self.target_train)
self.roc_estimators[cl_label] = nc_estimator

因此它适用于我尝试过的所有分类器,但不适用于最近的质心。关于我遗漏的最近质心分类器的性质是否有一个特定的原因解释了为什么不可能绘制ROC曲线(更具体地说,为什么估算器没有.predict_proba()方法?)谢谢你前进!<​​/ p>

2 个答案:

答案 0 :(得分:1)

你需要一个&#34;得分&#34;为每个预测做出ROC曲线。这可能是属于一个类的预测概率。

参见例如https://en.wikipedia.org/wiki/Receiver_operating_characteristic#Curves_in_ROC_space

只是寻找最接近的质心会给你预测的等级,但不是概率。

编辑:对于NearestCentroid,无法计算得分。这只是模型的限制。它为每个样本分配一个类,但不是该类的概率。我想如果你需要使用最近的质心并且你想要一个概率,你可以使用一些整体方法。训练一组训练数据子集的模型,并在测试集上平均他们的预测。这可以给你一个分数。请参阅scikit-learn.org/stable/modules/ensemble.html#bagging

答案 1 :(得分:0)

要获取类概率,您可以执行以下操作(未经测试的代码):

from sklearn.utils.extmath import softmax
from sklearn.metrics.pairwise import pairwise_distances

def predict_proba(self, X):
    distances = pairwise_distances(X, self.centroids_, metric=self.metric)
    probs = softmax(distances)
    return probs

clf = NearestCentroid()
clf.fit(X_train, y_train)
predict_proba(clf, X_test)