2

I have a multilabel classification problem and my y_true and y_pred during training looks like this:

y_true = tf.constant([[0, 1, 1, 0], [0, 1, 1, 0]])
y_pred = tf.constant([[0, 1, 0, 1], [0, 1, 1, 0]])

I want to compare those two based on each pair of lists. To do so, I wrote something like

values = tf.cast(x, "float32") == tf.cast(y, "float32")
bool_to_number_values = tf.cast(tranformed_values, "float32")
print(bool_to_number_values)
tranformed_values_summed = x.numpy().shape[0] - tf.reduce_sum(bool_to_number_values)
tranformed_values_summed.numpy()

This returns

tf.Tensor(
[[1. 1. 0. 0.]
 [1. 1. 1. 1.]], shape=(2, 4), dtype=float32)

and -4.0 because 2.0 - 6.0 == -4.0

But I don't want this. I want to compare the first array of y_true to the first array of y_pred and if they are identical return True else False. The same logic applies for the second array of y_true and y_pred.

So the correct result should be

tf.Tensor(
[0,
 1], , shape=(2,), dtype=float32)

#0: because the arrays on index 0 are not equal y_true[0] <> y_pred[0]
#1: because the arrays on index 1 are equal y_true[1] == y_pred[1] 

and the tranformed_values_summed.numpy() = 2.0 - 1.0 = 1.0

NikSp
  • 1,262
  • 2
  • 19
  • 42

1 Answers1

2

I think you might be looking for tf.reduce_all:

tf.cast(tf.reduce_all(tf.equal(y_true, y_pred), axis=-1), tf.int32)
<tf.Tensor: shape=(2,), dtype=int32, numpy=array([0, 1])>

Copy/pastable:

import tensorflow as tf

y_true = tf.constant([[0, 1, 1, 0], [0, 1, 1, 0]])
y_pred = tf.constant([[0, 1, 0, 1], [0, 1, 1, 0]])

tf.cast(tf.reduce_all(tf.equal(y_true, y_pred), axis=-1), tf.int32)
Nicolas Gervais
  • 33,817
  • 13
  • 115
  • 143
  • Nicolas thanks a lot for your answer. Imagine that I have used ```reduce_all``` after checking this https://stackoverflow.com/questions/56394240/how-to-compare-two-arrays-using-tensorflow...Although, I missed ```axis=-1``` which made the trick. – NikSp Dec 21 '20 at 17:23
  • 1
    It happens to the best of us ;) – Nicolas Gervais Dec 21 '20 at 17:25
  • Nicolas could please check (on your spare time) this question https://stackoverflow.com/questions/65381855/custom-zero-one-loss-metric-function-is-not-correctly-calculated-during-keras-ne Glad to receive your thoughts about it. – NikSp Dec 21 '20 at 18:17