George
George

Reputation: 944

Downsample a Tensor

Let's assume we have a 3D Tensor of shape a = [batch_size, length, 1] and we want to discard every 5th sample from the length axis. The new indices for every batch element could be calculated as indices = tf.where(tf.range(a.shape[1]) % 5 != 0).

Could you please help me with an operation that obtains the shorter Tensor shape b = [batch_size, length2, 1], where length2 = 4/5 * length ? I assume this is attainable with tf.gather_nd, but I am having an issue with providing the indices in the right format. It does not simply work to tile the indices Tensor batch_size times and provide the resulting 2D tensor to tf.gather_nd taking the 3D tensor as parameters.

Thank you.

Upvotes: 1

Views: 2474

Answers (1)

javidcf
javidcf

Reputation: 59711

You can simply do the following:

import tensorflow as tf
# Example data
a = tf.reshape(tf.range(60), [5, 12, 1])
print(a.numpy()[:, :, 0])
# [[ 0  1  2  3  4  5  6  7  8  9 10 11]
#  [12 13 14 15 16 17 18 19 20 21 22 23]
#  [24 25 26 27 28 29 30 31 32 33 34 35]
#  [36 37 38 39 40 41 42 43 44 45 46 47]
#  [48 49 50 51 52 53 54 55 56 57 58 59]]
# Mask every one in five items
mask = tf.not_equal(tf.range(tf.shape(a)[1]) % 5, 0)
b = tf.boolean_mask(a, mask, axis=1)
# Show result
print(b.numpy()[:, :, 0])
# [[ 1  2  3  4  6  7  8  9 11]
#  [13 14 15 16 18 19 20 21 23]
#  [25 26 27 28 30 31 32 33 35]
#  [37 38 39 40 42 43 44 45 47]
#  [49 50 51 52 54 55 56 57 59]]

Upvotes: 1

Related Questions