Arithmetics along batches

Hello everyone! I have 2 tensors: first (tensor A) is (b, c, h, w) shape and second (tensor B) is (b) shape. I want to make substraction, A - B, so from every tensor (c, h, w) were substracted corresponding number. But I got RuntimeError: The size of tensor a (w) must match the size of tensor b (b) at non-singleton dimension 3

I think if you add additional dimensions for tensor B then you could utilize broadcasting and obtain the results you desire. For example:

x = torch.ones((2, 3, 64, 64))
y = torch.ones((2))

x - y # This will bring an error
x - y.view(-1, 1, 1, 1) # This will work

Hi! Thank you for respond
However y.expand(2, 1, 1, 1) gives me an error RuntimeError: The expanded size of the tensor (1) must match the existing size (2) at non-singleton dimension 3. Target sizes: [2, 1, 1, 1]. Tensor sizes: [2]
I’ve made it the next way:
`
x = torch.ones((2, 3, 64, 64))
y = torch.ones((2))

x.view(2, -1) - y[:, None]
`
It works, but I’m not sure, it is the most optimal way

Sorry, made a mistake when I tested it, I edited my previous answer and used view instead. Does this work for you now?

Yeah! Now It’s working. Thank you