考虑它的最简单方法是 - 传入的轴axes将被折叠,并且统计数据将通过切片来计算axes。例子:
import tensorflow as tf
x = tf.random.uniform((8, 10, 4))
print(x, '\n')
print(tf.nn.moments(x, axes=[0]), '\n')
print(tf.nn.moments(x, axes=[0, 1]))
Tensor("random_uniform:0", shape=(8, 10, 4), dtype=float32)
(<tf.Tensor 'moments/Squeeze:0' shape=(10, 4) dtype=float32>,
<tf.Tensor 'moments/Squeeze_1:0' shape=(10, 4) dtype=float32>)
(<tf.Tensor 'moments_1/Squeeze:0' shape=(4,) dtype=float32>,
<tf.Tensor 'moments_1/Squeeze_1:0' shape=(4,) dtype=float32>)
从源代码中,math_ops.reduce_mean用于计算mean和variance,其运行方式如下:
# axes = [0]
mean = (x[0, :, :] + x[1, :, :] + ... + x[7, :, :]) / 8
mean.shape == (10, 4) # each slice's shape is (10, 4), so sum's shape is also (10, 4)
# axes = [0, 1]
mean = (x[0, 0, :] + x[1, 0, :] + ... + x[7, 0, :] +
x[0, 1, :] + x[1, 1, :] + ... + x[7, 1, :] +
... +
x[0, 10, :] + x[1, 10, :] + ... + x[7, 10, :]) / (8 * 10)
mean.shape == (4, ) # each slice's shape is (4, ), so sum's shape is also (4, )
换句话说,axes=[0]将计算(timesteps, channels)关于samples- 即迭代samples,计算(timesteps, channels)切片的均值和方差的统计信息。因此,对于
标准化将在整个批次和时间步中发生,这意味着我不想为不同的时间步保持单独的均值/方差
您只需要折叠timesteps维度(沿samples),并通过迭代和计算统计samples信息timesteps:
axes = [0, 1]
图像的相同故事,除了你有两个非通道/样本尺寸,你会做axes = [0, 1, 2](折叠samples, height, width)。
伪代码演示:查看平均计算
import tensorflow as tf
import tensorflow.keras.backend as K
import numpy as np
x = tf.constant(np.random.randn(8, 10, 4))
result1 = tf.add(x[0], tf.add(x[1], tf.add(x[2], tf.add(x[3], tf.add(x[4],
tf.add(x[5], tf.add(x[6], x[7]))))))) / 8
result2 = tf.reduce_mean(x, axis=0)
print(K.eval(result1 - result2))
# small differences per numeric imprecision
[[ 2.77555756e-17 0.00000000e+00 -5.55111512e-17 -1.38777878e-17]
[-2.77555756e-17 2.77555756e-17 0.00000000e+00 -1.38777878e-17]
[ 0.00000000e+00 -5.55111512e-17 0.00000000e+00 -2.77555756e-17]
[-1.11022302e-16 2.08166817e-17 2.22044605e-16 0.00000000e+00]
[ 0.00000000e+00 0.00000000e+00 0.00000000e+00 0.00000000e+00]
[-5.55111512e-17 2.77555756e-17 -1.11022302e-16 5.55111512e-17]
[ 0.00000000e+00 0.00000000e+00 0.00000000e+00 -2.77555756e-17]
[ 0.00000000e+00 0.00000000e+00 0.00000000e+00 -5.55111512e-17]
[ 0.00000000e+00 -3.46944695e-17 -2.77555756e-17 1.11022302e-16]
[-5.55111512e-17 5.55111512e-17 0.00000000e+00 1.11022302e-16]]