qml.math.sum

sum(tensor, axis=None, keepdims=False)

TensorBox: Returns the sum of the tensor elements across the specified dimensions.

Parameters
  • tensor (tensor_like) – input tensor

  • axis (int or tuple[int]) – The axis or axes along which to perform the sum. If not specified, all elements of the tensor across all dimensions will be summed, returning a tensor.

  • keepdims (bool) – If True, retains all summed dimensions.

Returns

The tensor with specified dimensions summed over. Note that if all elements are summed, then a 0-dimensional tensor is returned, rather than a Python scalar.

Return type

tensor_like

Example

Summing over all dimensions:

>>> x = tf.Variable([[1., 2.], [3., 4.]])
>>> sum(x)
<tf.Tensor: shape=(), dtype=float32, numpy=10.0>

Summing over specified dimensions:

>>> x = np.array([[[1, 1], [5, 3]], [[1, 4], [-6, -1]]])
>>> x.shape
(2, 2, 2)
>>> sum(x, axis=(0, 2))
tensor([7, 1], requires_grad=True)
>>> sum(x, axis=(0, 2), keepdims=True)
tensor([[[7],
         [1]]], requires_grad=True)