Broadcasting the multiplication along multipe dimension

I have tensor a and b
a = torch.ones(3,2,2,2)
b = torch.Tensor([1,2,3])
I expect the result as:

tensor([[[[1., 1.],
          [1., 1.]],

         [[1., 1.],
          [1., 1.]]],


        [[[2., 2.],
          [2., 2.]],

         [[2., 2.],
          [2., 2.]]],


        [[[3., 3.],
          [3., 3.]],

         [[3., 3.],
          [3., 3.]]]])

Is there any easy way to do such computation?

This code should work:

a = torch.ones(3, 2, 2, 2)
b = torch.tensor([1, 2, 3], dtype=torch.float32)
a * b.view(-1, 1, 1, 1)
1 Like