Argmin可能是空张量

时间:2017-10-14 13:42:50

标签: python python-3.x tensorflow

我想对张量流中可能为空的张量进行argmin,并返回一些值,如空列表或-1。 默认情况下,空张量上的armgin会产生以下结果:

InvalidArgumentError: Reduction axis 0 is empty in shape [0]

也许使用tf.conf会有所帮助,但我不确定如何检查矢量是否为空:

tf.equal(tf.size(vec), tf.constant(0)).eval()
ValueError: Operation 'Equal_5' has been marked as not fetchable.

还存在懒惰问题。

tf.cond(isEmpty(vec), lambda: tf.constant(0, dtype="int64"), lambda: tf.argmin(vec))

如果第一个问题已解决,即可以构建一些isEmpty函数,上述cond是否有效?

1 个答案:

答案 0 :(得分:0)

这只是互动会议的表现。以下工作正常:

import tensorflow as tf


sess = tf.Session()

a = tf.ones((2, 2, 4))
b = tf.zeros((2, 2, 4))
zero = tf.constant(0, dtype="float32")
idx = tf.constant([1, 1])

region_a = tf.gather_nd(a, idx)
region_b = tf.gather_nd(b, idx)

where_a = tf.not_equal(region_a, zero)
where_b = tf.not_equal(region_b, zero)

inuse_a = tf.where(where_a)
inuse_b = tf.where(where_b)
inuse_a_flat = tf.reshape(inuse_a, [-1])
inuse_b_flat = tf.reshape(inuse_b, [-1])

qvals = tf.ones(4, dtype="float32")
qvals_flat = tf.reshape(qvals, [-1])

inuse_a_q = tf.gather(qvals_flat, inuse_a_flat)
inuse_b_q = tf.gather(qvals_flat, inuse_b_flat)

size_iuq_a = tf.size(inuse_a_q)
size_iuq_b = tf.size(inuse_b_q)

eq_a = tf.equal(tf.size(inuse_a_q), tf.constant(0))
eq_b = tf.equal(tf.size(inuse_b_q), tf.constant(0))

argmin_a = tf.cond(
    eq_a,
    lambda: tf.constant(-1, dtype="int64"),
    lambda: tf.argmin(inuse_a_flat))

argmin_b = tf.cond(
    eq_b,
    lambda: tf.constant(-1, dtype="int64"),
    lambda: tf.argmin(inuse_b_flat))

with sess.as_default():
    print(inuse_a_q.eval())
    print(inuse_b_q.eval())
    print("\n")
    print(size_iuq_a.eval())
    print(size_iuq_b.eval())
    print("\n")
    print(eq_a.eval())
    print(eq_b.eval())
    print("\n")
    print(argmin_a.eval())
    # 0
    print(argmin_b.eval())
    # -1