2017-07-19 238 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)))