正确使用Tensorflow Batch_normalization

题外话:tensorflow中,tf.contrib是一些尝试代码或者不稳定的代码,将来可能会被弃用或者删除;tf.layers中是一些已经确定了的代码,基本不会有大的改动;tf.nn是最基本的代码,级别最低,基本不会变,但要实现各种功能,需要自己组合别的api来实现。


使用tf.layers.batch_normalization(),首先是api接口:点击打开链接

注意:

训练:

1.设置training=True;

2.添加下面的代码,以保存滑动平均值,测试时会使用到;

Note: when training, the moving_mean and moving_variance need to be updated. By default the update ops are placed in tf.GraphKeys.UPDATE_OPS, so they need to be added as a dependency to the train_op. Also, be sure to add any batch_normalization ops before getting the update_ops collection. Otherwise, update_ops will be empty, and training/inference will not work properly. For example:

  x_norm = tf.layers.batch_normalization(x, training=training)

  # ...

  update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
  with tf.control_dependencies(update_ops): #保证train_op在update_ops执行之后再执行。
    train_op = optimizer.minimize(loss)

3. 保存模型时:

var_list = tf.trainable_variables() 
g_list = tf.global_variables()
bn_moving_vars = [g for g in g_list if 'moving_mean' in g.name]
bn_moving_vars += [g for g in g_list if 'moving_variance' in g.name]
var_list += bn_moving_vars
saver = tf.train.Saver(var_list=var_list, max_to_keep=5)

用以保存滑动平均值,否则载入模型时,会出错。


预测:

设置training=False。(当训练时的batch_size设置为1时,training=False的测试效果不一定好,可能是由于训练时的batch_size太小,导致滑动平均值不稳定,因为使用滑动平均值去测试效果不好,反而设置为training=True效果更好。可以当做一个超参数去尝试。

点击打开链接

这个人提出即使使用training=False,在测试时效果也不好,他尝试了在测试时用:

update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(update_ops):
    logits = yourmodel.infersence(inputs_)

点击打开链接这是一个当batch_size = 1时,batch_norm实际上是instance_norm的讲解。

参考:https://www.cnblogs.com/hrlnw/p/7227447.html

你可能感兴趣的:(正确使用Tensorflow Batch_normalization)