2017-05-04 34 views
0

我想在Tensorflow中獲取roc_curve和混淆矩陣。我使用了sklearn.metrics函數,並且出現錯誤。我的代碼如下: 從sklearn.metrics進口roc_curve,AUC如何在TensorFlow中獲得ROC_Curve和混亂矩陣

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. 

任何幫助將不勝感激。謝謝!

回答

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訪問張量或計算的值/結果。