TensorFlow: numpy.repeat() alternative

TensorFlow: numpy.repeat() alternative

Asked on December 26, 2018 in Tensorflow.
Add Comment


  • 2 Answer(s)

          In Tensorflow, np.repeat() alternative is achieved by using a mixture of  tf.tile() and tf.reshape():

    idx = tf.range(len(yp))
    idx = tf.reshape(idx, [-1, 1])    # Convert to a len(yp) x 1 matrix.
    idx = tf.tile(idx, [1, len(yp)])  # Create multiple columns.
    idx = tf.reshape(idx, [-1])       # Convert back to a vector.
    

          By using tf.tile() just compute jdx :

    jdx = tf.range(len(yp))
    jdx = tf.tile(jdx, [len(yp)])
    

          Use tf.gather() to extract non-contiguous slices from the yp tensor, for indexing:

    s = tf.gather(yp, idx) - tf.gather(yp, jdx)
    
    Answered on December 26, 2018.
    Add Comment

    Let’s do it by using  tf.tiletf.reshapetf.squeeze.

    Example:

    import numpy as np
    import tensorflow as tf
     
    x = [[1,2],[3,4]]
    print np.repeat(3, 4)
    print np.repeat(x, 2)
    print np.repeat(x, 3, axis=1)
     
    x = tf.constant([[1,2],[3,4]])
    with tf.Session() as sess:
        print sess.run(tf.tile([3], [4]))
        print sess.run(tf.squeeze(tf.reshape(tf.tile(tf.reshape(x, (-1, 1)), (1, 2)), (1, -1))))
        print sess.run(tf.reshape(tf.tile(tf.reshape(x, (-1, 1)), (1, 3)), (2, -1)))
    
    Answered on December 26, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.