gpt4 book ai didi

python - Tensorflow numpy 重复

转载 作者:太空宇宙 更新时间:2023-11-03 14:43:22 25 4
gpt4 key购买 nike

我希望重复特定的数字不同的次数,如下所示:

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.tiletf.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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com