Skip to main content
 首页 » 编程设计

python之Keras 自定义回调 : Grid point training termination condition

2024年12月31日8sky-heaven

我正在使用 scikit-learn 的 GridSearchCV 在我的 keras 神经网络上进行网格搜索。我想自定义 callback,这样每次在一个网格点上完成网络训练时,我都可以打印出匹配完成。

假设我定义我的网格如下:

param_grid = dict(epochs=[50, 100, 500, 1000], 
              learn_rate=[0.1, 0.2, 0.3],  
              momentum=[0.01, 0.1],  
              dropout_rate=[0.05, 0.1, 0.15, 0.2]) 

我计算网格上的可能性总数为:

grid_size = reduce(lambda x,y: x*y,[len(param_grid_[key]) for key in param_grid]) 

回调是:

from keras.callbacks import ModelCheckpoint, EarlyStopping 
# checkpoint 
filepath="best_model.hdf5" 
checkpoint = ModelCheckpoint(filepath, monitor='val_acc', verbose=1,  
save_best_only=True, mode='max') 
# Early stoping 
monitor = EarlyStopping(monitor='val_loss', min_delta=1e-5, patience=200,  
verbose=1, mode='auto') 
 
callbacks_list = [checkpoint, monitor, LiveGridReport()] 

其中 LiveGridReport() 是我自定义的回调,它打印关于在网格点上完成训练的消息。

class LiveGridReport(keras.callbacks.Callback): 
 
    def __init__(self, grid_size): 
        grid_size_ = grid_size 
 
    def on_train_begin(self, logs={}): 
        return 
 
    def on_train_end(self, logs={}): 
        return 

我的问题是,考虑到我还有 EarlyStopping 回调,我不知道如何检测网格点上的训练已终止。

请您参考如下方法:

确定在使用 EarlyStopping 回调时停止训练的时期可以使用 stopped_epoch 来完成

EarlyStopping.stopped_epoch 

或使用历史记录

history = model.fit(....) 
number_of_epochs_it_ran = len(history.history['loss'])