如何计算tensorflow张量中的元素?

Pau*_*ino 2 python tensorflow

我有一个张量,例如X = [1, 1, 0, 0, 1, 2, 2, 0, 1, 2]

我想要的是将这个张量减少X到一个张量,例如:Y = [3, 4, 3]

其中Y位置 0 是 中 0 的个数X,位置 1 是 1 的个数,以此类推。

我现在正在做的是使用该tf.where函数迭代这个张量。但这看起来并不优雅,必须有更好的方法来做到这一点。

谢谢。

vij*_*y m 5

我想您正在寻找Y = tf.bincount(X)

X = tf.constant([1, 1, 0, 0, 1, 2, 2, 0, 1, 2])
Y = tf.bincount(X)
sess = tf.InteractiveSession()
tf.global_variables_initializer().run()
Y.eval()

# output
#[3, 4, 3]
Run Code Online (Sandbox Code Playgroud)

对于负整数,您可以使用:

tf.bincount(X + tf.abs(tf.reduce_min(X)) )
Run Code Online (Sandbox Code Playgroud)