如何知道"tf.boolean_mask"返回的动态张量是否为空?



tf.boolean_mask(tensor, mask) => returns (?, 4)

如何检查返回的张量是否为空boolean_mask

也许我们可以检查张量的大小是否等于 0。

tensor = tf.placeholder(name="tensor",shape=(None,4),dtype=tf.float32)
mask = tf.placeholder(name="mask",shape=(None,4),dtype=tf.bool)
print(tensor.shape)
# (?,4)
after_mask = tf.boolean_mask(tensor, mask)
is_empty = tf.equal(tf.size(after_mask), 0)
with tf.Session() as sess:
_t = np.arange(12).reshape(3,4)
_m_1 = np.random.randint(1,2,size=4).astype(np.bool).reshape(1,4)
_m_0 = np.random.randint(0,1,size=4).astype(np.bool).reshape(1,4)
_is_empty_0 = sess.run(is_empty, {tensor: _t, mask: _m_0}) # True
_is_empty_1 = sess.run(is_empty, {tensor: _t, mask: _m_1}) # False

有多种方法可以解决这个问题,基本上您正在尝试识别零张量。 可能的解决方案可以是:

  1. is_empty = tf.equal(tf.size(boolean_tensor(, 0(.如果不为空,它将给出假
  2. 使用 tf.count_nonzero(boolean_tensor( 计算非零数
  3. 通过简单地打印张量并检查变量

最新更新