Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to merge (cat) 2 tensors ((14000, 10, 2) and (14000, 10))?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading