How to get an element counter in a tensor

I want to get the counter of the element in the tensor, for example t = [1,2,0,0,0,0]] (t is the tensor), I can get the sum 4 from '0' by calling t.count (0) in python but in tensorflow i cannot find any functions for this. How can I get the score "0"? Can anyone help me out?

+4
source share
4 answers

There is no built-in calculation method in tensor flow. But you can do this using existing tools in this method:

def tf_count(t, val):
    elements_equal_to_value = tf.equal(t, val)
    as_ints = tf.cast(elements_equal_to_value, tf.int32)
    count = tf.reduce_sum(as_ints)
    return count
+6
source

To count only a specific element, you can create a Boolean mask, convert it to intand sum it:

import tensorflow as tf

X = tf.constant([6, 3, 3, 3, 0, 1, 3, 6, 7])
res = tf.reduce_sum(tf.cast(tf.equal(X, 3), tf.int32))
with tf.Session() as sess:
    print sess.run(res)

/, tf.unique_with_counts;

import tensorflow as tf

X = tf.constant([6, 3, 3, 3, 0, 1, 3, 6, 7])
y, idx, cnts = tf.unique_with_counts(X)
with tf.Session() as sess:
    a, _, b = sess.run([y, idx, cnts])
    print a
    print b
+4

Slater . , one_hot reduce_sum, python. , , word_tensor.

def build_vocab(word_tensor, vocab_size): 
  unique, idx = tf.unique(word_tensor)
  counts_one_hot = tf.one_hot(
      idx, 
      tf.shape(unique)[0],
      dtype=tf.int32
  )
  counts = tf.reduce_sum(counts_one_hot, 0)
  _, indices = tf.nn.top_k(counts, k=vocab_size)
  return tf.gather(unique, indices)

EDIT: , one_hot TF. , ( ) counts - :

counts = tf.foldl(
  lambda counts, item: counts + tf.one_hot(
      item, tf.shape(unique)[0], dtype=tf.int32),
  idx,
  initializer=tf.zeros_like(unique, dtype=tf.int32),
  back_prop=False
)
+1

n t, tf.unsorted_segment_sum :

count_all = tf.unsorted_segment_sum(tf.ones_like(t), t, n)

count_all .

. count_all[0] , 0 t:

t = tf.placeholder(tf.int32)
count_all = tf.unsorted_segment_sum(tf.ones_like(t), t, 3)
sess.run(count_all[0], {t: [1,2,0,0,0,0]})
# returns 4
sess.run(count_all, {t: [1,2,0,0,0,0]})
# returns array([4, 1, 1], dtype=int32)

, , . , Eli Bixby, one_hot . - tf.map_fn :

def count_all_fnc(e):
    return tf.unsorted_segment_sum(tf.ones_like(e), e, n)
count_all = tf.map_fn(count_all_fnc, t)

.

n = 3
t = tf.placeholder(tf.int32)
def count_all_fnc(e):
    return tf.unsorted_segment_sum(tf.ones_like(e), e, n)
count_all = tf.map_fn(count_all_fnc, t)
sess.run(count_all, {t:[[1, 0, 0, 2], [1, 2, 0, 0], [0, 0, 0, 0], [1, 1, 1, 2]]})

array([[2, 1, 1],
       [2, 1, 1],
       [4, 0, 0],
       [0, 3, 1]], dtype=int32)

, ( 10 ) , , , . n*|t|, .

one_hot_t = tf.one_hot(t, n)
count_all = tf.reduce_sum(one_hot_t, axis=1)
+1

All Articles