Tensorflow:如何将混淆矩阵(张量)显示为数组



我已成功获得(7x7(的混淆矩阵。它是张量形式。

我想查看混淆矩阵。尝试了 .eval 和 sess 方法,但它不起作用。

我的代码:

n_classes = 7
prediction = neural_network(x)
correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct, 'float'))
con_mat = tf.confusion_matrix(labels=[0, 1, 2, 3, 4, 5, 6], predictions=correct, num_classes=n_classes, dtype=tf.int32, name=None)
print('Confusion Matrix: nn', tf.SparseTensor.eval(con_mat, feed_dict=None, session=None))

输出:

AttributeError: 'Tensor' object has no attribute 'indices'

TF.SparseTensor.eval

神经网络:

weights = {
        'out': tf.Variable(tf.truncated_normal([hidden_units, n_classes], dtype=tf.float32))
    }
    biases = {
        'out': tf.Variable(tf.zeros([n_classes]))
    }
    x = tf.unstack(x, seq_len, 1)
    # 3-layer LSTM with 128 units.
    cell = rnn_cell_impl.MultiRNNCell([rnn_cell_impl.LSTMCell(hidden_units),
                                       rnn_cell_impl.LSTMCell(hidden_units),
                                       rnn_cell_impl.LSTMCell(hidden_units)])
    outputs, states = rnn.static_rnn(cell, x, dtype=tf.float32)
    output = tf.matmul(outputs[-1], weights['out']) + biases['out']
    return output

您可以通过运行来查看混淆矩阵

con_mat = tf.confusion_matrix(labels=[0, 1, 2, 3, 4, 5, 6], predictions=correct, num_classes=n_classes, dtype=tf.int32, name=None)
with tf.Session():
   print('Confusion Matrix: nn', tf.Tensor.eval(con_mat,feed_dict=None, session=None))

希望这有帮助。

定义混淆矩阵(在神经网络的上下文中,但相同的方法适用于其他方法(:

confusion = tf.confusion_matrix(tf.argmax(one_hot, 1),tf.argmax(logits, 1))

运行和打印矩阵:

with tf.Session() as sess:
    test_confusion = sess.run(confusion, feed_dict={X_place:X,y_place:y})
    print(test_confusion)