【问题标题】:Compare two tensors of numpy arrays by each array - tensorflow按每个数组比较两个 numpy 数组的张量 - tensorflow
【发布时间】:2020-12-21 17:14:10
【问题描述】:

我有一个多标签分类问题,我在训练期间的y_truey_pred 看起来像这样:

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

我想根据每对列表比较这两者。 为此,我写了类似的东西

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()

返回

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

-4.0 因为2.0 - 6.0 == -4.0

但我不想要这个。我想将y_true 的第一个数组与y_pred 的第一个数组进行比较,如果它们相同,则返回True,否则返回False。同样的逻辑适用于y_truey_pred 的第二个数组。

所以正确的结果应该是

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] 

还有tranformed_values_summed.numpy() = 2.0 - 1.0 = 1.0

【问题讨论】:

    标签: python arrays tensorflow


    【解决方案1】:

    我想你可能正在寻找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])>
    

    复制/粘贴:

    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)
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-06
    • 2017-01-18
    • 1970-01-01
    • 2012-05-21
    相关资源
    最近更新 更多