tensorflow – tf.confusion_matrix() throws error ValueError: Shape (2, 2048, 2) must have rank 2

Question:

I try to determine the confusion_matrix of my neural network model which
is written in python by using google tensorflow.
By using this piece of code:

cm = tf.zeros(shape=[2,2], dtype=tf.int32)

for i in range(0, validation_data.shape[0], batch_size_validation):
    batched_val_data = np.array(validation_data[i:i+batch_size_validation, :, :], dtype='float')
    batched_val_labels = np.array(validation_labels[i:i+batch_size_validation, :], dtype='float')

    batched_val_data = batched_val_data.reshape((-1, n_chunks, chunk_size))            

    _acc, _c, _p = sess.run([accuracy, correct, pred], feed_dict=({x:batched_val_data, y:batched_val_labels}))

    #batched_val_labels.shape ==> (2048, 2)
    #_p.shape                 ==> (2048, 2)
    #this piece of code throws the error!
    cm = tf.confusion_matrix(labels=batched_val_labels, predictions=_p)

I get the following error:
ValueError: Shape (2, 2048, 2) must have rank 2

At least you should know that the array for the validation labels batched_val_labels is an one hot array.
Can someone help me pls? Thanks in advance!

Asked By: H. Senkaya

||

Answers:

The problem was that I am using an one hot array.
By following this instruction: Tensorflow confusion matrix using one-hot code

I changed this piece of code:

cm = tf.math.confusion_matrix(labels=batched_val_labels, predictions=_p)

into:

cm = tf.math.confusion_matrix(labels=tf.argmax(batched_val_labels, 1), predictions=tf.argmax(_p, 1))
Answered By: H. Senkaya