π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix EarlyStopping condition and include filename fcn (#1718)
Edgar Ribaf26fea663dd2
diff --git a/kornia/x/callbacks.py b/kornia/x/callbacks.pyindex e5487064e..cd21f94f2 100644--- a/kornia/x/callbacks.py+++ b/kornia/x/callbacks.py@@ -1,5 +1,5 @@from pathlib import Path-from typing import Optional+from typing import Callable, Optionalimport torchimport torch.nn as nn@@ -7,17 +7,20 @@ import torch.nn as nnfrom .utils import TrainerState+# default function to generate the filename in the model checkpoint+def default_filename_fcn(x) -> str:+ return f"model_{x}.pt"++class EarlyStopping:"""Callback that evaluates whether there is improvement in the loss function.The module track the losses and in case of finish patience sends a termination signal to the trainer.- In case of termination, the module will save the last model.Args:monitor: the name of the value to track.min_delta: the minimum difference between losses to increase the patience counter.patience: the number of times to wait until the trainer does not terminate.- filepath: a backup filename to save the file in case of termination.**Usage example:**@@ -28,10 +31,11 @@ class EarlyStopping:)trainer = ImageClassifierTrainer(...,- callbacks={"terminate", early_stop}+ callbacks={"on_checkpoint", early_stop})"""- def __init__(self, monitor: str, min_delta: float = 0., patience: int = 8) -> None:++ def __init__(self, monitor: str, min_delta: float = 0.0, patience: int = 8) -> None:self.monitor = monitorself.min_delta = min_deltaself.patience = patience@@ -41,9 +45,8 @@ class EarlyStopping:self.early_stop: bool = Falsedef __call__(self, model: nn.Module, epoch: int, valid_metric) -> TrainerState:- score: float = -valid_metric[self.monitor].avg+ score: float = valid_metric[self.monitor].avg- # TODO: rethink about this logic - doesn't seem to do the job.if self.best_score is None:self.best_score = scoreelif score < self.best_score + self.min_delta:@@ -55,9 +58,6 @@ class EarlyStopping:self.counter = 0if self.early_stop:- # TODO: figure out later how and where to save- # store old metric and save new model- # torch.save(model, self.filepath)print(f"[INFO] Early-Stopping the training process. Epoch: {epoch}.")return TrainerState.TERMINATE@@ -65,7 +65,7 @@ class EarlyStopping:class ModelCheckpoint:- """Callback that save the model at the end of everyepoch.+ """Callback that save the model at the end of every epoch.Args:filepath: the where to save the mode.@@ -80,15 +80,17 @@ class ModelCheckpoint:)trainer = ImageClassifierTrainer(...,- callbacks={"checkpoint", model_checkpoint}+ callbacks={"on_checkpoint", model_checkpoint})"""- def __init__(self, filepath: str, monitor: str) -> None:++ def __init__(self, filepath: str, monitor: str, filename_fcn: Optional[Callable] = None) -> None:self.filepath = filepathself.monitor = monitor+ self._filename_fcn = filename_fcn or default_filename_fcn# track best model- self.best_metric: float = 0.+ self.best_metric: float = 0.0# create directoryPath(self.filepath).mkdir(parents=True, exist_ok=True)@@ -98,6 +100,5 @@ class ModelCheckpoint:if valid_metric_value > self.best_metric:self.best_metric = valid_metric_value# store old metric and save new model- filename = Path(self.filepath) / f"model_{epoch}.pt"+ filename = Path(self.filepath) / self._filename_fcn(epoch)torch.save(model, filename)- ...diff --git a/test/x/test_x.py b/test/x/test_x.pyindex 27cf92522..7e02d0aad 100644--- a/test/x/test_x.py+++ b/test/x/test_x.py@@ -11,16 +11,28 @@ def model():return nn.Conv2d(3, 10, kernel_size=1)-def test_callback_modelcheckpoint(tmp_path, model):- cb = ModelCheckpoint(tmp_path, 'test_monitor')- assert cb is not None+class TestModelCheckpoint:+ def test_smoke(self, tmp_path, model):+ cb = ModelCheckpoint(tmp_path, 'test_monitor')+ assert cb is not None- metric = {'test_monitor': AverageMeter()}- metric['test_monitor'].avg = 1.0+ metric = {'test_monitor': AverageMeter()}+ metric['test_monitor'].avg = 1.0++ cb(model, epoch=0, valid_metric=metric)+ assert cb.best_metric == 1.0+ assert (tmp_path / "model_0.pt").is_file()++ def test_custom_filename(self, tmp_path, model):+ cb = ModelCheckpoint(tmp_path, 'test_monitor', filename_fcn=lambda x: "model.pt")+ assert cb is not None++ metric = {'test_monitor': AverageMeter()}+ metric['test_monitor'].avg = 1.0- cb(model, epoch=0, valid_metric=metric)- assert cb.best_metric == 1.0- assert (tmp_path / "model_0.pt").is_file()+ cb(model, epoch=0, valid_metric=metric)+ assert cb.best_metric == 1.0+ assert (tmp_path / "model.pt").is_file()def test_callback_earlystopping(model):@@ -33,14 +45,23 @@ def test_callback_earlystopping(model):state = cb(model, epoch=0, valid_metric=metric)assert state == TrainerState.TRAINING- assert cb.best_score == -1+ assert cb.best_score == 1assert cb.counter == 0metric['test_monitor'].avg = 2state = cb(model, epoch=0, valid_metric=metric)assert state == TrainerState.TRAINING- assert cb.best_score == -1+ assert cb.best_score == 2+ assert cb.counter == 0++ metric['test_monitor'].avg = 1.9+ state = cb(model, epoch=0, valid_metric=metric)+ assert state == TrainerState.TRAINING+ assert cb.best_score == 2assert cb.counter == 1+ metric['test_monitor'].avg = 1.9state = cb(model, epoch=0, valid_metric=metric)assert state == TrainerState.TERMINATE+ assert cb.best_score == 2+ assert cb.counter == 2