Search code examples
pythonpytorchconcatenationtensor

How to combine two tensors of different shapes in pytorch?


I am currently doing this:

repeat_vals = [x.shape[0] // pfinal.shape[0]] + [-1] * (len(pfinal.shape) - 1)
            
x = torch.cat((x, pfinal.expand(*repeat_vals)), dim=-1)

the shape of x is[91,6] and of final is[6,6] but I am getting this error:

RuntimeError: The expanded size of the tensor (15) must match the existing size (6) at non-singleton dimension 0.  Target sizes: [15, -1].  Tensor sizes: [6, 6]

Solution

  • You cannot expand non-singleton values. Furthermore, you cannot enforce len(x) to be a multiple of len(pfinal), so instead, depending on your needs, you could more over the desired number and then slice away the excess. Something that you can modify to fit your needs:

    >>> reps = len(x) // len(pfinal) + 1
    >>> res = pfinal.repeat(reps, *[1]*(pfinal.ndim - 1))[:len(x)]