When I have a tensor m
of shape [12, 10]
and a vector s
of scalars with shape [12]
, how can I multiply each row of m
with the corresponding scalar in s
?
To perform element-wise subtraction on tensors, we can use the torch. sub() method of PyTorch. The corresponding elements of the tensors are subtracted. We can subtract a scalar or tensor from another tensor.
. item() ensures that you append only the float values to the list rather the tensor itself. You are basically converting a single element tensor value to a python number. This should not affect the performance in any way.
You need to add a corresponding singleton dimension:
m * s[:, None]
s[:, None]
has size of (12, 1)
when multiplying a (12, 10)
tensor by a (12, 1)
tensor pytoch knows to broadcast s
along the second singleton dimension and perform the "element-wise" product correctly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With