【问题标题】:How to change Learning rate in Tensorflow dependent on number of batches and epochs?如何根据批次和时期的数量改变 Tensorflow 中的学习率?
【发布时间】:2020-11-27 03:38:39
【问题描述】:

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

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

如何在回调中组合这种组合? Tensorflow 提供 tf.keras.callbacks.LearningRateScheduler 和回调函数 on_train_batch_begin() 或 on_train_batch_end()。但我不会得出这些回调的常见组合。

谁能给我一个方法来创建这样一个取决于批次和时期数的组合回调?

【问题讨论】:

    标签: python-3.x tensorflow callback tensorflow2.0 learning-rate


    【解决方案1】:

    类似的东西会起作用。我没有对此进行测试,也没有尝试完善它……但是这些部件都在那里,以便您可以按照自己的喜好进行操作。

    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])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-19
      • 2021-08-29
      • 1970-01-01
      • 2016-12-17
      • 2021-12-13
      • 1970-01-01
      • 2021-04-07
      • 2020-05-15
      相关资源
      最近更新 更多