2

我想在一个小例子中看到 batch_normalization 层的输出,但显然我做错了什么,所以我得到了与输入相同的输出。

import tensorflow as tf
import keras.backend as K
K.set_image_data_format('channels_last')

X = tf.placeholder(tf.float32,  shape=(None, 2, 2, 3))  #  samples are 2X2 images with 3 channels
outp =  tf.layers.batch_normalization(inputs=X,  axis=3)

x = np.random.rand(4, 2, 2, 3)  # sample set: 4 images

init_op = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init_op)
    K.set_session(sess)
    a = sess.run(outp, feed_dict={X:x, K.learning_phase(): 0})
    print(a-x) # print the difference between input and normalized output

上述代码的输入和输出几乎相同。谁能给我指出问题?

4

1 回答 1

2

请记住,batch_normalization在训练和测试时表现不同。在这里,你从来没有“训练”过你的批量归一化,所以它学到的移动平均值是随机的但接近于 0,移动方差因子接近 1,所以输出与输入几乎相同。如果您使用K.learning_phase(): 1,您已经看到了一些差异(因为它将使用批次的平均值和标准偏差进行归一化);如果您首先学习大量示例,然后在其他一些示例上进行测试,您还会看到标准化正在发生,因为学习的均值和标准差不会是 0 和 1。

为了更好地了解批量标准化的效果,我还建议您将输入乘以一个大数字(例如 100),以便您在未标准化和标准化向量之间有明显的区别,这将帮助您测试正在发生的事情。

编辑:在您的代码中,移动均值和移动方差的更新似乎从未完成。您需要确保更新操作已运行,如batch_normalization 的文档中所示。以下几行应该使它工作:

outp =  tf.layers.batch_normalization(inputs=X,  axis=3, training=is_training, center=False, scale=False)

update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(update_ops):
    outp = tf.identity(outp)

下面是我的完整工作代码(我摆脱了 Keras,因为我不太了解它,但你应该能够重新添加它)。

import tensorflow as tf
import numpy as np

X = tf.placeholder(tf.float32,  shape=(None, 2, 2, 3))  #  samples are 2X2 images with 3 channels
is_training = tf.placeholder(tf.bool,  shape=())  #  samples are 2X2 images with 3 channels
outp =  tf.layers.batch_normalization(inputs=X,  axis=3, training=is_training, center=False, scale=False)

update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(update_ops):
    outp = tf.identity(outp)

x = np.random.rand(4, 2, 2, 3) * 100  # sample set: 4 images

init_op = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init_op)
    initial = sess.run(outp, feed_dict={X:x, is_training: False})
    for i in range(10000):
        a = sess.run(outp, feed_dict={X:x, is_training: True})
        if (i % 1000 == 0):
            print("Step %i: " %i, a-x) # print the difference between input and normalized output

    final = sess.run(outp, feed_dict={X: x, is_training: False})
    print("initial: ", initial)
    print("final: ", final)
    assert not np.array_equal(initial, final)
于 2017-12-22T09:00:07.170 回答