2017-07-19 240 views
1

我有一个张量例如:X = [1, 1, 0, 0, 1, 2, 2, 0, 1, 2]如何统计张量张量中的元素?

而我想要的是减少张量X张量如Y = [3, 4, 3]

其中位置0处的YX中有多少个0,以及位置1有多少个1,等等。

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

谢谢。

回答

4

您正在寻找tf.unique_with_counts

import tensorflow as tf 
X = tf.constant([1, 1, 0, 0, 1, 2, 2, 0, 1, 2]) 
op = tf.unique_with_counts(X) 
sess = tf.InteractiveSession() 
res = sess.run(op) 
print(res.count) 
# [4 3 3] 

要注意的是tf.bincount只处理正整数。如果输入张量不是整数类型,或者包含负值,则必须使用tf.unique_with_count。否则bincount是好的,并重点。

4

我认为你正在寻找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] 

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

tf.bincount(X + tf.abs(tf.reduce_min(X)))