python - Tensorflow numpy 重复

标签 python numpy tensorflow

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

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/

相关文章:

python - 微软情感API多图像PYTHON 2.7

python - 如何在 Flask 中获取自定义 SELECT 查询?

python - 以统一的方式缩放值?

python-3.x - 将图像放在另一个图像之上的更有效方法 - OpenCV Python3

python - 如何将具有 numpy 数组值的 Pandas 系列转换为数据框

ubuntu - TensorFlow Android 示例 : Cannot find WORKSPACE file

tensorflow - model.fit_generator() 因 use_multiprocessing=True 失败

python - 如何优化推理一个简单的、保存的 TensorFlow 1.0.1 图?

python : Cannot retrieve shape of numpy matrix in dict

python - Keras 模型不学习