【问题标题】:how to count the nonzero mismatches between two tensors如何计算两个张量之间的非零不匹配
【发布时间】:2020-10-30 20:12:03
【问题描述】:

假设我在张量流中有两个张量,A,B(形状相同)。假设这些都是稀疏的。我需要知道其中一个张量在给定索引处具有非零值而另一个张量具有零值的实例的计数。所以,我正在寻找许多位置(i,j 对),其中一个矩阵在那里具有非零值,而另一个矩阵在那里具有零值。如何有效地做到这一点?

【问题讨论】:

    标签: python tensorflow


    【解决方案1】:

    我会这样做:

    import tensorflow as tf
    tensor1 = tf.constant([[0, 1], [0, 2]])
    tensor2 = tf.constant([[1, 0], [0, 2]])
    a = tf.math.equal(tensor1, tf.zeros_like(tensor1))
    b = tf.math.equal(tensor2, tf.zeros_like(tensor2))
    c = tf.math.equal(a, b)
    c = tf.cast(c, tf.int32)
    c = tf.math.reduce_sum(c)
    

    【讨论】:

      【解决方案2】:
      import tensorflow as tf
      
      a = tf.sparse.SparseTensor(
          [[0,1], [1,1]], [1,2], [2,2]
      )
      b = tf.sparse.SparseTensor(
          [[0,0], [0,1],[1,0]], [1,2,1], [2,2]
      )
      
      res = tf.reduce_sum(
          tf.cast(tf.math.logical_xor(
              tf.math.not_equal(tf.sparse.to_dense(a), 0), 
              tf.math.not_equal(tf.sparse.to_dense(b), 0)
          ), 'int32')
      )
      

      【讨论】:

      • @NicolasGervais,我只是创建了两个布尔数组来指示 a 或 b 在何处获得非零值。如果我对这两个布尔数组进行异或运算,我会在一个数组具有非零元素的每个位置得到 True。 (对于异或 - (0,0 -> 0) / (0,1 -> 1) / (1,0 -> 1) / (1,1 -> 0))
      【解决方案3】:

      这样就可以了。它根据这些条件对 True 案例进行汇总,逐个元素:

      1. ab 的值不相等
      2. a 不为零
      3. b 不为零
      tf.reduce_sum(
          tf.cast(
              tf.logical_and(
                  tf.not_equal(tf.sparse.to_dense(a), tf.sparse.to_dense(b)),
                  tf.cast(tf.sparse.to_dense(a), tf.bool),
                  tf.cast(tf.sparse.to_dense(b), tf.bool)),
              tf.int32))
      

      基于这两个稀疏张量:

      <tf.Tensor: shape=(3, 3), dtype=int32, numpy=
      array([[1, 0, 2],
             [0, 1, 0],
             [0, 2, 1]])>
      
      <tf.Tensor: shape=(3, 3), dtype=int32, numpy=
      array([[2, 2, 2],
             [0, 0, 0],
             [0, 2, 1]])>
      

      完整示例:

      import tensorflow as tf
      
      a = tf.SparseTensor(indices=[[0, 0], [0, 2], [1, 1], [2, 1], [2, 2]],
                          values=[1, 2, 1, 2, 1], dense_shape=[3, 3])
      b = tf.SparseTensor(indices=[[0, 0], [0, 1], [0, 2], [2, 1], [2, 2]],
                          values=[2, 2, 2, 2, 1], dense_shape=[3, 3])
      
      tf.sparse.to_dense(a)
      tf.sparse.to_dense(b)
      
      tf.reduce_sum(
          tf.cast(
              tf.logical_and(
                  tf.not_equal(tf.sparse.to_dense(a), tf.sparse.to_dense(b)),
                  tf.cast(tf.sparse.to_dense(a), tf.bool),
                  tf.cast(tf.sparse.to_dense(b), tf.bool)),
              tf.int32))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多