当我尝试比较来自 tf.nn.fused_batch_norm 的方差输出和来自 tf.nn.moments 的方差输出时,对于相同的输入,我没有相同的值。
import numpy as np
import tensorflow as tf
tf.reset_default_graph()
inputs = tf.placeholder(shape=[None,4,4,1], dtype=tf.float32)
mean1, var1 = tf.nn.moments(inputs, [0,1,2])
_, mean2, var2 = tf.nn.fused_batch_norm( \
inputs, scale=[1.], offset=[0.], \
mean=None, variance=None, epsilon=1e-5, \
data_format='NHWC', is_training=True, \
name='reference')
val = np.random.rand(1,4,4,1)
mean3 = tf.reduce_mean(inputs, [0, 1, 2])
mean_sq3 = tf.reduce_mean(tf.square(inputs), [0, 1, 2])
var3 = mean_sq3 - tf.square(mean3)
var_eps1 = var3 + 1e-5
var_eps2 = var3 + np.sqrt(1e-5)
with tf.Session() as sess:
mean_val, var_val = sess.run([mean1, var1], {inputs:val})
print "tf.nn.moments: mean:", mean_val, "| var:", var_val
mean_val, var_val = sess.run([mean2, var2], {inputs:val})
print "tf.nn.fused_batch_norm: mean:", mean_val, "| var:", var_val
mean_val, var_val, var_eps1_val, var_eps2_val = sess.run([mean3, var3, var_eps1, var_eps2], {inputs:val})
print "customs: mean:", mean_val, "| var:", var_val, "| var + eps:", var_eps1_val, "| var + sqrt(eps):", var_eps2_val
您可以看到我试图检查它是否与 epsilon 有关,但显然不是,因为在 GPU 上运行的脚本返回此(它是随机的,但问题总是会发生):
tf.nn.moments: mean: [ 0.54445559] | var: [ 0.09011541]
tf.nn.fused_batch_norm: mean: [ 0.54445559] | var: [ 0.09612311]
customs: mean: [ 0.54445559] | var: [ 0.09011537] | var + eps: [ 0.09012537] | var + sqrt(eps): [ 0.09327765]
如您所见,tf.nn.fused_batch_norm 的方差高于 tf.nn.moments(即使在添加 sqrt(epsilon) 之后)
任何线索为什么会有这种差异?(我觉得 >5% 不算小,看起来也不像是数值精度问题)