tf.keras.layers.BatchNormalization 与 trainable=False 似乎没有更新其内部移动均值和方差

Add*_*ddy 5 python tensorflow batch-normalization tensorflow2.0

我试图找出 BatchNormalization 层在 TensorFlow 中的具体表现。我想出了以下一段代码,据我所知,它应该是一个完全有效的 keras 模型,但是 BatchNormalization 的均值和方差似乎没有更新。

来自文档https://www.tensorflow.org/api_docs/python/tf/keras/layers/BatchNormalization

对于 BatchNormalization 层,在该层上设置 trainable = False 意味着该层随后将在推理模式下运行(这意味着它将使用移动均值和移动方差来规范化当前批次,而不是使用均值和当前批次的方差)。

我希望模型在每次后续预测调用时返回不同的值。然而,我看到的是返回 10 次的完全相同的值。谁能向我解释为什么 BatchNormalization 层不更新其内部值?

import tensorflow as tf
import numpy as np

if __name__ == '__main__':

    np.random.seed(1)
    x = np.random.randn(3, 5) * 5 + 0.3

    bn = tf.keras.layers.BatchNormalization(trainable=False, epsilon=1e-9)
    z = input = tf.keras.layers.Input([5])
    z = bn(z)

    model = tf.keras.Model(inputs=input, outputs=z)

    for i in range(10):
        print(x)
        print(model.predict(x))
        print()
Run Code Online (Sandbox Code Playgroud)

我使用TensorFlow 2.1.0

Add*_*ddy 10

好吧,我发现我的假设有错误。移动平均线是在训练期间更新的,而不是像我想象的那样在推理期间更新。这是完全有道理的,因为在推理期间更新移动平均值可能会导致不稳定的生产模型(例如,一长串高度病态的输入样本[例如,它们的生成分布与网络训练的分布截然不同]可能会使网络产生偏差并导致有效输入样本的性能较差)。

当您微调预训练模型并希望在训练期间冻结网络的某些层时,可训练参数非常有用。因为当您调用model.predict(x)(或 甚至model(x)model(x, training=False)) 时,图层会自动使用移动平均线而不是批量平均线。

下面的代码清楚地演示了这一点

import tensorflow as tf
import numpy as np

if __name__ == '__main__':

    np.random.seed(1)
    x = np.random.randn(10, 5) * 5 + 0.3

    z = input = tf.keras.layers.Input([5])
    z = tf.keras.layers.BatchNormalization(trainable=True, epsilon=1e-9, momentum=0.99)(z)

    model = tf.keras.Model(inputs=input, outputs=z)
    
    # a dummy loss function
    model.compile(loss=lambda x, y: (x - y) ** 2)

    # a dummy fit just to update the batchnorm moving averages
    model.fit(x, x, batch_size=3, epochs=10)
    
    # first predict uses the moving averages from training
    pred = model(x).numpy()
    print(pred.mean(axis=0))
    print(pred.var(axis=0))
    print()
    
    # outputs the same thing as previous predict
    pred = model(x).numpy()
    print(pred.mean(axis=0))
    print(pred.var(axis=0))
    print()
    
    # here calling the model with training=True results in update of moving averages
    # furthermore, it uses the batch mean and variance as in training, 
    # so the result is very different
    pred = model(x, training=True).numpy()
    print(pred.mean(axis=0))
    print(pred.var(axis=0))
    print()
    
    # here we see again that the moving averages are used but they differ slightly after
    # the previous call, as expected
    pred = model(x).numpy()
    print(pred.mean(axis=0))
    print(pred.var(axis=0))
    print()
Run Code Online (Sandbox Code Playgroud)

最后,我发现文档(https://www.tensorflow.org/api_docs/python/tf/keras/layers/BatchNormalization)提到了这一点:

  1. 当使用包含批量归一化的模型执行推理时,通常(尽管并非总是)需要使用累积统计数据而不是小批量统计数据。这是通过在调用模型时传递 Training=False 或使用 model.predict 来完成的。

希望这对将来有类似误解的人有所帮助。