我想在Tensorflow中获得一个roc_curve和混淆矩阵。我使用了sklearn.metrics函数,我收到了一个错误。我的代码如下: 来自sklearn.metrics import roc_curve,auc
n_inputs = x_train.shape[1]
n_hidden1 = 500
n_hidden2 = 200
n_outputs = 2
learning_rate = 0.01
X = tf.placeholder(tf.float32, shape=(None, n_inputs), name="X")
y = tf.placeholder(tf.int64, shape=(None), name="y")
hidden1 = tf.layers.dense(X, n_hidden1, activation=None)
hidden2 = tf.layers.dense(hidden1, n_hidden2, activation=None)
logits = tf.layers.dense(hidden2, n_outputs)
loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y, logits=logits))
training_op = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)
correct = tf.nn.in_top_k(logits, y, 1)
accuracy = tf.reduce_mean(tf.cast(correct, tf.float32))
init = tf.global_variables_initializer()
n_epochs = 20
with tf.Session() as sess:
init.run()
for epoch in range(n_epochs):
sess.run(training_op, feed_dict={X: x_train, y: y_train})
acc_train = accuracy.eval(feed_dict={X: x_train, y: y_train})
acc_test = accuracy.eval(feed_dict={X: x_test, y: y_test})
print("Epoch:", epoch, "Train accuracy:", acc_train, "Test accuracy:", acc_test)
y_score = np.array(logits)
roc_curve(y_test, y_score)
我得到的错误如下:
TypeError: Singleton array array(<tf.Tensor 'dense_26/BiasAdd:0' shape=(?, 2) dtype=float32>, dtype=object) cannot be considered a valid collection.
任何帮助将不胜感激。谢谢!
答案 0 :(得分:1)
致电时
sess.run(training_op, feed_dict={X: x_train, y: y_train})
您需要请求网络返回logits
张量的值,将其更改为:
training_op_result, logits_result = sess.run([training_op, logits], feed_dict={X: x_train, y: y_train})
y_score = np.array(logits_result)
roc_curve(y_test, y_score)
张量是图形对象。您可以通过sess.run
访问张量或计算的值/结果。