You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在TensorFlow Keras的Adam优化器中每10个epoch衰减0.9倍学习率

一、decay_steps参数含义

decay_steps指的是每执行多少次参数更新(即一个batch训练完成算1步)触发一次学习率衰减。当你把staircase设为True时,学习率会每累计到decay_steps步时一次性乘以decay_rate,呈现阶梯式下降的效果,和你需要的固定间隔衰减的需求完全匹配。

二、实现每10个epoch衰减的操作步骤

  • 第一步:先计算单epoch训练步数,公式为:
    单epoch步数 = 训练集总样本数 // batch_size(如果不足一个batch也单独训练的话,用向上取整即可)
  • 第二步:计算10个epoch对应的总步数,也就是你需要的decay_steps:
    decay_steps = 单epoch步数 * 10
  • 第三步:配置学习率调度器和Adam优化器即可

三、完整代码示例

假设你的训练集总共有5000个样本,batch_size设为32,示例代码如下:

import tensorflow as tf

# 配置参数
initial_learning_rate = 1e-3
train_samples = 5000  # 替换为你的训练集实际样本数
batch_size = 32       # 替换为你的实际batch size
epochs_per_decay = 10
decay_rate = 0.9

# 计算decay_steps
steps_per_epoch = train_samples // batch_size
decay_steps = steps_per_epoch * epochs_per_decay

# 初始化学习率调度器
lr_schedule = tf.keras.optimizers.schedules.ExponentialDecay(
    initial_learning_rate=initial_learning_rate,
    decay_steps=decay_steps,
    decay_rate=decay_rate,
    staircase=True
)

# 初始化Adam优化器
optimizer = tf.keras.optimizers.Adam(learning_rate=lr_schedule)

# 后续正常编译模型训练即可,建议在model.fit中显式指定steps_per_epoch避免步数计算偏差
# model.compile(optimizer=optimizer, loss=...)
# model.fit(..., steps_per_epoch=steps_per_epoch)

内容的提问来源于stack exchange,提问作者Ahmad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 15:27:03