tf.reducemean
前言
tf.reducemean是一类常见的计算属于Reduction类,这一类的API类似。下面主要看看tf.reducemean的用法和理解
官方
tf.reduce_mean(input_tensor, reduction_indices=None, keep_dims=False, name=None)
Computes the mean of elements across dimensions of a tensor.
Reduces input_tensor
along the dimensions given in reduction_indices.
Unless keep_dims
is true, the rank of the tensor is reduced by 1 for each entry in reduction_indices
. If keep_dims
is true, the reduced dimensions are retained with length 1.
If reduction_indices
has no entries, all dimensions are reduced, and a tensor with a single element is returned.
Args:
- input_tensor
: The tensor to reduce. Should have numeric type.
- reduction_indices
: The dimensions to reduce. If None (the defaut), reduces all dimensions.
- keep_dims
: If true, retains reduced dimensions with length 1.
- name
: A name for the operation (optional).
Returns:
The reduced tensor.
例子
import numpy as np
import tensorflow as tf
inputs = [[1, 0, 2],
[3, 2, 4]]
inputs = np.array(inputs)
A = tf.reduce_mean(inputs)
B = tf.reduce_mean(inputs, reduction_indices=0)
C = tf.reduce_mean(inputs, reduction_indices=1)
D = tf.reduce_mean(inputs, 0, keep_dims=True)
E = tf.reduce_mean(inputs, 1, keep_dims=True)
with tf.Session() as sess:
print(sess.run(A))
print(sess.run(B))
print(sess.run(C))
print(sess.run(D))
print(sess.run(E))
结果
理解
(图片摘自知乎)
reduction_indices
在Martix中可以为none,0,1。none即是求tensor的mean;0则是求column列的mean,因此压缩为一行;而1则是求row行的mean,因此压缩为一列。reduction_indices
为1的时候虽然计算的是行压缩为列,应该是以列输出,当是在实验中可以观测到实际以行在输出。若要以列输出,可以让keep_dims = true
(例子E)