上篇文章中讲到《pytorch动态调整学习率之Poly策略》,本次讲解另一个较为常用的策略,即训练过程中随着epoch的增加根据设定的
e
p
o
c
h
_
s
t
e
p
epoch\_step
epoch_step对学习率进行衰减操作,具体公式如下所示:
l
r
=
b
a
s
e
_
l
r
×
0.
1
e
p
o
c
h
i
n
t
(
n
u
m
_
e
p
o
c
h
/
e
p
o
c
h
_
s
t
e
p
)
lr = base\_lr \times {0.1^{\frac{{epoch}}{{{\mathop{\rm int}} (num\_epoch/epoch\_step)}}}}
lr=base_lr×0.1int(num_epoch/epoch_step)epoch
其中,
l
r
lr
lr为新的学习率,
b
a
s
e
_
l
r
base\_lr
base_lr为基准学习率,
e
p
o
c
h
epoch
epoch为迭代次数,
n
u
m
_
e
p
o
c
h
num\_epoch
num_epoch为最大迭代次数,
e
p
o
c
h
_
s
t
e
p
epoch\_step
epoch_step控制衰减的速率,其中
i
n
t
(
)
int()
int()为取整运算。
代码具体如下所示:
def adjust_learning_rate_epoch_step(optimizer, epoch, num_epochs, base_lr, epoch_step)
lr = base_lr * 0.1**(epoch/int(num_epochs/epoch_step))
for param_group in optimizer.param_groups:
param_group['lr'] = lr
return lr
以下为学习率随
e
p
o
c
h
_
s
t
e
p
epoch\_step
epoch_step变化而变化的曲线,假设
b
a
s
e
_
l
r
base\_lr
base_lr=0.005,
n
u
m
_
e
p
o
c
h
num\_epoch
num_epoch=100。