gpt4 book ai didi

python - 如何根据损失值告诉 Keras 停止训练?

转载 作者:IT老高 更新时间:2023-10-28 21:39:51 25 4
gpt4 key购买 nike

目前我使用以下代码:

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)

当损失在 2 个 epoch 内没有改善时,它会告诉 Keras 停止训练。但是我想在损失变得小于某个恒定的“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)

关于python - 如何根据损失值告诉 Keras 停止训练?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37293642/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com