通过计算各个维度axis的元素平均值,沿给定的维度axis减少input_tensor。除非keepdims为true,否则对于axis中的每个条目,张量的等级都会降低1。如果keepdims为true,则减小的维度将保留为长度1。
如果axis为None,则缩小所有维度,并返回带有单个元素的张量。
import tensorflow as tf with tf.Session() as sess: x = tf.constant([[1., 1.], [2., 2.]]) a = tf.reduce_mean(x) print(a) print(sess.run(a)) b = tf.reduce_mean(x, 0) print(b) print(sess.run(b)) c = tf.reduce_mean(x, 0) print(c) print(sess.run(c)) # 输出结果: # Tensor("Mean:0", shape=(), dtype=float32) # 1.5 # Tensor("Mean_1:0", shape=(2,), dtype=float32) # [1.5 1.5] # Tensor("Mean_2:0", shape=(2,), dtype=float32) # [1.5 1.5] import tensorflow as tf with tf.Session() as sess: x = tf.constant([[1., 1.], [2., 2.]]) print(tf.reduce_mean(x)) print(sess.run(tf.reduce_mean(x))) print(tf.reduce_mean(x, 0)) print(sess.run(tf.reduce_mean(x, 0))) print(tf.reduce_mean(x, 1)) print(sess.run(tf.reduce_mean(x, 1))) # 输出结果: # Tensor("Mean:0", shape=(), dtype=float32) # 1.5 # Tensor("Mean_2:0", shape=(2,), dtype=float32) # [1.5 1.5] # Tensor("Mean_4:0", shape=(2,), dtype=float32) # [1. 2.]
要减少的维度。如果为None(默认),减少所有的维度。必须在范围
[-rank(input_tensor),rank(input_tensor)]中。
keepdims如果为true,则保留长度为1的减少维度。name操作的名称(可选)。reduction_indices轴的旧名称(不建议使用)。keep_dims不推荐使用的别名keepdims。numpy兼容性:相当于np.mean
请注意,np.mean具有一个可用于指定输出类型的dtype参数。默认情况下为dtype=float64。另一方面,tf.reduce_mean具有来自input_tensor的激进类型推断,例如:
import tensorflow as tf with tf.Session() as sess: x = tf.constant([1, 0, 1, 0]) x_ = tf.reduce_mean(x) print(x_) print(sess.run(x_)) y = tf.constant([1., 0., 1., 0.]) y_ = tf.reduce_mean(y) print(y_) print(sess.run(y_)) # 输出结果: # Tensor("Mean:0", shape=(), dtype=int32) # 0 # Tensor("Mean_1:0", shape=(), dtype=float32) # 0.5即,tf.reduce_mean返回与input_tensor相同的数据类型。