Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiply all elements of PyTorch tensor

Tags:

python

pytorch

I wanted to do something like this question in PyTorch i.e. multiply all elements with each other keeping a certain axis constant. Does PyTorch has any pre-defined function for this?

like image 563
DuttaA Avatar asked Jun 14 '19 06:06

DuttaA


People also ask

How do you multiply PyTorch tensors?

mul() method is used to perform element-wise multiplication on tensors in PyTorch. It multiplies the corresponding elements of the tensors. We can multiply two or more tensors. We can also multiply scalar and tensors.

What is Torch prod?

torch. prod (input, dim, keepdim=False, *, dtype=None) → Tensor. Returns the product of each row of the input tensor in the given dimension dim . If keepdim is True , the output tensor is of the same size as input except in the dimension dim where it is of size 1.

What is BMM PyTorch?

PyTorch bmm is used for matrix multiplication in batches where the scenario involves that the matrices to be multiplied have the size of 3 dimensions that is x, y, and z and the dimension of the first dimension for matrices to be multiplied should be the same.

How to use tensor for matrix multiplication in PyTorch?

The Tensor can hold only elements of the same data type. The methods in PyTorch expect the inputs to be a Tensor and the ones available with PyTorch and Tensor for matrix multiplication are: torch.mm (). torch.matmul (). @ operator.

How to multiply a matrix by a scalar?

multiply a matrix by a scalar ( or tensor with scalars ) you can use torch.multiply The tensordocs are very extensive on that matter... you should take a look

What is the output dimension of tensor_1 in matrices?

Thus, the output will also be of the same dimension. Here tensor_1 is of 2×2 dimension, tensor_2 is of 2×3 dimension. So the output will be of 2×3. This method allows the computation of multiplication of two vector matrices (single-dimensional matrices), 2D matrices and mixed ones also.


2 Answers

Yes. torch.prod. Use the dim parameter to tell which along which axis you want the product to be computed.

x = torch.randn((2, 2))
print(x)
print(torch.prod(x, 0)) # product along 0th axis

This prints

tensor([[-0.3661, 1.0693],
           [0.5144, 1.3489]])
tensor([-0.1883, 1.4424])
like image 114
Priyatham Avatar answered Oct 23 '22 07:10

Priyatham


Assuming you want to do:
matrix multiplication, you can use torch.matmul
multiply a matrix by a scalar ( or tensor with scalars ) you can use torch.multiply

The tensor docs are very extensive on that matter... you should take a look

like image 1
Paulo Queiroz Avatar answered Oct 23 '22 06:10

Paulo Queiroz