📜  tensorflow reduce_sum - Python (1)

📅  最后修改于: 2023-12-03 15:20:33.886000             🧑  作者: Mango

Tensorflow Reduce Sum - Python

TensorFlow is a popular open source library used for machine learning and deep learning. One of its most commonly used functions is tf.reduce_sum(). This function is used to compute the sum of elements across different dimensions of the input tensor.

Syntax
reduce_sum(
    input_tensor,
    axis=None,
    keepdims=False,
    name=None
)
  • input_tensor: Tensor to reduce. Input to be summed. Dimensionality can be of variable size.
  • axis: The dimensions to reduce. If None (the default), reduces all dimensions. Must be in the range [-rank(input_tensor), rank(input_tensor)).
  • keepdims: If true, retains reduced dimensions with length 1. Default to False.
  • name: The operation name.
Examples
1. Computing the sum over all dimensions
import tensorflow as tf
import numpy as np

x = tf.constant(np.array([[1, 2], [3, 4]]))

result = tf.reduce_sum(x)

print(result)
# Output: tf.Tensor(10, shape=(), dtype=int64)

In this example, we create a 2x2 tensor x and use tf.reduce_sum() to compute the sum over all dimensions.

2. Computing the sum over a specific dimension
import tensorflow as tf
import numpy as np

x = tf.constant(np.array([[1, 2], [3, 4]]))

result = tf.reduce_sum(x, axis=0)

print(result)
# Output: tf.Tensor([4 6], shape=(2,), dtype=int64)

In this example, we create a 2x2 tensor x and use tf.reduce_sum() to compute the sum over the first dimension (columns).

3. Keeping the reduced dimensions
import tensorflow as tf
import numpy as np

x = tf.constant(np.array([[1, 2], [3, 4]]))

result = tf.reduce_sum(x, axis=0, keepdims=True)

print(result)
# Output: tf.Tensor([[4 6]], shape=(1, 2), dtype=int64)

In this example, we create a 2x2 tensor x and use tf.reduce_sum() to compute the sum over the first dimension (columns) while keeping the reduced dimension.

Conclusion

In this article, we have discussed the tf.reduce_sum() function in TensorFlow. It is an important function for manipulating tensors in TensorFlow and is often used in deep learning and machine learning models.