mygrad.sum#
- mygrad.sum(x: ArrayLike, axis: None | int | Tuple[int, ...] = None, keepdims: bool = False, *, constant: bool | None = None) Tensor [source]#
Sum of tensor elements over a given axis.
- Parameters:
- xArrayLike
- axisOptional[int, Tuple[ints, …]]
Axis or axes along which a sum is performed. The default, axis=None, will sum all of the elements of the input tensor. If axis is negative it counts from the last to the first axis. If axis is a tuple of ints, a sum is performed on all of the axes specified in the tuple instead of a single axis or all the axes as before.
- keepdimsbool, optional
If this is set to True, the axes which are reduced are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input tensor.
- constantOptional[bool]
If
True
, this tensor is treated as a constant, and thus does not facilitate back propagation (i.e.constant.grad
will always returnNone
).Defaults to
False
for float-type data. Defaults toTrue
for integer-type data.Integer-type tensors must be constant.
- Returns:
- sum_along_axismygrad.Tensor
A Tensor with the same shape as self, with the specified axis/axes removed. If self is a 0-d tensor, or if axis is None, a 0-dim Tensor is returned.
Notes
Arithmetic is modular when using integer types, and no error is raised on overflow.
The sum of an empty tensor is the neutral element 0:
>>> mygrad.sum([]) Tensor(0.0)
Examples
>>> import mygrad as mg >>> import numpy as np >>> mg.sum([0.5, 1.5]) Tensor(2.0) >>> mg.sum([0.5, 0.7, 0.2, 1.5], dtype=np.int32) Tensor(1) >>> mg.sum([[0, 1], [0, 5]]) Tensor(6) >>> mg.sum([[0, 1], [0, 5]], axis=0) Tensor([0, 6]) >>> mg.sum([[0, 1], [0, 5]], axis=1) Tensor([1, 5])
If the accumulator is too small, overflow occurs:
>>> mg.ones(128, dtype=mg.int8).sum(dtype=np.int8) Tensor(-128)