在MNIST初学者教程中,有这样一个语句:
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
tf.cast
基本上是改变对象的张量类型,但tf.reduce_mean
和np.mean
之间有什么区别呢?
这是关于tf.reduce_mean
的文档:
reduce_mean(input_tensor, reduction_indices=None, keep_dims=False, name=None)
input_tensor
:要减少的张量。应为数值类型。
reduction_indices
:要减少的维度。如果为None
(默认值),则减少所有维度。# 'x' 是 [[1., 1.]]# [2., 2.]]tf.reduce_mean(x) ==> 1.5tf.reduce_mean(x, 0) ==> [1.5, 1.5]tf.reduce_mean(x, 1) ==> [1., 2.]
对于一维向量,看起来np.mean == tf.reduce_mean
,但我不明白tf.reduce_mean(x, 1) ==> [1., 2.]
发生了什么。tf.reduce_mean(x, 0) ==> [1.5, 1.5]
有一定道理,因为[1, 2]
和[1, 2]
的平均值是[1.5, 1.5]
,但tf.reduce_mean(x, 1)
是怎么回事呢?
回答:
numpy.mean
和tensorflow.reduce_mean
的功能是相同的。它们做的事情是一样的。从numpy和tensorflow的文档中可以看出这一点。让我们看一个例子,
c = np.array([[3.,4], [5.,6], [6.,7]])print(np.mean(c,1))Mean = tf.reduce_mean(c,1)with tf.Session() as sess: result = sess.run(Mean) print(result)
输出
[ 3.5 5.5 6.5][ 3.5 5.5 6.5]
在这里你可以看到,当axis
(numpy)或reduction_indices
(tensorflow)为1时,它计算(3,4)、(5,6)和(6,7)的平均值,所以1
定义了计算平均值的轴。当它为0时,平均值是跨(3,5,6)和(4,6,7)计算的,依此类推。我希望你能明白这个概念。
那么它们之间有什么区别呢?
你可以在python的任何地方计算numpy操作。但要进行tensorflow操作,必须在tensorflow的Session
中进行。你可以在这里阅读更多。所以当你需要为tensorflow图(或结构,如果你愿意的话)执行任何计算时,必须在tensorflow的Session
中进行。
让我们看另一个例子。
npMean = np.mean(c)print(npMean+1)tfMean = tf.reduce_mean(c)Add = tfMean + 1with tf.Session() as sess: result = sess.run(Add) print(result)
我们可以在numpy
中自然地将平均值增加1
,但在tensorflow中,你需要在Session
中执行这个操作,如果不使用Session
,你就无法做到这一点。换句话说,当你计算tfMean = tf.reduce_mean(c)
时,tensorflow并不会立即计算它。它只会在Session
中计算。但numpy会在你写np.mean()
时立即计算。
我希望这有意义。