1. 求和 tf.reduce_sum
在 TensorFlow2 中对序列求和,使用的是 tf.reduce_sum 函数,但是要求输入为 Tensor。
import tensorflow as tfinp = tf.constant([2, 3, 5], dtype=tf.float32)print(tf.reduce_sum(inp)) # 10
TensorFlow 中的 reduce_sum 函数还支持根据不同维度进行计算,以下为常用可设置的参数:
reduction_indices:计算所指定的维度方向keep_dims:输出 Tensor 是否与原 Tensor 维度一致
🍦更多示例:
import tensorflow as tfinp = tf.constant([[1, 2, 3], [4, 5, 6]], dtype=tf.float32)print(tf.reduce_sum(inp))print(tf.reduce_sum(inp, 0)) # y-axisprint(tf.reduce_sum(inp, 1)) # x-axisprint(tf.reduce_sum(inp, 0, keepdims=True))print(tf.reduce_sum(inp, [0, 1]))
输出结果:
tf.Tensor(21.0, shape=(), dtype=float32)tf.Tensor([5. 7. 9.], shape=(3,), dtype=float32)tf.Tensor([ 6. 15.], shape=(2,), dtype=float32)tf.Tensor([[5. 7. 9.]], shape=(1, 3), dtype=float32)tf.Tensor(21.0, shape=(), dtype=float32)
