TensorFlow 神经网络优化:指数衰减学习率、滑动平均、正则化

1. 指数衰减学习率

tf.train.exponential_decay

先使用较大的学习率快速得到一个较优解,然后随着迭代逐步减小学习率,使模型在训练后期更加稳定。
d e c a y e d _ l e a r n i n g _ r a t e = l e a r n i n g _ r a t e d e c a y _ r a t e g l o b a l _ s t e p d e c a y _ s t e p s decayed\_learning\_rate = learning\_rate * decay\_rate ^{\frac{global\_step}{ decay\_steps}}

global_step = tf.Variable(0,trainable=False)
learning_rate  = tf.train.exponential_decay(learning_rate, global_step, decay_steps, decay_rate, staircase=False)
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost,global_step = global_step)

2. 滑动平均

tf.train.ExponentialMovingAverage

滑动平均记录了一段时间内模型中所有参数 w w b b 各自的平均值。利用滑动平均值可以增强模型的泛化能力。
s h a d o w _ v a r i a b l e = d e c a y × s h a d o w _ v a r i a b l e + ( 1 d e c a y ) × v a r i a b l e shadow\_variable = decay \times shadow\_variable + (1-decay) \times variable 其中, s h a d o w _ v a r i a b l e shadow\_variable 为影子变量, v a r i a b l e variable 为待更新的变量, d e c a y decay 为衰减率。 d e c a y decay 决定了模型的更新速度, d e c a y decay 越大,模型越趋于稳定。实际应用中,一般设定为接近1的数(如0.999或0.9999)。为了使模型在训练前期可以更新的更快,ExponentialMovingAverage还提供了num_updates参数设置 d e c a y decay 的大小:
min { d e c a y , 1 + n u m _ u p d a t e s 10 + 1 + n u m _ u p d a t e s } \min \{ decay, \frac{1+num\_updates}{10+1+num\_updates} \} 使用如下:

variable_averages = tf.train.ExponentialMovingAverage(MOVING_AVERAGE_DECCAY,global_step)
variable_averages_op = variable_averages.apply(tf.trainable_variables())
with tf.control_dependencies([optimizer,variable_averages_op]):
        train_op= tf.no_op(name = 'train')

3. 正则化

Tensorflow提供了

  • tf.contrib.layers.l1_regularizer
  • tf.contrib.layers.l2_regularizer

来计算给定参数的L1/L2正则化项的值。

使用如下:

regularizer = tf.contrib.layers.l2_regularizer(REGULARIZER_RATE) 
tf.add_to_collection('losses',regularizer(W1))
tf.add_to_collection('losses',regularizer(W2))
cem = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits = Y_, labels = Y))
cost = cem + tf.add_n(tf.get_collection('losses'))

猜你喜欢

转载自blog.csdn.net/apr15/article/details/106244851