TensorFlow学习--tf.reduce_mean()

tf.reduce_mean()对应API为:

def reduce_mean(input_tensor,
                axis=None,
                keep_dims=False,
                name=None,
                reduction_indices=None):

通过张量的维数计算元素的平均值.
相当于Numpy中的np.mean().

# !/usr/bin/python
# coding:utf-8

import tensorflow as tf

t0 = tf.Variable([[1., 9.], [2., 0.]], name='t')
t1 = tf.Variable([[[1., 9.], [2., 0.], [6., 3.]], [[1., 9.], [2., 0.], [6., 3.]]], name='t')
# 初始化变量
init = tf.initialize_all_variables()
# 启动默认图
with tf.Session() as sess:
    sess.run(init)

    print "t0:\n", t0.eval()
    # 默认为求全部元素的均值,即所有维度都会减少,最终返回一个单个元素的张量
    print "reduce_mean(t0):\n", tf.reduce_mean(t0).eval()
    # 若 keep_dims=True 则返回一个单个元素且张量维度与原张量一致的张量
    print "reduce_mean(t0, keep_dims=True):\n", tf.reduce_mean(t0, keep_dims=True).eval()
    # axis=0即沿列方向求均值,即张量的等级沿列方向降低为1
    print "reduce_mean(t0, 0):\n", tf.reduce_mean(t0, 0).eval()
    # axis=0即沿行方向求均值,即张量的等级沿行方向降低为1
    print "reduce_mean(t0, 1):\n", tf.reduce_mean(t0, 1).eval()

    print "t1:\n", t1.eval()
    # reduction_indices:轴的旧名称(不推荐使用)
    print "reduce_mean(t1, 0):\n", tf.reduce_mean(t1, 0).eval()
    print "reduce_mean(t1, 1):\n", tf.reduce_mean(t1, 1).eval()
    # reduction_indices=[0]/[1] 即 axis=0/1
    print "reduce_mean(t1, reduction_indices=[0]):\n", tf.reduce_mean(t1, reduction_indices=[0]).eval()
    print "reduce_mean(t1, reduction_indices=[1]):\n", tf.reduce_mean(t1, reduction_indices=[1]).eval()

输出:

t0:
[[ 1.  9.]
 [ 2.  0.]]
reduce_mean(t0):
3.0
reduce_mean(t0, keep_dims=True):
[[ 3.]]
reduce_mean(t0, 0):
[ 1.5  4.5]
reduce_mean(t0, 1):
[ 5.  1.]
t1:
[[[ 1.  9.]
  [ 2.  0.]
  [ 6.  3.]]

 [[ 1.  9.]
  [ 2.  0.]
  [ 6.  3.]]]
reduce_mean(t1, 0):
[[ 1.  9.]
 [ 2.  0.]
 [ 6.  3.]]
reduce_mean(t1, 1):
[[ 3.  4.]
 [ 3.  4.]]
reduce_mean(t1, reduction_indices=[0]):
[[ 1.  9.]
 [ 2.  0.]
 [ 6.  3.]]
reduce_mean(t1, reduction_indices=[1]):
[[ 3.  4.]
 [ 3.  4.]]
reduce_mean(t1):
[[[ 3.5]]]

你可能感兴趣的:(TensorFlow)