如何在TensorFlow中为卷积层正确创建批量规范化层?

时间:2016-09-19 03:33:47

标签: machine-learning neural-network tensorflow conv-neural-network

我在TensorFlow中查看official batch normalization layer(BN),但它并没有真正解释如何将它用于卷积层。有人知道怎么做吗?特别重要的是它应用并学习每个要素图的相同参数(而不是每次激活)。按照其他顺序,它适用于每个过滤器并学习BN。

在一个特定的玩具示例中,我想在MNIST上使用BN进行转换(基本上是2D数据)。因此可以做到:

W_conv1 = weight_variable([5, 5, 1, 32]) # 5x5 filters with 32 filters
x_image = tf.reshape(x, [-1,28,28,1]) # MNIST image
conv = tf.nn.conv2d(x_image, W_conv1, strides=[1, 1, 1, 1], padding='VALID') #[?,24,24,1]
z = conv # [?,24,24,32]
z = BN(z) # [?,24,24,32], essentially only 32 different scales and shift parameters to learn, per filer application
a = tf.nn.relu(z) # [?,24,24,32]

z = BN(z)将BN应用于每个过滤器创建的每个要素。在伪代码中:

x_patch = x[h:h+5,w:w+h,1] # patch to do convolution
z[h,w,f] = x_patch * W[:,:,f] = tf.matmul(x_patch, W[:,:,f]) # actual matrix multiplication for the convolution

我们已经应用了适当的批量规范层(在伪代码中省略了重要的细节):

z[h,w,f] = BN(z[h,w,f]) = scale[f] * (z[h,w,f]  - mu / sigma) + shift[f]

即。对于每个过滤器f,我们应用BN。

2 个答案:

答案 0 :(得分:2)

重要提示:我在此处提供的链接会影响tf.contrib.layers.batch_norm模块,而不会影响通常tf.nn(请参阅下面的评论和帖子)

我没有对它进行测试,但TF希望您使用它的方式似乎记录在convolution2d docstring中:

def convolution2d(inputs,
              num_outputs,
              kernel_size,
              stride=1,
              padding='SAME',
              activation_fn=nn.relu,
              normalizer_fn=None,
              normalizer_params=None,
              weights_initializer=initializers.xavier_initializer(),
              weights_regularizer=None,
              biases_initializer=init_ops.zeros_initializer,
              biases_regularizer=None,
              reuse=None,
              variables_collections=None,
              outputs_collections=None,
              trainable=True,
              scope=None):
  """Adds a 2D convolution followed by an optional batch_norm layer.
  `convolution2d` creates a variable called `weights`, representing the
  convolutional kernel, that is convolved with the `inputs` to produce a
  `Tensor` of activations. If a `normalizer_fn` is provided (such as
  `batch_norm`), it is then applied. Otherwise, if `normalizer_fn` is
  None and a `biases_initializer` is provided then a `biases` variable would be
  created and added the activations.

根据此建议,您应将normalizer_fn='batch_norm'作为参数添加到您的conv2d方法调用中。

关于特征映射与激活问题,我的猜测是TF会将规范化层添加为新的"节点"在构建图形时,在conv2d的顶部,并且它们都将修改相同的权重变量(在您的情况下,W_conv1对象)。我无论如何都不会将规范层的任务描述为“学习”,但我不太确定我是否明白你的观点(如果你详细说明,我可以尝试进一步提供帮助)那)

修改: 仔细查看函数的主体可以确认我的猜测,并解释了如何使用normalized_params参数。从line 354阅读:

outputs = nn.conv2d(inputs, weights, [1, stride_h, stride_w, 1],
padding=padding)
if normalizer_fn:
  normalizer_params = normalizer_params or {}
  outputs = normalizer_fn(outputs, **normalizer_params)
else:
  ...etc...

我们看到保持每层的相应输出的outputs变量被顺序覆盖。因此,如果在构建图形时给出了normalizer_fn,则nn.conv2d的输出将被额外的图层normalizer_fn覆盖。以下是**normalizer_params发挥作用的位置,作为kwarg迭代传递给给定的normalizer_fn。您可以找到batch_norm here的默认参数,因此将字典传递给带有您希望更改的字典的normalizer_params应该可以做到这一点,如下所示:

normalizer_params = {"epsilon" : 0.314592, "center" : False}

希望它有所帮助!

答案 1 :(得分:1)

以下示例似乎适用于我:

import numpy as np

import tensorflow as tf


normalizer_fn = None
normalizer_fn = tf.contrib.layers.batch_norm

D = 5
kernel_height = 1
kernel_width = 3
F = 4
x = tf.placeholder(tf.float32, shape=[None,1,D,1], name='x-input') #[M, 1, D, 1]
conv = tf.contrib.layers.convolution2d(inputs=x,
    num_outputs=F, # 4
    kernel_size=[kernel_height, kernel_width], # [1,3]
    stride=[1,1],
    padding='VALID',
    rate=1,
    activation_fn=tf.nn.relu,
    normalizer_fn=normalizer_fn,
    normalizer_params=None,
    weights_initializer=tf.contrib.layers.xavier_initializer(dtype=tf.float32),
    biases_initializer=tf.zeros_initializer,
    trainable=True,
    scope='cnn'
)

# syntheitc data
M = 2
X_data = np.array( [np.arange(0,5),np.arange(5,10)] )
print(X_data)
X_data = X_data.reshape(M,1,D,1)
with tf.Session() as sess:
    sess.run( tf.initialize_all_variables() )
    print( sess.run(fetches=conv, feed_dict={x:X_data}) )

控制台输出:

$ python single_convolution.py
[[0 1 2 3 4]
 [5 6 7 8 9]]
[[[[ 1.33058071  1.33073258  1.30027914  0.        ]
   [ 0.95041472  0.95052338  0.92877126  0.        ]
   [ 0.57024884  0.57031405  0.55726254  0.        ]]]


 [[[ 0.          0.          0.          0.56916821]
   [ 0.          0.          0.          0.94861376]
   [ 0.          0.          0.          1.32805932]]]]