Skip to main content
 首页 » 编程设计

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

2024年08月20日29jillzhang

我成功得到了(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: \n\n', 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: \n\n', tf.Tensor.eval(con_mat,feed_dict=None, session=None)) 

希望这对您有所帮助。