方法:

在reduce_sum()中,是从维度上去考虑元素相加。

tf.math.reduce_sum(
    input_tensor, axis=None, keepdims=False, name=None
)

参数说明:

input_tensor:要求和的数据

axis:有两个取值分别为0和1,0代表按照列进行求和,1代表按照行进行求和。当该参数省略时,默认对矩阵所有元素进行求和。

keepdims: If true, retains reduced dimensions with length 1.尝试设置为True,发现跟False没有啥区别。

例子:

import tensorflow as tf
x = tf.constant([[1, 1, 1], [1, 1, 1]])   #2行3列的矩阵
print x
sess = tf.Session()
print "value of x is :  "
print sess.run(x)
#1.所有元素求和
b = tf.reduce_sum(x)
print sess.run(b)

#2.元素按列求和
c = tf.reduce_sum(x, 0)
print c
print "value of c is :"
print sess.run(c)
#3.元素按照行求和
d = tf.reduce_sum(x, 1)
print d
print "value of d is :"
print sess.run(d)
#等价1
bb = tf.reduce_sum(x, [0, 1])
print bb
print "value of bb is:"
print sess.run(bb)

输出:

Tensor("Const:0", shape=(2, 3), dtype=int32)
value of x is :  
[[1 1 1]
 [1 1 1]]
6
Tensor("Sum_1:0", shape=(1, 3), dtype=int32)
value of c is :
[[2 2 2]]
Tensor("Sum_2:0", shape=(2,), dtype=int32)
value of d is :
[3 3]
Tensor("Sum_3:0", shape=(), dtype=int32)
value of bb is:
6

函数名是的前缀reduce_,是“对矩阵降维”的含义,下划线后面的部分就是降维的方式,在reduce_sum()中就是按照求和的方式对矩阵降维。那么其他reduce前缀的函数也举一反三了,比如reduce_mean()就是按照某个维度求平均值,等等。

 

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