📅  最后修改于: 2023-12-03 15:20:33.886000             🧑  作者: Mango
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.
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.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.
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).
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.
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.