测试代码:
x = np.arange(12,dtype=np.float32).reshape(3,4)
a = tf.nn.moments(tf.constant(x),[0])
b = tf.nn.moments(tf.constant(x),[1])
# 相当于展开[0,1]维度, 在所有数上计算均值和方差,等于x.mean(),x.var()
c = tf.nn.moments(tf.constant(x),[0,1])
d = tf.nn.moments(tf.constant(x),None) # 同上
e = tf.nn.moments(tf.constant(x),[]) # 在实数上(0维tensor上)计算
print(0, x,x.mean(),x.var())
with tf.Session() as sess:
print(1, sess.run(a))
print(2, sess.run(b))
print(3, sess.run(c))
print(4, sess.run(c)==sess.run(d),)
print(5, sess.run(e))
执行结果:
0 [[ 0. 1. 2. 3.]
[ 4. 5. 6. 7.]
[ 8. 9. 10. 11.]] 5.5 11.916667
1 (array([4., 5., 6., 7.], dtype=float32), array([10.666667, 10.666667, 10.666667, 10.666667], dtype=float32))
2 (array([1.5, 5.5, 9.5], dtype=float32), array([1.25, 1.25, 1.25], dtype=float32))
3 (5.5, 11.916667)
4 True
5 (array([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.]], dtype=float32), array([[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]], dtype=float32))