如何使用 Tensorflow 和 scikit-learn 绘制 ROC 曲线?

Posted

技术标签:

【中文标题】如何使用 Tensorflow 和 scikit-learn 绘制 ROC 曲线?【英文标题】:How to plot a ROC curve with Tensorflow and scikit-learn? 【发布时间】:2016-08-24 16:09:41 【问题描述】:

我正在尝试根据 tensorflow 提供的 CIFAR-10 示例的修改版本绘制 ROC 曲线。现在是 2 个班级而不是 10 个班级。

网络的输出称为 logits 并采用以下形式:

[[-2.57313061 2.57966399] [ 0.04221377 -0.04033273] [-1.42880082 1.43337202] [-2.7692945 2.78173304] [-2.48195744 2.49331546] [2.0941515 -2.10268974] [-3.51670194 3.53267646] [-2.74760485 2.75617]

首先,这些logits实际上代表什么?网络中的最后一层是 WX+b 形式的“softmax linear”。

模型可以通过调用计算准确率

top_k_op = tf.nn.in_top_k(logits, labels, 1)

然后一旦图被初始化:

predictions = sess.run([top_k_op])
predictions_int = np.array(predictions).astype(int)
true_count += np.sum(predictions) 
...
precision = true_count / total_sample_count

这很好用。

但是现在我如何从中绘制 ROC 曲线?

我一直在尝试“sklearn.metrics.roc_curve()”函数 (http://scikit-learn.org/stable/modules/generated/sklearn.metrics.roc_curve.html#sklearn.metrics.roc_curve),但我不知道用什么作为“y_score”参数。

任何帮助将不胜感激!

【问题讨论】:

查看此处link 获取计算和绘制 ROC 曲线的代码。 【参考方案1】:

这里的'y_score'应该是一个数组,对应于每个样本被分类为阳性的概率(如果阳性在你的y_true数组中被标记为1)

实际上,如果你的网络使用 Softmax 作为最后一层,那么模型应该输出这个实例的每个类别的概率。但是您在此处提供的数据不符合此格式。我检查了示例代码:https://github.com/tensorflow/tensorflow/blob/r0.10/tensorflow/models/image/cifar10/cifar10.py 似乎使用了名为 softmax_linear 的层,我对这个示例知之甚少,但我想你应该用 Logistic Function 之类的东西处理输出,将其转化为概率。

然后将其与您的真实标签“y_true”一起提供给 scikit-learn 函数:

y_score = np.array(output)[:,1]
roc_curve(y_true, y_score)

【讨论】:

我也是这种情况……如果模型的输出值太大,会导致 Logistic 函数饱和。我该如何继续?【参考方案2】:
import tensorflow as tf
tp = [] # the true positive rate list
fp = [] # the false positive rate list
total = len(fp)
writer = tf.train.SummaryWriter("/tmp/tensorboard_roc")
for idx in range(total):
    summt = tf.Summary()
    summt.value.add(tag="roc", simple_value = tp[idx])
    writer.add_summary (summt, tp[idx] * 100) #act as global_step
    writer.flush ()

然后启动张量板:

tensorboard --logdir=/tmp/tensorboard_roc

tensorboard_roc

详情和代码可以访问我的博客:http://blog.csdn.net/mao_feng/article/details/54731098

【讨论】:

我在模型中使用了这段代码,但在 tensorboard 上我只看到从 (0,0) 开始的直线。 是的,即使我看到从 (0,0) 到 (1,1) 的对角线。这不起作用。

以上是关于如何使用 Tensorflow 和 scikit-learn 绘制 ROC 曲线?的主要内容,如果未能解决你的问题,请参考以下文章

Tensorflow DNNClassifier 和 scikit-learn GridSearchCV 问题

混淆矩阵(Confusion matrix)的原理及使用(scikit-learn 和 tensorflow)

现在tensorflow和mxnet很火,是不是还有必要学习scikit-learn等框架

结合 scikit-learn 模型使用 TensorFlow 预处理(tf.feature_column)

分享《机器学习实战:基于Scikit-Learn和TensorFlow》高清中英文PDF+源代码

使用 tensorflow 代替 scikit-learn 进行回归有啥优势? [关闭]