【问题标题】:how to give negative conditions in tf.where tensorflow如何在 tf.where tensorflow 中给出否定条件
【发布时间】:2021-05-27 18:53:58
【问题描述】:

我想提取不满足某些条件的张量的索引。

例如,我想要一个张量行的索引,其中所有列都不为零。

idx = tf.where(!(x[:,0]==x[:,1]==x[:,2]==0))

还有其他更好的方法来提取此类信息吗?

【问题讨论】:

    标签: tensorflow keras indices


    【解决方案1】:

    提取所有元素都不为 0 的张量的索引相当于查找元素的绝对值之和不为 0 的张量(在您的张量的元素可能为负的情况下)。

    x = tf.constant([[2.0, 0., 4.0], [0., 0., 2.0], [-2.0, 0., 1.0]])
    
    idx = tf.where(tf.reduce_sum(tf.abs(x), axis=0)!=0)
    

    输出:

    >>>print(idx)
    tf.Tensor(
    [[0]
     [2]], shape=(2, 1), dtype=int64)
    

    如果所有值都是正数,tf.abs 将毫无用处。

    您也可以使用 tf.math.logical_not 来反转条件:

    >>>print(tf.math.logical_not(x==0))
    tf.Tensor(
    [[ True False  True]
     [False False  True]
     [ True False  True]], shape=(3, 3), dtype=bool)
    

    【讨论】:

    • 谢谢。我用了 idx = tf.where(tf.reduce_sum(tf.abs(y_true), axis=1)!=0) # all of (x,y,z) 不为零 y_true = tf.gather_nd(y_true, idx)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-18
    • 1970-01-01
    • 2022-11-04
    • 1970-01-01
    相关资源
    最近更新 更多