1.使用sklearn库和matplotlib.pyplot库

import sklearn
import matplotlib.pyplot as plt

2.准备绘图函数的传入参数1.预测的概率值数组2.预测的labels值数组

for i in range(len(y_labeles)):
a = np.argmax(y_labeles[i])
y_pred.append(y_conv.eval(feed_dict={x: np.reshape(mnist.test.images[i], [1, 784]), keep_prob: 0.5}, session=sess)[0][a])
y_labeles_d1.append(correct_prediction.eval(feed_dict={x: np.reshape(mnist.test.images[i], [1, 784]), y_: np.reshape(y_labeles[i], [1, 10]), keep_prob: 0.5}, session=sess))

3.调用sklearn.metrics.roc_curve();

fpr, tpr, thresholds = sklearn.metrics.roc_curve(y_labeles_d1, y_pred)

plt.plot(fpr, tpr, 'b')#生成ROC曲线
plt.legend(loc='lower right')
plt.plot([0, 1], [0, 1], 'r--')
plt.xlim([0, 1])
plt.ylim([0, 1])
plt.ylabel('TP')
plt.xlabel('FP')
plt.show()

4.例子

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import numpy as np
import sklearn
import matplotlib.pyplot as plt mnist = input_data.read_data_sets('data/', one_hot=True) def weight_variable(shape, name):
initial = tf.truncated_normal(shape, stddev=0.1, name=name)
return tf.Variable(initial) def bias_variable(shape, name):
initial = tf.constant(0.1, shape=shape, name=name)
return tf.Variable(initial) def conv2d(x, W):
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') def max_pool_2x2(x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') x = tf.placeholder(tf.float32, [None, 784])
y_ = tf.placeholder(tf.float32, [None, 10])
x_image = tf.reshape(x, [-1, 28, 28, 1]) W_conv1 = weight_variable([5, 5, 1, 32], name='W_conv1')
b_conv1 = bias_variable([32], name='b_conv1')
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1) W_conv2 = weight_variable([5, 5, 32, 64], name='W_conv2')
b_conv2 = bias_variable([64], name='b_conv2')
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2) W_fc1 = weight_variable([7*7*64, 1024], name='W_fc1')
b_fc1 = bias_variable([1024], name='b_fc1')
h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) keep_prob = tf.placeholder(tf.float32)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) W_fc2 = weight_variable([1024, 10], name='W_fc2')
b_fc2 = bias_variable([10], name='b_fc2')
y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2) cross_entropy = tf.reduce_sum(tf.nn.softmax_cross_entropy_with_logits(logits=y_conv, labels=y_)) # cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_conv), reduction_indices=[1]))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) sess = tf.Session()
sess.run(tf.global_variables_initializer()) for i in range(500): batch = mnist.train.next_batch(100) train_step.run(session=sess, feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})
if i % 500 == 0 and i != 0:
train_accuracy = accuracy.eval(session=sess, feed_dict={x: batch[0], y_: batch[1], keep_prob: 1.0})
print('step %d, training accuracy %g' % (i, train_accuracy)) print("!!!!!")
print('test accuracy %g' % accuracy.eval(session=sess, feed_dict={
x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0
})) saver = tf.train.Saver()
saver.save(sess, './trained_variables.ckpt', global_step=1000) y_labeles = mnist.test.labels
y_pred = []
y_labeles_d1 = [] for i in range(len(y_labeles)):
a = np.argmax(y_labeles[i])
y_pred.append(y_conv.eval(feed_dict={x: np.reshape(mnist.test.images[i], [1, 784]), keep_prob: 0.5}, session=sess)[0][a])
y_labeles_d1.append(correct_prediction.eval(feed_dict={x: np.reshape(mnist.test.images[i], [1, 784]), y_: np.reshape(y_labeles[i], [1, 10]), keep_prob: 0.5}, session=sess)) fpr, tpr, thresholds = sklearn.metrics.roc_curve(y_labeles_d1, y_pred) plt.plot(fpr, tpr, 'b')#生成ROC曲线
plt.legend(loc='lower right')
plt.plot([0, 1], [0, 1], 'r--')
plt.xlim([0, 1])
plt.ylim([0, 1])
plt.ylabel('TP')
plt.xlabel('FP')
plt.show() # with tf.Session() as sess:
# new_saver = tf.train.import_meta_graph('my_test_model-1000.meta')
# new_saver.restore(sess, tf.train.latest_checkpoint('./')) # print(sess.run(W_conv1))

5.效果:

