Reputation: 1118
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.
Upvotes: 7
Views: 5667
Reputation: 101
The equivalent function for pytorch expand
is tensorflow tf.broadcast_to
Docs: https://www.tensorflow.org/api_docs/python/tf/broadcast_to
Upvotes: 10
Reputation: 18723
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
Upvotes: 0