Multiplication of tensors of different dimensions

I want to multiply different scalar values for each image.

For example, the image have [4,3,10,10] shape. (batch size, channel, w,h).

0.1 * image works fine but,

[0.1, 0.2, 0.3, 0.4] * image doesn’t work because the dimensions are different.

How can I multiply this ?

You can unsqueeze the additional dimensions to multiply the list entries with each sample in the batch:

x = torch.randn(4,3,10,10)
f = torch.tensor([0.1, 0.2, 0.3, 0.4])
res = f[:, None, None, None] * x
2 Likes

hello partick ,
is my tensor is below :slight_smile:

f = torch.zeros(1, 1, 3, dtype=torch.float)
f[:,:,0] = 255

and i want to multiply with a above

x = torch.randn(4,3,10,10)
res = x*f
what would be the correct way to do the same?

The current shapes are incompatible, since dim2 in f won’t be broadcasted to x.
Since you are using 3 elements in f, you could align dim2 to dim1 in x which would work:

f = torch.zeros(1, 1, 3, dtype=torch.float)
f[:,:,0] = 255
f = f.squeeze(1).unsqueeze(2).unsqueeze(3)

x = torch.randn(4,3,10,10)
res = x*f

Hello patrick.

Thanks

What if if we have mutiple elements in f and we want to mutuply each time with elements of x

In this case if x is batch size of 4

And f is of2

So it should be 8 elements in total .

I don’t quite understand the use case. If you want to apply an elementwise multiplication you would either have to make sure the number of elements match in both tensors or are broadcastable.