如何根据损失值告诉Keras停止训练?
目前,我使用以下代码:
callbacks = [ EarlyStopping(monitor='val_loss', patience=2, verbose=0),
ModelCheckpoint(kfold_weights_path, monitor='val_loss', save_best_only=True, verbose=0),
]
model.fit(X_train.astype('float32'), Y_train, batch_size=batch_size, nb_epoch=nb_epoch,
shuffle=True, verbose=1, validation_data=(X_valid, Y_valid),
callbacks=callbacks)
它告诉Keras,如果损失在2个时期内没有改善,就停止训练。但是我要在损失小于某个恒定的“ THR”后停止训练:
if val_loss < THR: break
我在文档中已经看到有可能进行自己的回调:http :
//keras.io/callbacks/ 但没有找到如何停止训练过程的方法。我需要个建议。
回答:
我找到了答案。我调查了Keras的资源,并找到了EarlyStopping的代码。我基于此进行了自己的回调:
class EarlyStoppingByLossVal(Callback): def __init__(self, monitor='val_loss', value=0.00001, verbose=0):
super(Callback, self).__init__()
self.monitor = monitor
self.value = value
self.verbose = verbose
def on_epoch_end(self, epoch, logs={}):
current = logs.get(self.monitor)
if current is None:
warnings.warn("Early stopping requires %s available!" % self.monitor, RuntimeWarning)
if current < self.value:
if self.verbose > 0:
print("Epoch %05d: early stopping THR" % epoch)
self.model.stop_training = True
和用法:
callbacks = [ EarlyStoppingByLossVal(monitor='val_loss', value=0.00001, verbose=1),
# EarlyStopping(monitor='val_loss', patience=2, verbose=0),
ModelCheckpoint(kfold_weights_path, monitor='val_loss', save_best_only=True, verbose=0),
]
model.fit(X_train.astype('float32'), Y_train, batch_size=batch_size, nb_epoch=nb_epoch,
shuffle=True, verbose=1, validation_data=(X_valid, Y_valid),
callbacks=callbacks)
以上是 如何根据损失值告诉Keras停止训练? 的全部内容, 来源链接: utcz.com/qa/419586.html