2020-03-03 16:39:43 +00:00
|
|
|
r"""
|
|
|
|
Early Stopping
|
|
|
|
==============
|
2020-04-05 09:38:52 +00:00
|
|
|
|
2020-03-03 16:39:43 +00:00
|
|
|
Stop training when a monitored quantity has stopped improving.
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
2020-02-23 02:45:34 +00:00
|
|
|
import numpy as np
|
2020-04-19 20:41:54 +00:00
|
|
|
import torch
|
2020-02-23 02:45:34 +00:00
|
|
|
|
2020-03-17 22:44:00 +00:00
|
|
|
from pytorch_lightning import _logger as log
|
2020-03-19 13:14:29 +00:00
|
|
|
from pytorch_lightning.callbacks.base import Callback
|
2020-04-09 18:05:46 +00:00
|
|
|
from pytorch_lightning.utilities import rank_zero_warn
|
2020-02-23 02:45:34 +00:00
|
|
|
|
2020-04-19 20:41:54 +00:00
|
|
|
torch_inf = torch.tensor(np.Inf)
|
|
|
|
|
2020-02-23 02:45:34 +00:00
|
|
|
|
|
|
|
class EarlyStopping(Callback):
|
|
|
|
r"""
|
|
|
|
|
|
|
|
Args:
|
2020-04-05 09:38:52 +00:00
|
|
|
monitor: quantity to be monitored. Default: ``'val_loss'``.
|
|
|
|
min_delta: minimum change in the monitored quantity
|
2020-02-23 02:45:34 +00:00
|
|
|
to qualify as an improvement, i.e. an absolute
|
|
|
|
change of less than `min_delta`, will count as no
|
|
|
|
improvement. Default: ``0``.
|
2020-04-05 09:38:52 +00:00
|
|
|
patience: number of epochs with no improvement
|
2020-02-23 02:45:34 +00:00
|
|
|
after which training will be stopped. Default: ``0``.
|
2020-04-05 09:38:52 +00:00
|
|
|
verbose: verbosity mode. Default: ``False``.
|
|
|
|
mode: one of {auto, min, max}. In `min` mode,
|
2020-02-23 02:45:34 +00:00
|
|
|
training will stop when the quantity
|
|
|
|
monitored has stopped decreasing; in `max`
|
|
|
|
mode it will stop when the quantity
|
|
|
|
monitored has stopped increasing; in `auto`
|
|
|
|
mode, the direction is automatically inferred
|
|
|
|
from the name of the monitored quantity. Default: ``'auto'``.
|
2020-04-05 09:38:52 +00:00
|
|
|
strict: whether to crash the training if `monitor` is
|
2020-02-23 02:45:34 +00:00
|
|
|
not found in the metrics. Default: ``True``.
|
|
|
|
|
|
|
|
Example::
|
|
|
|
|
2020-04-05 09:38:52 +00:00
|
|
|
>>> from pytorch_lightning import Trainer
|
|
|
|
>>> from pytorch_lightning.callbacks import EarlyStopping
|
|
|
|
>>> early_stopping = EarlyStopping('val_loss')
|
|
|
|
>>> trainer = Trainer(early_stop_callback=early_stopping)
|
2020-02-23 02:45:34 +00:00
|
|
|
"""
|
|
|
|
|
2020-04-19 20:41:54 +00:00
|
|
|
def __init__(self, monitor: str = 'val_loss', min_delta: float = 0.0, patience: int = 3,
|
2020-02-23 02:45:34 +00:00
|
|
|
verbose: bool = False, mode: str = 'auto', strict: bool = True):
|
|
|
|
super().__init__()
|
|
|
|
|
|
|
|
self.monitor = monitor
|
|
|
|
self.patience = patience
|
|
|
|
self.verbose = verbose
|
|
|
|
self.strict = strict
|
|
|
|
self.min_delta = min_delta
|
|
|
|
self.wait = 0
|
|
|
|
self.stopped_epoch = 0
|
|
|
|
|
|
|
|
mode_dict = {
|
2020-04-19 20:41:54 +00:00
|
|
|
'min': torch.lt,
|
|
|
|
'max': torch.gt,
|
|
|
|
'auto': torch.gt if 'acc' in self.monitor else torch.lt
|
2020-02-23 02:45:34 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if mode not in mode_dict:
|
|
|
|
if self.verbose > 0:
|
|
|
|
log.info(f'EarlyStopping mode {mode} is unknown, fallback to auto mode.')
|
|
|
|
mode = 'auto'
|
|
|
|
|
|
|
|
self.monitor_op = mode_dict[mode]
|
2020-04-19 20:41:54 +00:00
|
|
|
self.min_delta *= 1 if self.monitor_op == torch.gt else -1
|
|
|
|
|
|
|
|
def _validate_condition_metric(self, logs):
|
|
|
|
"""
|
|
|
|
Checks that the condition metric for early stopping is good
|
|
|
|
:param logs:
|
|
|
|
:return:
|
|
|
|
"""
|
2020-02-23 02:45:34 +00:00
|
|
|
monitor_val = logs.get(self.monitor)
|
|
|
|
error_msg = (f'Early stopping conditioned on metric `{self.monitor}`'
|
|
|
|
f' which is not available. Available metrics are:'
|
|
|
|
f' `{"`, `".join(list(logs.keys()))}`')
|
|
|
|
|
|
|
|
if monitor_val is None:
|
|
|
|
if self.strict:
|
|
|
|
raise RuntimeError(error_msg)
|
|
|
|
if self.verbose > 0:
|
2020-04-09 18:05:46 +00:00
|
|
|
rank_zero_warn(error_msg, RuntimeWarning)
|
2020-02-23 02:45:34 +00:00
|
|
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
return True
|
|
|
|
|
2020-02-26 04:17:27 +00:00
|
|
|
def on_train_start(self, trainer, pl_module):
|
2020-02-23 02:45:34 +00:00
|
|
|
# Allow instances to be re-used
|
|
|
|
self.wait = 0
|
|
|
|
self.stopped_epoch = 0
|
2020-04-19 20:41:54 +00:00
|
|
|
self.best = torch_inf if self.monitor_op == torch.lt else -torch_inf
|
2020-02-23 02:45:34 +00:00
|
|
|
|
2020-02-26 04:17:27 +00:00
|
|
|
def on_epoch_end(self, trainer, pl_module):
|
|
|
|
logs = trainer.callback_metrics
|
2020-02-23 02:45:34 +00:00
|
|
|
stop_training = False
|
2020-04-19 20:41:54 +00:00
|
|
|
if not self._validate_condition_metric(logs):
|
2020-02-23 02:45:34 +00:00
|
|
|
return stop_training
|
|
|
|
|
|
|
|
current = logs.get(self.monitor)
|
2020-04-19 20:41:54 +00:00
|
|
|
if not isinstance(current, torch.Tensor):
|
|
|
|
current = torch.tensor(current)
|
|
|
|
|
2020-02-23 02:45:34 +00:00
|
|
|
if self.monitor_op(current - self.min_delta, self.best):
|
|
|
|
self.best = current
|
|
|
|
self.wait = 0
|
|
|
|
else:
|
|
|
|
self.wait += 1
|
|
|
|
if self.wait >= self.patience:
|
2020-02-26 04:17:27 +00:00
|
|
|
self.stopped_epoch = trainer.current_epoch
|
2020-02-23 02:45:34 +00:00
|
|
|
stop_training = True
|
2020-02-26 04:17:27 +00:00
|
|
|
self.on_train_end(trainer, pl_module)
|
2020-02-23 02:45:34 +00:00
|
|
|
|
|
|
|
return stop_training
|
|
|
|
|
2020-02-26 04:17:27 +00:00
|
|
|
def on_train_end(self, trainer, pl_module):
|
2020-02-23 02:45:34 +00:00
|
|
|
if self.stopped_epoch > 0 and self.verbose > 0:
|
2020-04-09 18:05:46 +00:00
|
|
|
rank_zero_warn('Displayed epoch numbers by `EarlyStopping` start from "1" until v0.6.x,'
|
|
|
|
' but will start from "0" in v0.8.0.', DeprecationWarning)
|
2020-02-23 02:45:34 +00:00
|
|
|
log.info(f'Epoch {self.stopped_epoch + 1:05d}: early stopping')
|