Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to multiply a tensor row-wise by a vector in PyTorch?

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?

like image 903
Chris Avatar asked Dec 31 '18 13:12

Chris


People also ask

How do you subtract two tensors in PyTorch?

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.

What does item () do PyTorch?

. 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.


1 Answers

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.

like image 156
Shai Avatar answered Oct 03 '22 16:10

Shai