0

I would like to get the occurrences of numbers of a 3 dimension tensor (displayed in a tensor at the corresponding indexes, like tf.math.bincount does).

For a 2d tensor, you can simply do this:

T = tf.round(25*tf.random.uniform((5,8)))
bincounts = tf.cast(tf.math.bincount(T, axis=-1),tf.float32)

But on a 3d tensor, the only way I found is looping over the third dimension, like this:

third_dim  = 10
T = tf.round(25*tf.random.uniform((5,8,third_dim)))
bincounts = []
for i in range(third_dim):
    bincounts.append(tf.math.bincount(T[:,:,i], axis=-1))
bincounts = tf.stack(bincounts,-1)

Does anyone know if there is a way to apply such a function directly on all the dimensions?

1 Answers1

0

I found a way:

Apply bincounts on the reshaped tensor, and then reshape back to the shape you want:

third_dim  = 10
T = tf.round(25*tf.random.uniform((5,8,third_dim)))
T2 = tf.reshape(T,(5*8,third_dim))
bincounts2 = tf.math.bincount(T2, axis=-1)
bincounts = tf.reshape(bincounts2, [5,8,bincounts2.shape[-1]])