Without an axis argument, reduce_sum() collapses the entire tensor down to a single scalar sum of every element. Specifying an axis instead sums only along that dimension, collapsing it away while preserving the others — axis=0 sums down each column, collapsing rows, while axis=1 sums across each row, collapsing columns, the same axis convention used throughout NumPy and TensorFlow. The reduce prefix on this and similar functions, reduce_mean, reduce_max, etc., specifically signals that the operation collapses, or reduces, one or more dimensions of the input.
1Understanding tf.reduce_sum()
Without an axis argument, reduce_sum() collapses the entire tensor down to a single scalar sum of every element. Specifying an axis instead sums only along that dimension, collapsing it away while preserving the others — axis=0 sums down each column, collapsing rows, while axis=1 sums across each row, collapsing columns, the same axis convention used throughout NumPy and TensorFlow. The reduce prefix on this and similar functions, reduce_mean, reduce_max, etc., specifically signals that the operation collapses, or reduces, one or more dimensions of the input.
Remember the axis argument names the dimension being collapsed away, not the one that remains in the result — axis=0 on a 2D tensor reduces rows down to a single value per column, which trips people up expecting the opposite.
import tensorflow as tf
x = tf.constant([[1, 2, 3], [4, 5, 6]])
print(tf.reduce_sum(x))2Practical Example
Here is a real-world application of tf.reduce_sum() showing how it is used in production TensorFlow code.
import tensorflow as tf
x = tf.constant([[1, 2, 3], [4, 5, 6]])
print(tf.reduce_sum(x, axis=1))3Best Practices
Follow these guidelines when working with tf.reduce_sum():
1. Double-check whether axis=0 or axis=1 matches your intent by testing on a small example, since the reduced-vs-remaining dimension is easy to get backwards
2. Use reduce_sum() over a mask tensor, 0s and 1s, as a common technique to count how many elements satisfy a condition
3. Pass keepdims=True when you need the reduced dimension to remain in the output shape as a size-1 axis, instead of being removed entirely, which matters for broadcasting the result back against the original tensor
Tip: Remember the axis argument names the dimension being collapsed away, not the one that remains in the result — axis=0 on a 2D tensor reduces rows down to a single value per column, which trips people up expecting the opposite.
import tensorflow as tf
x = tf.constant([[1, 2, 3], [4, 5, 6]])
print(tf.reduce_sum(x))