Keras提供两种学习率适应方法,可通过回调函数实现。
1. LearningRateScheduler
1 |
keras.callbacks.LearningRateScheduler(schedule) |
该回调函数是学习率调度器.
参数
- schedule:函数,该函数以epoch号为参数(从0算起的整数),返回一个新学习率(浮点数)
代码
1
2
3
4
5
6
7
8
9
10
11
12
13 |
import keras.backend as K from keras.callbacks import LearningRateScheduler def scheduler(epoch): # 每隔100个epoch,学习率减小为原来的1/10 if epoch % 100 = = 0 and epoch ! = 0 : lr = K.get_value(model.optimizer.lr) K.set_value(model.optimizer.lr, lr * 0.1 ) print ( "lr changed to {}" . format (lr * 0.1 )) return K.get_value(model.optimizer.lr) reduce_lr = LearningRateScheduler(scheduler) model.fit(train_x, train_y, batch_size = 32 , epochs = 5 , callbacks = [reduce_lr]) |
2. ReduceLROnPlateau
1 |
keras.callbacks.ReduceLROnPlateau(monitor = 'val_loss' , factor = 0.1 , patience = 10 , verbose = 0 , mode = 'auto' , epsilon = 0.0001 , cooldown = 0 , min_lr = 0 ) |
当评价指标不在提升时,减少学习率
当学习停滞时,减少2倍或10倍的学习率常常能获得较好的效果。该回调函数检测指标的情况,如果在patience
个epoch中看不到模型性能提升,则减少学习率
参数
- monitor:被监测的量
- factor:每次减少学习率的因子,学习率将以lr = lr*factor的形式被减少
- patience:当patience个epoch过去而模型性能不提升时,学习率减少的动作会被触发
- mode:‘auto’,‘min’,‘max’之一,在min模式下,如果检测值触发学习率减少。在max模式下,当检测值不再上升则触发学习率减少。
- epsilon:阈值,用来确定是否进入检测值的“平原区”
- cooldown:学习率减少后,会经过cooldown个epoch才重新进行正常操作
- min_lr:学习率的下限
代码
1
2
3 |
from keras.callbacks import ReduceLROnPlateau reduce_lr = ReduceLROnPlateau(monitor = 'val_loss' , patience = 10 , mode = 'auto' ) model.fit(train_x, train_y, batch_size = 32 , epochs = 5 , validation_split = 0.1 , callbacks = [reduce_lr]) |
参考文献:
【1】Keras学习率调整