+3 votes
in Programming Languages by (28.5k points)
I want to concatenate two tensors along rows/columns. Which function should I use?

1 Answer

+2 votes
by (48.9k points)
edited by

 torch.cat() function concatenates tensors in the given dimension. You can use two or more tensors in this function to concatenate them.

 torch.cat(tensors, dim=0, *, out=None) → Tensor

You can also use hstack() for horizontal stacking and vstack() for vertical stacking of tensors.

Here are some examples:

1. Concatenating 1d tensors

>>> import torch
>>> a=torch.randn(3)
>>> b=torch.randn(3)
>>> a
tensor([ 0.4886,  0.1983, -1.8426])
>>> b
tensor([-0.5119,  0.6101,  0.9693])
>>> torch.cat((a,b))
tensor([ 0.4886,  0.1983, -1.8426, -0.5119,  0.6101,  0.9693])

2. Concatenating 2d tensors

>>> a=torch.randn(2,3)
>>> a
tensor([[-0.1045,  0.5538, -1.8206],
        [-0.6275,  1.6419,  0.3089]])
>>> b=torch.randn(2,3)
>>> b
tensor([[ 0.4254, -0.1717, -0.2772],
        [-0.1911, -0.9333, -1.3382]])
>>> torch.cat((a,b),1)    # horizontal concatenation
tensor([[-0.1045,  0.5538, -1.8206,  0.4254, -0.1717, -0.2772],
        [-0.6275,  1.6419,  0.3089, -0.1911, -0.9333, -1.3382]])

>>> torch.hstack((a,b))
tensor([[-0.1045,  0.5538, -1.8206,  0.4254, -0.1717, -0.2772],
        [-0.6275,  1.6419,  0.3089, -0.1911, -0.9333, -1.3382]])
 

>>> torch.cat((a,b),0)    # vertical concatenation
tensor([[-0.1045,  0.5538, -1.8206],
        [-0.6275,  1.6419,  0.3089],
        [ 0.4254, -0.1717, -0.2772],
        [-0.1911, -0.9333, -1.3382]])

>>> torch.vstack((a,b))
tensor([[-0.1045,  0.5538, -1.8206],
        [-0.6275,  1.6419,  0.3089],
        [ 0.4254, -0.1717, -0.2772],
        [-0.1911, -0.9333, -1.3382]])


...