Tensorflow Numpy Repeat
I wish to repeat a particular number different number of times as shown below: x = np.array([0,1,2]) np.repeat(x,[3,4,5]) >>> array([0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2])
Solution 1:
This is a kind of "brute force" solution to the problem, simply tiling every value as many times as the largest number of repetitions and then picking the right elements:
import tensorflow as tf
# Repeats across the first dimension
def tf_repeat(arr, repeats):
arr = tf.expand_dims(arr, 1)
max_repeats = tf.reduce_max(repeats)
tile_repeats = tf.concat(
[[1], [max_repeats], tf.ones([tf.rank(arr) - 2], dtype=tf.int32)], axis=0)
arr_tiled = tf.tile(arr, tile_repeats)
mask = tf.less(tf.range(max_repeats), tf.expand_dims(repeats, 1))
result = tf.boolean_mask(arr_tiled, mask)
return result
with tf.Graph().as_default(), tf.Session() as sess:
print(sess.run(tf_repeat([0, 1, 2], [3, 4, 5])))
Output:
[0 0 0 1 1 1 1 2 2 2 2 2]
Post a Comment for "Tensorflow Numpy Repeat"