NoamDecay¶
- class paddle.optimizer.lr. NoamDecay ( d_model, warmup_steps, learning_rate=1.0, last_epoch=- 1, verbose=False ) [源代码] ¶
该接口提供 Noam 衰减学习率的策略。
Noam 衰减的计算方式如下:
\[new\_learning\_rate = learning\_rate * d_{model}^{-0.5} * min(epoch^{-0.5}, epoch * warmup\_steps^{-1.5})\]
相关论文:attention is all you need 。
参数¶
d$_{model}$ (int) - 模型的输入、输出向量特征维度,为超参数。数据类型为 Python int。
warmup_steps (int) - 预热步数,为超参数。数据类型为 Python int。
learning_rate (float) - 初始学习率,数据类型为 Python float。默认值为 1.0。
last_epoch (int,可选) - 上一轮的轮数,重启训练时设置为上一轮的 epoch 数。默认值为 -1,则为初始学习率。
verbose (bool,可选) - 如果是 True,则在每一轮更新时在标准输出 stdout 输出一条信息。默认值为
False
。
返回¶
用于调整学习率的 NoamDecay
实例对象。
代码示例¶
import paddle
import numpy as np
# train on default dynamic graph mode
linear = paddle.nn.Linear(10, 10)
scheduler = paddle.optimizer.lr.NoamDecay(d_model=0.01, warmup_steps=100, verbose=True)
sgd = paddle.optimizer.SGD(learning_rate=scheduler, parameters=linear.parameters())
for epoch in range(20):
for batch_id in range(5):
x = paddle.uniform([10, 10])
out = linear(x)
loss = paddle.mean(out)
loss.backward()
sgd.step()
sgd.clear_gradients()
scheduler.step() # If you update learning rate each step
# scheduler.step() # If you update learning rate each epoch
# train on static graph mode
paddle.enable_static()
main_prog = paddle.static.Program()
start_prog = paddle.static.Program()
with paddle.static.program_guard(main_prog, start_prog):
x = paddle.static.data(name='x', shape=[None, 4, 5])
y = paddle.static.data(name='y', shape=[None, 4, 5])
z = paddle.static.nn.fc(x, 100)
loss = paddle.mean(z)
scheduler = paddle.optimizer.lr.NoamDecay(d_model=0.01, warmup_steps=100, verbose=True)
sgd = paddle.optimizer.SGD(learning_rate=scheduler)
sgd.minimize(loss)
exe = paddle.static.Executor()
exe.run(start_prog)
for epoch in range(20):
for batch_id in range(5):
out = exe.run(
main_prog,
feed={
'x': np.random.randn(3, 4, 5).astype('float32'),
'y': np.random.randn(3, 4, 5).astype('float32')
},
fetch_list=loss.name)
scheduler.step() # If you update learning rate each step
# scheduler.step() # If you update learning rate each epoch