keras - How to use EarlyStopping to stop training when val_acc reaches a certain percentage
问题描述
I want to stop the training when it reaches a certain percentage, say 98%. I tried many ways and search on Google with no luck. What I do is using EarlyStopping
like this:
es = EarlyStopping(monitor='val_acc', baseline=0.98, verbose=1)
model.fit(tr_X, tr_y, epochs=1000, batch_size=1000, validation_data=(ts_X, ts_y), verbose=1, callbacks=[es])
_, train_acc = model.evaluate(tr_X, tr_y, verbose=0)
_, test_acc = model.evaluate(ts_X, ts_y, verbose=0)
print('>> Train: %.3f, Test: %.3f' % (train_acc, test_acc))
This isn't correct. I would truly appreciate if someone can suggest a way to achieve this goal.
Thank you,
解决方案
你可以像这样创建一个新的回调:
class EarlyStoppingValAcc(Callback):
def __init__(self, monitor='val_acc', value=0.98, verbose=1):
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 = [
EarlyStoppingByValAcc(monitor='val_acc', value=0.98, verbose=1),
]
model.fit(tr_X, tr_y, epochs=1000, batch_size=1000, validation_data=(ts_X, ts_y), verbose=1, callbacks=callbacks)
推荐阅读
- java - 如何创建一个新文件并放置一些用户定义的整数(使用 Scanner 类)然后读取它?
- pandas - Pandas DataFrame 清理
- c - 为 C/C++ 安装 openSSL MacOs X gcc-9 时遇到问题
- curl - Curl 拒绝访问
- reactjs - getDerivedStateFromProps 中的状态更新是否与渲染同步?
- reactjs - 使用 Lerna 为 Create React App 开发模块时编译时间很慢
- javascript - 如何从来自 json 的视频中生成缩略图?
- javascript - 使用 Angular8 将 NPM 包 Stockfish.js(国际象棋引擎)编译为 Web Worker 时出错
- javascript - 正则表达式:匹配字符串之外的字符串对
- java - onJoin 事件不替换 lastPlayer