I have tensor with shape: (14000, 10, 2)
and another tensor with shape: (14000, 2)
I want to merge the 2 tensors and get new tensor of shape:
(14000, 10, 3)
for example:
import torch
import numpy as np
x = torch.rand([14000, 10, 2])
y = np.random.randint(2, size=14000)
y = np.repeat(y, 10)
y = torch.Tensor(y)
y = y.view(14000, 10)
How can I do it ?
>Solution :
You can do that by first, expand the second tensor so that the two tensors have the same number of dimensions. Then, use torch.cat to concatenate the tensors:
import torch
import numpy as np
x = torch.rand([14000, 10, 2])
y = np.random.randint(2, size=14000)
y = np.repeat(y, 10)
y = torch.Tensor(y)
y = y.view(14000, 10)
print("x shape: "+ str(x.shape))
print("y shape: "+ str(y.shape))
y = y.unsqueeze(-1)
print("y shape after adding a dimension to its shape: "+ str(y.shape))
x_y = torch.cat((x,y),-1)
print("x and y concatenated: "+ str(x_y.shape))
output:
x shape: torch.Size([14000, 10, 2])
y shape: torch.Size([14000, 10])
y shape after adding a dimension to its shape: torch.Size([14000, 10, 1])
x and y concatenated: torch.Size([14000, 10, 3])