Dong Le
Dong Le

Reputation: 179

How to concatenate a 0-D tensor into a 3-D tensor in PyTorch?

I have the following tensor:

X = torch.randn(30,1,2)  # [batch_size, dim_1, dim_2]

t = torch.Tensor([0]) 

I am trying to concatenate the t tensor into X tensor that results [30,1,3] tensor. However, I tried couple of methods even with torch.stack. I still have not figured out how to do this properly. I tried both and they gave errors.

result = torch.cat((X,t), dim = -1) # first try
result = torch.stack([X,t], dim = -1) # second try. 

Is there a way I can concatenate these tensors?

Upvotes: 0

Views: 1490

Answers (1)

Caiof
Caiof

Reputation: 89

You can't concatenate the two described tensors, the shape of tensor X is [30, 1 , 2], which means it has 30 positions in the first dimension, 1 position in the second dimension, and 2 positions in the last dimension, totalling 30*1*2 = 60 elements. A tensor of shape [30,1,3] has 90 elements, meaning you need to add 30 elements to get the desired result.

You can do this by changing the code to:

>>> X = torch.randn(30,1,2)
>>> t = torch.zeros(30,1,1)
>>> r = torch.cat((X,t), dim=-1)
>>> r.shape
torch.Size([30, 1, 3])

Upvotes: 2

Related Questions