打印sgd中每个epoch的学习率



我尝试打印小批量梯度下降中的学习率。但是Ir在许多时期保持不变(总是0.10000000149)。但它应该改变每一个小批量。代码如下:

# set the decay as 1e-1 to see the Ir change between epochs.
sgd = SGD(lr=0.1, decay=1e-1, momentum=0.9, nesterov=True)
model.compile(loss='categorical_crossentropy',
              optimizer=sgd,
              metrics=['accuracy'])
class LossHistory(Callback):
    def on_epoch_begin(self, batch, logs={}):
        lr=self.model.optimizer.lr.get_value()
        print('Ir:', lr)
history=LossHistory()
model.fit(X_train, Y_train,
          batch_size= batch_size,
          nb_epoch= nb_epoch,
          callbacks= [history])

您打印的是初始学习率,而不是在运行中计算的实际学习率:

lr = self.lr * (1. / (1. + self.decay * self.iterations))
from keras import backend as K
from keras.callbacks import Callback

class SGDLearningRateTracker(Callback):
    def on_epoch_end(self, epoch, logs={}):
        optimizer = self.model.optimizer
        lr = K.eval(optimizer.lr * (1. / (1. + optimizer.decay * optimizer.iterations)))
        print('nLR: {:.6f}n'.format(lr))

然后在你的模型中添加回调:

model.fit(X_train, Y_train_cat, nb_epoch=params['n_epochs'], batch_size=params['batch_size'], validation_split=0.1,callbacks=[SGDLearningRateTracker()])

相关内容

  • 没有找到相关文章

最新更新