scikit-learn画ROC图的更多相关文章

  1. (原创)(三)机器学习笔记之Scikit Learn的线性回归模型初探

    一.Scikit Learn中使用estimator三部曲 1. 构造estimator 2. 训练模型:fit 3. 利用模型进行预测:predict 二.模型评价 模型训练好后,度量模型拟合效果的 ...

  2. MATLAB画ROC曲线,及计算AUC值

    根据决策值和真实标签画ROC曲线,同时计算AUC的值 步骤: 根据决策值和真实标签画ROC曲线,同时计算AUC的值: 计算算法的决策函数值deci 根据决策函数值deci对真实标签y进行降序排序,得到 ...

  3. 使用Mysql Workbench 画E-R图

    MySQL Workbench 是一款专为MySQL设计的ER/数据库建模工具.你可以用MySQL Workbench设计和创建新的数据库图示,建立数据库文档,以及进行复杂的MySQL 迁移.这里介绍 ...

  4. 用rose画UML图(用例图,活动图)

    用rose画UML图(用例图,活动图) 首先,安装rose2003,电脑从win8升到win10以后,发现win10并不支持rose2003的安装,换了rose2007以后,发现也不可以. 解决途径: ...

  5. python中matplotlib画折线图实例(坐标轴数字、字符串混搭及标题中文显示)

    最近在用python中的matplotlib画折线图,遇到了坐标轴 "数字+刻度" 混合显示.标题中文显示.批量处理等诸多问题.通过学习解决了,来记录下.如有错误或不足之处,望请指 ...

  6. 相机拍的图,电脑上画的图,word里的文字,电脑屏幕,手机屏幕,相机屏幕显示大小一切的一切都搞明白了!

    相机拍的图,电脑上画的图,word里的文字,电脑屏幕,手机屏幕,相机屏幕显示大小一切的一切都搞明白了! 先说图片X×dpi=点数dotX是图片实际尺寸,简单点,我们只算图片的高吧,比如说拍了张图片14 ...

  7. SAS 画折线图PROC GPLOT

    虽然最后做成PPT里的图表会被要求用EXCEL画,但当我们只是在分析的过程中,想看看数据的走势,直接在SAS里画会比EXCEL画便捷的多. 修改起来也会更加的简单,,不用不断的修改程序然后刷新EXCE ...

  8. Windows8.1画热度图 - 坑

    想要的效果 如上是silverlight版本.原理是设定一个调色板,为256的渐变色(存在一个png文件中,宽度为256,高度为1),然后针对要处理的距离矩阵图形,取图片中每个像素的Alpha值作为索 ...

  9. 使用网站websequencediagrams在线画时序图

    在线画时序图的网站:https://www.websequencediagrams.com/ 该网站提供拖拉图形和编写脚本代码2个方式来制作时序图,同时提供多种显示风格. 实例: 1.脚本代码: ti ...

随机推荐

  1. Vue过渡动画—Vue学习笔记

    要求:要通过Vue使用过渡动画我们要把需要过度的元素放在<transition name='变量名'></transition>中. 原理:通过在特定的时刻增加/移除样式实现. ...

  2. [LeetCode] 206. Reverse Linked List_Easy tag: Linked List

    Reverse a singly linked list. Example: Input: 1->2->3->4->5->NULL Output: 5->4-> ...

  3. SQLServer中的cross apply和FOR XML PATH

    参考: FOR XML PATH:http://www.cnblogs.com/doubleliang/archive/2011/07/06/2098775.html cross apply:http ...

  4. vue传参页面刷新数据丢失问题

    在做vue的时候,经常会遇到组件之间数据的传递问题,通过params或者query传参,但是,当页面刷新的时候,数据会丢失,找不到数据.今天经过总结,解决了这个问题.通过了一下几种情况进行传值: 通过 ...

  5. Chapter 3 Phenomenon——24

    My mom was in hysterics, of course. 我的母亲当时是歇斯底里的发疯了. I had to tell her I felt fine at least thirty t ...

  6. 记一次解决CSS定位bug思路

    事因 网站中的遮罩层大都有一个问题,就是在这个遮罩层中滑动,里面的内容也会跟着滑动,我是这样想的,既然都有这个问题,干脆写一个通用的插件出来,省的每个还得单独处理.如果是单独处理这个问题是比较好解决的 ...

  7. C#中将String类型保存到本地文件的方法

    今天刚刚遇到,要在WinForm中把一个xml保存到本地, 由于之前是学习java的,一时间还真不知道怎么写, 没想到C#居然那么方便,就3句代码就实现了我要的功能: StreamWriter sw ...

  8. SingleThreadExecutor(单线程执行器)

    前要:一般的执行器会为每个任务单独创建线程,起码是分配单独的线程,即每个任务有其自己的线程.这样可以让任务并发执行.   问题:既然这样,为什么只用一个线程处理多个任务呢?     如果是这样,那一个 ...

  9. 对CAP原理的理解

    对CAP原理的理解 CAP原理按照定义,指的是C(Consistency)一致性,A(Availability)可用性,P(Partition tolerance)分区容错性在一个完整的计算机系统中三 ...

  10. GCC 多文件编辑

    #include <stdio.h> int plus(int a, int b); int minus(int a, int b); int multiply(int a, int b) ...