使用单热代码的Tensorflow混淆矩阵

时间:2017-10-18 12:48:31

标签: tensorflow confusion-matrix multiclass-classification one-hot-encoding

我使用RNN进行多类分类,这是我的RNN主要代码:

def RNN(x, weights, biases):
    x = tf.unstack(x, input_size, 1)
    lstm_cell = rnn.BasicLSTMCell(num_unit, forget_bias=1.0, state_is_tuple=True) 
    stacked_lstm = rnn.MultiRNNCell([lstm_cell]*lstm_size, state_is_tuple=True) 
    outputs, states = tf.nn.static_rnn(stacked_lstm, x, dtype=tf.float32)

    return tf.matmul(outputs[-1], weights) + biases

logits = RNN(X, weights, biases)
prediction = tf.nn.softmax(logits)

cost =tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=Y))
optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
train_op = optimizer.minimize(cost)

correct_pred = tf.equal(tf.argmax(prediction, 1), tf.argmax(Y, 1)) 
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))

我必须将所有输入分类为6个类,每个类都由一个热门代码标签组成,如下所示:

happy = [1, 0, 0, 0, 0, 0]
angry = [0, 1, 0, 0, 0, 0]
neutral = [0, 0, 1, 0, 0, 0]
excited = [0, 0, 0, 1, 0, 0]
embarrassed = [0, 0, 0, 0, 1, 0]
sad = [0, 0, 0, 0, 0, 1]

问题是我无法使用tf.confusion_matrix()函数打印混淆矩阵。

有没有办法用这些标签打印混淆矩阵?

如果没有,只有当我需要打印混淆矩阵时,如何才能将单热代码转换为整数索引?

1 个答案:

答案 0 :(得分:2)

您不能使用单热矢量作为labelspredictions的输入参数生成混淆矩阵。您必须直接提供包含标签的1D张量。

要将您的一个热矢量转换为普通标签,请使用argmax功能:

label = tf.argmax(one_hot_tensor, axis = 1)

之后,您可以像这样打印confusion_matrix

import tensorflow as tf

num_classes = 2
prediction_arr = tf.constant([1,  1, 1, 1,  0, 0, 0, 0,  1, 1])
labels_arr     = tf.constant([0,  1, 1, 1,  1, 1, 1, 1,  0, 0])

confusion_matrix = tf.confusion_matrix(labels_arr, prediction_arr, num_classes)
with tf.Session() as sess:
    print(confusion_matrix.eval())

输出:

[[0 3]
 [4 3]]