我希望重复特定的数字不同的次数,如下所示:
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])
(0 重复 3 次、1、4 次等)。
这个答案 ( https://stackoverflow.com/a/35367161/2530674 ) 似乎表明我可以结合使用 tf.tile
和 tf.reshape
来获得相同的效果。但是,我相信只有在重复次数恒定的情况下才会出现这种情况。
如何在 Tensorflow 中获得相同的效果?
edit1:不幸的是没有tf.repeat
。
最佳答案
这是一种“蛮力”解决问题的方法,简单地将每个值平铺到最大重复次数,然后选择正确的元素:
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])))
输出:
[0 0 0 1 1 1 1 2 2 2 2 2]
关于python - Tensorflow numpy 重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51490806/