TensorFlow中具有预热和余弦衰减的自定义回调

2024-06-09 13:34:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我提到了this example,特别是这里介绍的回调。所以,我决定写一个受this one启发的回调。基本上,它结合了热身和余弦衰减

我是这样编码的-

class CustomSchedule(tf.keras.optimizers.schedules.LearningRateSchedule):
    def __init__(self, base_lr=0.1, end_lr=0.001, warmup_steps=390*5):
        super(CustomSchedule, self).__init__()

        self.base_lr = base_lr
        self.end_lr = end_lr
        self.warmup_steps = warmup_steps
    
    def __call__(self, step=390*35):
        warmup_lr_schedule = tf.linspace(0., self.base_lr, self.warmup_steps)
        iters = tf.range(step, dtype=tf.float32) 
        cosine_lr_schedule = tf.convert_to_tensor([self.end_lr + 0.5 * (self.base_lr - self.end_lr) * (1 + \
                        tf.math.cos(tf.constant(math.pi) * t / (step))) for t in iters])
        lr_schedule = tf.concat([warmup_lr_schedule, cosine_lr_schedule], axis=0)
        
        return lr_schedule

我验证了这是否是我想要的,而且确实是-

enter image description here

但是当我在优化器中传递这个回调时,我遇到了奇怪的事情-

OperatorNotAllowedInGraphError: iterating over `tf.Tensor` is not allowed: AutoGraph did convert this function. This might indicate you are trying to use an unsupported feature.

这里是my Colab Notebook的完整再现性。我知道LearningRateSchedule.__call__方法接受step参数,并输出用于该特定步骤的学习速率。但是我介绍的课程是在每一步输出一个完整的时间表,而不是特定步骤的学习率。但我不知道如何才能有效地实现这一目标


Tags: selfbaseinittfdefstepcallsteps
1条回答
网友
1楼 · 发布于 2024-06-09 13:34:30

只是语义,但您使用的是调度程序,而不是回调。调度程序的__call__方法将在每一步被调用以生成新的LR值,因此您不必计算整个调度。您链接的示例完美地说明了这一点

相关问题 更多 >