Mikus
Mikus

Reputation: 322

Equivalent of np.resize in TensorFlow

I have a 1D array x and want to reshape it to the requested shape in the same way that np.resize is doing, i.e. if there is too many elements in x they are dropped, if it is too few, they are circularly added, e.g.

x = np.array([1, 2, 3, 4, 5, 6])
y = np.resize(x, shape=(2, 2))
assert y == np.array([[1, 2], [3, 4]])
z = np.resize(x, shape=(3, 3))
assert z == np.array([[1, 2, 3], [4, 5, 6], [1, 2, 3]])

I'm wonder how to do it using only tensor operators from TensorFlow.

Upvotes: 0

Views: 188

Answers (2)

Mikus
Mikus

Reputation: 322

Thanks to Poe Dator's hints I ended up with the following solution:

def tf_resize(t, shape):
    """
    Args:
      t: a `Tensor`
      shape: requested output shape
    """
    input_size = tf.size(t)
    output_size = tf.reduce_prod(shape)
    t_flatten = tf.reshape(t, [input_size])
    result = tf.tile(t_flatten, [output_size // input_size + 1])
    return tf.reshape(result[0:output_size], shape=shape)

Upvotes: 1

Poe Dator
Poe Dator

Reputation: 4913

I am not sure that this is doable in single operation in TF, but one can write a function using crops or tf.tile and then reshaping the result.

Upvotes: 1

Related Questions