What is the function in TensorFlow that is equivalent to expand() in PyTorch?


Let’s say I have a 2 x 3 matrix and I want to create a 6 x 2 x 3 matrix where each element in the first dimension is the original 2 x 3 matrix.

In PyTorch, I can do this:

import torch
from torch.autograd import Variable
import numpy as np

x = np.array([[1, 2, 3], [4, 5, 6]])
x = Variable(torch.from_numpy(x))

# y is the desired result
y = x.unsqueeze(0).expand(6, 2, 3)

What is the equivalent way to do this in TensorFlow? I know unsqueeze() is equivalent to tf.expand_dims() but I don’t TensorFlow has anything equivalent to expand(). I’m thinking of using tf.concat on a list of the 1 x 2 x 3 tensors but am not sure if this is the best way to do it.


Tensorflow automatically broadcasts, so in general you don’t need to do any of this. Suppose you have a y' of shape 6x2x3 and your x is of shape 2x3, then you can already do y'*x or y'+x will already behave as if you had expanded it. But if for some other reason you really need to do it, then the command in tensorflow is tile:

y = tf.tile(tf.reshape(x, (1,2,3)), multiples=(6,1,1))

Docs: https://www.tensorflow.org/api_docs/python/tf/tile

Answered By – patapouf_ai

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published