莫烦tensorflow Batch Normalization总结与tf.identity()/EMA功能

本文详细介绍了TensorFlow中的Batch Normalization,包括其作用和实现过程,同时深入探讨了tf.identity()函数在控制依赖中的作用以及指数滑动平均(EMA)的概念和应用。通过代码示例,阐述了BN层中影子变量的更新机制和衰减率的设置方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码来源于莫烦tensorflow Batch Normalization一节。我添加了一些注释(自己的理解),添加了一些函数的功能介绍。

# 对输入的分散的数据要统一数据规格,这样神经网络可以更好的学习数据的规律,因为数据分布对神经网络是有很大影响的,比如:
# w = 0.1, x1 = 1, x2 =20 --> w*x 0.1, w*x2=2 --> tanh activation function --> tanh(w*x1)接近0,tanh(w*x2)接近1,
#这会使得x增加,w*x接近1或者-1,w*x对较大的x特征范围不敏感.这时候可以对输入数据进行Normalization.


#但是这种情况不仅发生在输入层,所以引入Batch Normalization,在每个batch前向传播时,都要在全连接层与激活函数之间进行Normalization,保持数据分布集中在敏感区域.SGD
# Batch Normalization 包括 标准化工序(x' = x-u/s),s是方差,u是均值.
           # 反标准化工序 y = r * x' + b = BN(x')(参数r, b) 自动学习,用于与标准化工序共同调节数据分布.r:扩展参数,b:平移参数


#=================tf.identity()函数作用与control_dependencies===================
# 第一种:
# x_plus_1 = tf.assign_add(x, 1)

# #control_dependencies的意义是,在执行with包含的内容(在这里就是 y = x)前,
# #先执行control_dependencies参数中的内容(在这里就是 x_plus_1),这里的解释不准确,先接着看。。。
# with tf.control_dependencies([x_plus_1]):
#     y = x    
# 第二种:
# x_plus_1 = tf.assign_add(x, 1)
# with tf.control_dependencies([x_plus_1]):
#     y = tf.identity(x)#修改部分

# 结论:
# 对于control_dependencies这个管理器,只有当里面的操作是一个op时,才会生效,也就是先执行传入的参数op,再执行里面的op。
# 而y=x仅仅是tensor的一个简单赋值,不是定义的op,所以在图中不会形成一个节点,这样该管理器就失效了。
# tf.identity是返回一个一模一样新的tensor的op,这会增加一个新节点到gragh中,这时control_dependencies就会生效,所以第二种情况的输出符合预期。

#=========================================================================
    
    
#=============================EMA=========================================
# 指数滑动平均(ExponentialMovingAverage)EMA被广泛的应用在深度学习的BN层中,RMSprop,adadelta࿰

### 使用或替代 `tf.layers.batch_normalization` 进行批归一化 在 TensorFlow 中,`tf.layers.batch_normalization` 是用于执行批量标准化的操作。然而,在较新的版本中推荐使用更灵活和功能更强的层实现方式。 对于批归一化的应用,可以采用如下方法: #### 方法一:使用 Keras 层 API 实现批归一化 Keras 提供了一个更高层次的接口来构建神经网络模型,其中包含了 BatchNormalization 层可以直接调用[^1]。 ```python import tensorflow as tf from tensorflow.keras.layers import Input, Dense, BatchNormalization input_layer = Input(shape=(784,)) dense_layer = Dense(256)(input_layer) bn_layer = BatchNormalization()(dense_layer) model = tf.keras.Model(inputs=input_layer, outputs=bn_layer) ``` 这种方法不仅简化了代码编写过程,还提供了更好的兼容性和扩展性。 #### 方法二:自定义批归一化函数 如果希望更加深入理解或者有特殊需求,则可以选择自己动手创建一个类似的批处理规范化函数[^2]。 ```python def batch_norm(x, is_training=True): beta = tf.Variable(tf.constant(0.0, shape=[x.shape[-1]]), name='beta', trainable=True) gamma = tf.Variable(tf.constant(1.0, shape=[x.shape[-1]]), name='gamma', trainable=True) axises = list(range(len(x.get_shape()) - 1)) batch_mean, batch_var = tf.nn.moments(x, axes=axises) ema = tf.train.ExponentialMovingAverage(decay=0.99) def mean_var_with_update(): ema_apply_op = ema.apply([batch_mean, batch_var]) with tf.control_dependencies([ema_apply_op]): return tf.identity(batch_mean), tf.identity(batch_var) mean, var = tf.cond(is_training, true_fn=mean_var_with_update, false_fn=lambda: (ema.average(batch_mean), ema.average(batch_var))) normed = tf.nn.batch_normalization(x, mean, var, beta, gamma, 1e-3) return normed ``` 此段代码实现了基本的批归一化逻辑,并通过指数移动平均保存训练期间计算得到的均值方差以便于推理阶段使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值