tf.softmax()比较好理解,就是求各个值的比重,看下面程序的例子就知道了。
tf.reduce_sum(),tf.reduce_mean()常出现的地方例如:
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
从reduce_sum的源码定义中看,def reduce_sum(input_tensor,axis=None,keepdims=None,name=None,reduction_indices=None,
keep_dims=None),其中注释说axis和reduction_indices的作用是一样的,reduction_indices可以说是axis的别名。一般调用reduce_sum也只需要两个参数就够了。
参考网址:https://blog.csdn.net/qq_16137569/article/details/72568793 感谢!
在reduce_sum()中,是从维度上去考虑的
调用reduce_sum(arg1, arg2)时,参数arg1即为要求和的数据,arg2有两个取值分别为0和1,通常用reduction_indices=[0]或reduction_indices=[1]来传递参数。从上图可以看出,当arg2 = 0时,是纵向对矩阵求和,原来矩阵有几列就得到几个值;相似地,当arg2 = 1时,是横向对矩阵求和;当省略arg2参数时,默认对矩阵所有元素进行求和。
看到这里,函数名的前缀为什么是reduce_其实也就很容易理解了,reduce就是“对矩阵降维”的含义,下划线后面的部分就是降维的方式,在reduce_sum()中就是按照求和的方式对矩阵降维。那么其他reduce前缀的函数也举一反三了,比如reduce_mean()就是按照某个维度求平均值,等等。
关于softmax和reduce_sum的例子如下:
import tensorflow as tf
a = tf.constant([1.0,2.0,3.0,4.0,5.0,6.0])
b = tf.nn.softmax(logits = a)
x = tf.constant([[1.0],[4.0]]) # (2,1)
print(x)
y = tf.constant([[1.0,2.0,3.0,4.0],[5.0,6.0,7.0,8.0]]) # (2,4)
print(y)
c = tf.reduce_sum(y,0)
d = tf.reduce_sum(y,1)
e = x*y # 利用广播机制即可相乘
f = tf.reduce_sum(e,0) # 也就是axis=0
g = tf.reduce_sum(e,1) # axis=1
with tf.Session() as sess:
print("a:", sess.run(a))
print("b:", sess.run(b))
print("c:", sess.run(c))
print("d:", sess.run(d))
print("e:", sess.run(e))
print("f:", sess.run(f))
print("g:", sess.run(g))
输出为:
Tensor("Const_1:0", shape=(2, 1), dtype=float32)
Tensor("Const_2:0", shape=(2, 4), dtype=float32)
a: [1. 2. 3. 4. 5. 6.]
b: [0.00426978 0.01160646 0.03154963 0.08576079 0.233122 0.6336913 ]
c: [ 6. 8. 10. 12.]
d: [10. 26.]
e: [[ 1. 2. 3. 4.]
[20. 24. 28. 32.]]
f: [21. 26. 31. 36.]
g: [ 10. 104.]