1、tf.reduce_sum()函数
官方给的API:
tf.reduce_sum 函数
reduce_sum (
input_tensor ,
axis = None ,
keep_dims = False ,
name = None ,
reduction_indices = None
)
- input_tensor:要减少的张量.应该有数字类型。
- axis:要减小的尺寸.如果为None(默认),则缩小所有尺寸.必须在范围[-rank(input_tensor), rank(input_tensor))内。
- keep_dims:如果为true,则保留长度为1的缩小尺寸。
- name:操作的名称(可选)。
- reduction_indices:axis的废弃的名称。
返回值及注意:
- 此函数计算一个张量的各个维度上元素的总和。
- 函数中的input_tensor是按照axis中已经给定的维度来减少的;除非 keep_dims 是true,否则张量的秩将在axis的每个条目中减少1;如果keep_dims为true,则减小的维度将保留为长度1。
- 如果axis没有条目,则缩小所有维度,并返回具有单个元素的张量.
官方例子:
x = tf.constant([[1, 1, 1], [1, 1, 1]])
tf.reduce_sum(x) # 6
tf.reduce_sum(x, 0) # [2, 2, 2]
tf.reduce_sum(x, 1) # [3, 3]
tf.reduce_sum(x, 1, keep_dims=True) # [[3], [3]]
tf.reduce_sum(x, [0, 1]) # 6
代码示例:
例1:
import tensorflow as tf
import numpy as np
x = np.array([[[1,2,3],[4,5,6]],[[7,8,9],[10,11,12]]])
x_p = tf.placeholder(tf.int32,[2,2,3])
y = tf.reduce_sum(x_p,0) # 修改这里的0,这里的axis可以为0,1,2
with tf.Session() as sess:
y = sess.run(y,feed_dict={x_p:x})
print(y)
axis= 0:[[ 8 10 12] [14 16 18]]
1+7 2+8 3+9 ……..
axis=1: [[ 5 7 9] [17 19 21]]
1+4 2+5 3 +6 ….
axis=2: [[ 6 15] [24 33]]
1+2+3 4+5+6…..
2、tf.reduce_mean()函数
基本内容和 tf.reduce_sum()函数差不多,tf.reduce_mean()函数是计算平均值的
例2:
import tensorflow as tf
import numpy as np
x = tf.constant([[1.,1.],[2.,2.]])
y = tf.reduce_mean(x,0) # y = tf.reduce_mean(x,1)
with tf.Session() as sess:
x = sess.run(y)
print(y.eval())
y = tf.reduce_mean(x,0) # [1.5,1.5] <= (1+2)/2 = 1.5
y = tf.reduce_mean(x,1) # [1.,2.] <= (1+1)/2 = 1;(2+2)/2 = 2
注:这里的x
是 [[1.,1.],[2.,2.]]
,若改为[[1,1],[2,2]]
则结果不一样!
3、轴(axis)
- 在numpy中可以理解为方向,使用0,1,2…数字表示,对于一个一维数组,只有一个0轴,对于2维数组
(shape(2,2))
,有0轴和1轴,对于三维数组(shape(2,2, 3))
,有0,1,2轴
——————————————————————————————————————————————————————
参考博客:https://blog.csdn.net/lxg0807/article/details/74625861
https://www.w3cschool.cn/tensorflow_python/tensorflow_python-5y4d2i2n.html
感谢原作者!博客记录学习日常~后续会补充