megengine.functional.prod

prod(inp, axis=None, keepdims=False)[source]

Calculates the product of tensor elements over a given axis (or axes).

Parameters
  • inp (Tensor) – input tensor. Should have a numeric data type.

  • axis (Union[int, Sequence[int], None]) – axis or axes along which products must be computed. By default, the product must be computed over the entire tensor. If a sequence of integers, products must be computed over multiple axes.

  • keepdims – if True, the reduced axes (dimensions) must be included in the result as singleton dimensions, and, accordingly, the result must be compatible with the input tensor (see Broadcasting mechanism and rules). Otherwise, if False, the reduced axes (dimensions) must not be included in the result.

Return type

Tensor

Returns

if the product was computed over the entire tensor, a zero-dimensional tensor containing the products; otherwise, a non-zero-dimensional tensor containing the products. The returned tensor must have a data type determined by Type promotion rules.

Special Cases

Let N equal the number of elements over which to compute the product.

  • If N is 0, the product is 1 (i.e., the empty product).

  • If \(x_i\) is NaN, the product is NaN (i.e., NaN values propagate).

Warning

Arithmetic is modular when using integer types, and no error is raised on overflow:

>>> x = Tensor([536870910, 536870910, 536870910, 536870910])
>>> F.prod(x)
Tensor(16, dtype=int32, device=xpux:0)

Examples

The product of an empty tensor is the neutral element 1:

>>> F.prod(Tensor([]))
Tensor(1.0, device=xpux:0)

Normal case:

>>> F.prod(Tensor([1, 2, 3]))
Tensor(6, dtype=int32, device=xpux:0)
>>> F.prod(Tensor([0.5, 1.5]))
Tensor(0.75, device=xpux:0)

Along an axis:

>>> F.prod(Tensor([[1, 2, 3], [4, 5, 6]]), axis=0)
Tensor([ 4 10 18], dtype=int32, device=xpux:0)
>>> F.prod(Tensor([[1, 2, 3], [4, 5, 6]]), axis=1)
Tensor([  6 120], dtype=int32, device=xpux:0)