如何在 Tensorflow 中检查张量是否为空
How to check if a tensor is empty in Tensorflow
我的部分代码如下:
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
是否为空张量。
您可以使用 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...)
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 = [].
is_empty = tf.equal(tf.size(row_index), 0)
我的部分代码如下:
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
是否为空张量。
您可以使用 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...)
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 = [].
is_empty = tf.equal(tf.size(row_index), 0)