프로그래밍/TensorFlow2
tf.reduce_sum 함수
깊은대학
2021. 3. 12. 13:29
tf.reduce_sum 은 텐서의 모든 성분의 총합을 계산하는 함수다.
예를 들어 다음과 같은

import tensorflow as tf
A = tf.constant([[[1, 2, 3]], [[4, 5, 6]]])
print("A=", A)
print(tf.reduce_sum(A))
Output:
A= tf.Tensor(
[[[1 2 3]]
[[4 5 6]]], shape=(2, 1, 3), dtype=int32)
tf.Tensor(21, shape=(), dtype=int32)
텐서

print(tf.reduce_sum(A, 0))
print(tf.reduce_sum(A, 2))
Output:
tf.Tensor([[5 7 9]], shape=(1, 3), dtype=int32)
tf.Tensor(
[[ 6]
[15]], shape=(2, 1), dtype=int32)
옵션 keepdims 을 True 로 하면 차원은 유지되는 대신 길이는 1로 축소된다. 텐서

print(tf.reduce_sum(A, 0, keepdims=True))
print(tf.reduce_sum(A, 2, keepdims=True))
Output:
tf.Tensor([[[5 7 9]]], shape=(1, 1, 3), dtype=int32)
tf.Tensor(
[[[ 6]]
[[15]]], shape=(2, 1, 1), dtype=int32)