Sum of tensor elements over given axis Args: t: Singa.tensor The array_like tensor to be sumed axis: None or int or tuple of ints, optional Axis or axes along which a sum is performed. The default, axis=None, will sum all of the elements of th
(t, axis=None, out=None)
| 1007 | |
| 1008 | |
| 1009 | def sum(t, axis=None, out=None): |
| 1010 | '''Sum of tensor elements over given axis |
| 1011 | |
| 1012 | Args: |
| 1013 | t: Singa.tensor |
| 1014 | The array_like tensor to be sumed |
| 1015 | axis: None or int or tuple of ints, optional |
| 1016 | Axis or axes along which a sum is performed. |
| 1017 | The default, axis=None, will sum all of the elements of the input array. |
| 1018 | If axis is negative it counts from the last to the first axis. |
| 1019 | If axis is a tuple of ints, a sum is performed on all of the axes specified |
| 1020 | in the tuple instead of a single axis or all the axes as before. |
| 1021 | out:Singa.tensor optional |
| 1022 | Alternative output array in which to place the result. |
| 1023 | It must have the same shape as the expected output, |
| 1024 | but the type of the output values will be cast if necessary. |
| 1025 | |
| 1026 | Returns: |
| 1027 | A tensor with the same shape as t, with the specified axis removed. |
| 1028 | If a is a 0-d array, or if axis is None, a scalar is returned. |
| 1029 | If an output array is specified, a reference to out is returned |
| 1030 | ''' |
| 1031 | |
| 1032 | t_shape = t.shape |
| 1033 | t_ndim = t.ndim() |
| 1034 | |
| 1035 | if axis is None: |
| 1036 | one = Tensor(t.shape, t.device) |
| 1037 | one.set_value(1.0) |
| 1038 | ret = tensordot(t, one, t_ndim) |
| 1039 | |
| 1040 | if isinstance(axis, int): |
| 1041 | if axis < 0: |
| 1042 | axis += t_ndim |
| 1043 | |
| 1044 | axis_shape = t_shape[axis] |
| 1045 | axis_shape = int(axis_shape) |
| 1046 | one = Tensor(shape=(axis_shape,), device=t.device) |
| 1047 | one.set_value(1.0) |
| 1048 | ret = tensordot(t, one, axes=([axis], [0])) |
| 1049 | |
| 1050 | if isinstance(axis, tuple): |
| 1051 | l_axis = list(axis) |
| 1052 | axis_shape = [t_shape[x] for x in axis] |
| 1053 | axisshape = tuple(axis_shape) |
| 1054 | one = Tensor(axisshape, t.device) |
| 1055 | one.set_value(1.0) |
| 1056 | one_axis = [x for x in range(one.ndim())] |
| 1057 | ret = tensordot(t, one, (l_axis, one_axis)) |
| 1058 | |
| 1059 | if out is not None: |
| 1060 | if out.shape != ret.shape: |
| 1061 | raise ValueError('dimensions do not match') |
| 1062 | out[:] = ret |
| 1063 | return out |
| 1064 | else: |
| 1065 | return ret |
| 1066 |
no test coverage detected