TensorFlow ——slim.batch_norm大坑(参数设置以及保存问题)

TensorFlow ——slim.batch_norm大坑(参数设置以及保存问题)

  • slim.batch_norm运用方法。
batch_norm_params = {
            'is_training': is_training,
            'scale': True, # 默认是没有gamma的
            'decay': 0.995,
            'epsilon': 0.001
        }

with slim.arg_scope([slim.conv2d],
                            normalizer_fn=slim.batch_norm,
                            normalizer_params=batch_norm_params,
                            reuse=tf.AUTO_REUSE):
	print("")
  • bn的中变量打印包括四个

    BatchNorm/beta:0
    BatchNorm/gamma:0
    BatchNorm/moving_mean:0
    BatchNorm/moving_variance:0
    
  • batch_norm里的mean和var是无法自动更新的,只有手动添加来更新。

    • 方法一:
      使用slim库的create_train_op训练时可以自动添加update_ops,以更新mean和var参数。
    update_ops = tf.compat.v1.get_collection(tf.compat.v1.GraphKeys.UPDATE_OPS)
    train_op = slim.learning.create_train_op(total_loss=self.cm_loss,optimizer=optimizer,update_ops=update_ops)
    
    • 方法二:
      在参数里设置updates_collections:None,会强制更新,但不推荐
    batch_norm_params = {
                'is_training': is_training,
                updates_collections:None,
                'decay': 0.995,
                'epsilon': 0.001
            }
    
    with slim.arg_scope([slim.conv2d],
                                normalizer_fn=slim.batch_norm,
                                normalizer_params=batch_norm_params,
                                reuse=tf.AUTO_REUSE):
    	print("")
    
    • 方法三:
      使用普通训练方式,需要使用tf.control_dependencies添加参数。
    update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
    with tf.control_dependencies(update_ops):
          train_op = optimizer.minimize(loss)
    
  • slim.batch_norm保存参数
    slim.batch_norm中的moving_mean和moving_variance不是trainable的,在tf.trainable_variables()里面是查不到的,但使用默认的saver = tf.train.Saver()可以保存。
    不能保存的情况下,可以改为:

    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)
    
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值