【问题标题】:How to count non zero rows in a N-d tensor?如何计算 N-d 张量中的非零行?
【发布时间】:2021-02-08 09:16:00
【问题描述】:

我需要找到非零行的数量并将它们放入一维张量(一种向量)中。

举个例子:

tensor = [
    [
        [1, 2, 3, 4, 0, 0, 0],
        [4, 5, 6, 7, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0]
    ],
    [
        [4, 3, 2, 1, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0], 
        [0, 0, 0, 0, 0, 0, 0]
    ],
    [
        [0, 0, 0, 0, 0, 0, 0],
        [4, 5, 6, 7, 0, 0, 0],
        [0, 0, 0, 0, 0, 0, 0]
    ]
]

张量形状在实际应用中为[None,45,7],但这里是[3,2,7]

所以我需要找到维度 1 中非零行的数量,并将它们保持在一维张量中。

non_zeros = [2,1,1] #result for the above tensor

我需要在TensorFlow 做,如果它在NumPy,我会做的。

谁能帮我解决这个问题?

提前致谢

【问题讨论】:

    标签: python python-3.x tensorflow


    【解决方案1】:

    您可以将tf.math.count_nonzerotf.reduce_sum 结合使用

    >>> tf.math.count_nonzero(tf.reduce_sum(tensor,axis=2),axis=1)
    <tf.Tensor: shape=(3,), dtype=int64, numpy=array([2, 1, 1])>
    

    【讨论】:

      【解决方案2】:

      试试这个代码:

      t = tf.math.not_equal(tensor, 0)
      t = tf.reduce_any(t, -1)
      t = tf.cast(t, tf.int32)
      t = tf.reduce_sum(t, -1)
      

      【讨论】:

        猜你喜欢
        • 2020-02-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-11
        • 2022-01-24
        • 2018-11-19
        • 1970-01-01
        相关资源
        最近更新 更多