Search code examples
pythonpytorchtensorbroadcast

PyTorch Tensor broadcasting


I'm trying to figure out how to do the following broadcast:

I have two tensors, of sizes (n1,N) and (n2,N)

What I want to do is to multiply each row of the first tensor, with each row of the second tensor, and then sum each of there multiplied row result, so that my final tensor should be of the form (n1,n2).

I tried this:

x1*torch.reshape(x2,(x2.size(dim=0),x2.size(dim=1),1))

But obviously this doesn't work.. Can't figure out how to do this


Solution

  • What you describe seems to be effectively the same as performing a matrix multiplication between the first tensor and the transpose of the second tensor. This can be done as:

    torch.matmul(x1, x2.T)