【问题标题】:How to check if a tensor is empty in Tensorflow如何在 Tensorflow 中检查张量是否为空
【发布时间】:2018-05-25 12:31:36
【问题描述】:

我的部分代码如下:

class_label = tf.placeholder(tf.float32, [None], name="condition_checking")
row_index = tf.where(class_label > 0)

我想检查row_index什么时候为空写如下

loss_f_G_filtered = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(
    logits=y1_filterred, labels=y__filtered), name="filtered_reg")

if row_index == []:
  loss_f_G_filtered = tf.constant(0, tf.float32)

但是,我不知道如何检查row_index 是否为空张量。

【问题讨论】:

    标签: tensorflow tensor


    【解决方案1】:
    is_empty = tf.equal(tf.size(row_index), 0)
    

    【讨论】:

    • 我只是用另一种方式解决了它,但这要简单得多。谢谢
    【解决方案2】:

    你可以使用tf.cond:

    idx0 = tf.shape(row_index)[0]
    loss_f_G_filtered = tf.cond(idx0 == 0,
                                lambda: tf.constant(0, tf.float32),
                                lambda: ...another function...)
    

    【讨论】:

    • 谢谢@walkerlala,问题是条件永远不会成立,我在down中添加了解释
    【解决方案3】:
        loss_f_G = 
    
    tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=y1_filterred, labels=y__filtered), name = "filtered_reg")
        idx0 = tf.shape(row_index)[0]
        loss_f_G_filtered = tf.cond(tf.cast(idx0 == 0, tf.bool), lambda: tf.constant(0, tf.float32), lambda:loss_f_G)
    

    问题是 idx0 == 0 永远不会为真,即使 row_index = []。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-08
      • 1970-01-01
      • 2021-03-30
      • 1970-01-01
      • 2011-05-20
      相关资源
      最近更新 更多