如何根据批次和纪元的数量更改 Tensorflow 中的学习率?

How to change Learning rate in Tensorflow dependent on number of batches and epochs?

是否有可能使用 Tensorflow 实现以下场景:

在前 N 个批次中,学习率应从 0 增加到 0.001。达到此批次数后,学习率应在每个时期后从 0.001 缓慢下降到 0.00001。

如何在回调中组合此组合? Tensorflow 提供 tf.keras.callbacks.LearningRateScheduler 和回调函数 on_train_batch_begin() 或 on_train_batch_end()。但是我不会来这些回调的通用组合。

有人可以告诉我如何创建这样一个取决于批次和时期数的组合回调吗?

这样的东西会起作用。我没有对此进行测试,也没有尝试对其进行完善...但是其中的部分可以让您按照自己喜欢的方式工作。

import tensorflow as tf
from tensorflow.keras.callbacks import Callback
import numpy as np

class LRSetter(Callback):
    
    def __init__(self, start_lr=0, middle_lr=0.001, end_lr=0.00001, 
                 start_mid_batches=200, end_epochs=2000):
        
        self.start_mid_lr = np.linspace(start_lr, middle_lr, start_mid_batches)
        #Not exactly right since you'll have gone through a couple epochs
        #but you get the picture
        self.mid_end_lr = np.linspace(middle_lr, end_lr, end_epochs) 
        
        self.start_mid_batches = start_mid_batches
        
        self.epoch_takeover = False
        
    def on_train_batch_begin(self, batch, logs=None):
    
        if batch < self.start_mid_batches:
            tf.keras.backend.set_value(self.model.optimizer.lr, self.start_mid_lr[batch])
        else:
            self.epoch_takeover = True

    def on_epoch_begin(self, epoch):
        if self.epoch_takeover:
            tf.keras.backend.set_value(self.model.optimizer.lr, self.mid_end_lr[epoch])