Multiply all elements of PyTorch tensor

Viewed 13655

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?

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])

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

Related