Tensor stack or concatenate

Here is the question:
suppose:
tensor a is a 3x3 tensor
tensor b is a 4x3 tensor
tensor c is a 5x3 tensor

I want to build a tensor which contains all the unique row tensor of these three tensors
example:
a = [[1,2,3],[4,5,6],[7,8,9]]
b = [[1,3,7],[2,4,8],[3,7,9],[4,5,6]]
c = [[1,2,3],[2,4,8],[3,7,9],[3,5,6],[7,8,9]]

I expect the ouput is a 3xn tensor, which in this example should be:
[[1,2,3],[4,5,6],[7,8,9],[1,3,7],[2,4,8],[3,7,9],[3,5,6]]

Someone could help? Thank you in advance

you cannot solve that directly with stack or concatenate. That problem requires an analysis of tensor’s rows.
Besides you may require an ordering in the way this new tensor is created. Anyway you can solve that by adding rows to the new tensor and checking if the row already exist before adding it.

Thank you for your explanation, could you show me one example of adding rows to new tensor?

a = torch.Tensor([[1,2,3],[4,5,6],[7,8,9]])
b = torch.Tensor([[1,3,7],[2,4,8],[3,7,9],[4,5,6]])
c = torch.Tensor([[1,2,3],[2,4,8],[3,7,9],[3,5,6],[7,8,9]])
d = torch.cat((a,b,c))
torch.Tensor([list(item) for item in set(tuple(row) for row in d.numpy())])

tensor([[1., 3., 7.],
[3., 7., 9.],
[2., 4., 8.],
[7., 8., 9.],
[1., 2., 3.],
[3., 5., 6.],
[4., 5., 6.]])

This is not the best solution but it will do the trick
1 Like

It’s a little tricky.


import torch

a=torch.rand(3)

a
Out[3]: tensor([0.3544, 0.3355, 0.4885])

a.size()
Out[4]: torch.Size([3])

b=torch.rand(4,3)

b.size()
Out[6]: torch.Size([4, 3])

Here if you do torch.cat((b,a)) you will get an error because size of a is 3

c=torch.cat((b,a))
Traceback (most recent call last):

  File "<ipython-input-7-cc137009b380>", line 1, in <module>
    c=torch.cat((b,a))

RuntimeError: invalid argument 0: Tensors must have same number of dimensions: got 2 and 1 at /pytorch/aten/src/TH/generic/THTensorMath.cpp:3607

So you have to unsqueeze a to get a size 1,3
c=torch.cat((b,a.unsqueeze(0)))

@JuanFMontesinos all tensor dimension are same so there not gonna be problem m x 3

Thank you for your reply, your solution give my a hint, I find another solution:

a = torch.Tensor([[1,2,3],[4,5,6],[7,8,9]])
b = torch.Tensor([[1,3,7],[2,4,8],[3,7,9],[4,5,6]])
c = torch.Tensor([[1,2,3],[2,4,8],[3,7,9],[3,5,6],[7,8,9]])
d = torch.cat((a,b,c))
print(d.shape)
d_unique = torch.unique(d, dim=0)
print(d_unique.shape)
print(d_unique)

output:

torch.Size([12, 3])
torch.Size([7, 3])
tensor([[1., 2., 3.],
        [1., 3., 7.],
        [2., 4., 8.],
        [3., 5., 6.],
        [3., 7., 9.],
        [4., 5., 6.],
        [7., 8., 9.]])
1 Like

Hi, I think you midunderstood me, my tensor is the same size in dimention1.
so the torch.cat works

@Xiaoyu_Song smart solution

Here’s a one liner to do this:

torch.unique(torch.cat((a, b, c), dim=0), dim=0)

However, this will not preserve ordering.

1 Like