tf.train.exponential_decay
函数描述:
通过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}}
decayed_learning_rate=learning_rate∗decay_ratedecay_stepsglobal_step
学习率较大容易搜索震荡(在最优值附近徘徊),学习率较小则收敛速度较慢,
那么可以通过初始定义一个较大的学习率,通过设置decay_rate来缩小学习率,减少迭代次数。tf.train.exponential_decay就是用来实现这个功能。
步骤:
1.首先使用较大学习率(目的:为快速得到一个比较优的解);
2.然后通过迭代逐步减小学习率(目的:为使模型在训练后期更加稳定);
tf.train.exponential_decay(
learning_rate,
global_step,
decay_steps,
decay_rate,
staircase=True/False
)
参数:
learning_rate - 初始学习率
global_step - 用于衰减计算的全局步骤。 一定不为负数。喂入一次 BACTH_SIZE 计为一次 global_step
decay_steps - 衰减速度,一定不能为负数,每间隔decay_steps次更新一次learning_rate值
decay_rate - 衰减系数,衰减速率,其具体意义参看函数计算方程(对应α^t中的α)。
staircase - 若 ‘ True ’ ,则学习率衰减呈 ‘ 离散间隔 ’ (discrete intervals),具体地讲,global_step / decay_steps是整数除法,衰减学习率( the decayed learning rate )遵循阶梯函数;若为 ’ False ‘ ,则更新学习率的值是一个连续的过程,每步都会更新学习率。
返回值:
与初始学习率 ‘ learning_rate ’ 相同的标量 ’ Tensor ‘ 。
示例:
# -*- coding:utf-8 -*-
import tensorflow as tf
import matplotlib.pyplot as plt
learning_rate = 0.1
decay_rate = 0.96
global_steps = 1000
decay_steps = 100
global_step = tf.Variable(0, trainable = False)
c = tf.train.exponential_decay(learning_rate, global_step, decay_steps, decay_rate, staircase=True)
d = tf.train.exponential_decay(learning_rate, global_step, decay_steps, decay_rate, staircase=False)
T_C = []
F_D = []
with tf.Session() as sess:
for i in range(global_steps):
T_c = sess.run(c, feed_dict={global_step: i})
T_C.append(T_c)
F_d = sess.run(d, feed_dict={global_step: i})
F_D.append(F_d)
plt.figure(1)
plt.plot(range(global_steps), T_C, 'b-')
plt.plot(range(global_steps), F_D, 'r-')
plt.show()
备注:
(1)台阶形状的蓝色线是 staircase = True,线条形状的红色线是 staircase = Fasle
(2)初始学习率 learning_rate 为0.1,总训练次数 global_setps 为 1000 次;staircase=True时,每隔 decay_steps = 100 次更新一次 学习率 learning_rate,而staircase=False时,每一步均会更新一次学习率 learning_rate ,
(3)训练过程中,decay_rate的数值保持步不变。