Whole-tensor totals
Aggregate every value in a tensor into one scalar-like tensor.
TensorFlow · Function
Computes sums across selected tensor dimensions. By default it reduces all dimensions and returns a one-element tensor; keepdims preserves reduced dimensions as size-one axes.
tf.reduce_sum adds tensor elements over selected dimensions. With no axis it produces a one-element tensor; with an axis it removes those dimensions unless keepdims=True, which leaves them as size-one dimensions.
tf.math.reduce_sum(input_tensor, axis=None, keepdims=False, name=None)| Name | Type | Description |
|---|---|---|
input_tensor | Tensor | Tensor to reduce; it should have a numeric type. |
axis | int, list of int, or None | Dimensions to reduce. None reduces all dimensions; values must be in the range [-rank(input_tensor), rank(input_tensor)]. |
keepdims | bool | If true, retains reduced dimensions with length 1. |
name | string or None | Optional name for the operation. |
The reduced tensor, with the same dtype as input_tensor.
import tensorflow as tf
x = tf.constant([[1, 2, 3], [4, 5, 6]])
print(tf.reduce_sum(x).numpy())
print(tf.reduce_sum(x, axis=0).numpy())
print(tf.reduce_sum(x, axis=1, keepdims=True).numpy())Creates a numeric matrix, sums every element, then reduces selected axes with and without retaining dimensions.
Aggregate every value in a tensor into one scalar-like tensor.
Compute column or row totals by selecting a particular dimension.
Keep output rank compatible with broadcasting or later shape-sensitive operations.
It computes the sum across the dimensions named by axis. If axis is None, all dimensions are reduced and the result contains one element.
Follow-up: How would you preserve rank? Set keepdims=True, which retains every reduced dimension with length one.
keepdims controls the shape after reduction. When false, reduced dimensions are removed; when true, they remain with length one.
Follow-up: For a rank-two tensor reduced over axis 1, what shapes result? Without keepdims the result is rank one; with it, the second dimension is size one.
The input must have a numeric type, and the returned tensor has the same dtype as input_tensor. The operation is the reduction form of elementwise tf.math.add.
Follow-up: Why can this differ from NumPy? NumPy may upcast uint8 and int32 to int64, whereas TensorFlow returns the input dtype.
tf.math.reduce_sumtf.math.addtf.reduce_meantf.reduce_prodtf.sparse.reduce_sum