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]]]
  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值