π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
:star2: Add semantic segmentation trainer (#1323)
Edgar Ribad4f8376dcd12
diff --git a/docs/source/get-started/training.rst b/docs/source/get-started/training.rstindex 964d8099a..e869d27f3 100644--- a/docs/source/get-started/training.rst+++ b/docs/source/get-started/training.rst@@ -109,7 +109,7 @@ At this point you might think - *Is this API generic enough ?*The :py:class:`~kornia.x.Trainer` internals are clearly defined such in a way so that e.g you cansubclass and just override the :py:meth:`~kornia.x.Trainer.evaluate` method and adjustaccording to your needs. We provide predefined classes for generic problems such as-:py:class:`~kornia.x.ImageClassifierTrainer`.+:py:class:`~kornia.x.ImageClassifierTrainer`, :py:class:`~kornia.x.SemanticSegmentationTrainer`... note::More trainers will come as soon as we include more models.@@ -162,6 +162,10 @@ You can easily customize by creating your own class, or even through ``callbacks# create the trainer and pass the evaluate method as followstrainer = K.train.Trainer(..., callbacks={"fit", my_fit})+.. note::+ The following hooks are available to override: ``preprocess``, ``augmentations``, ``evaluate``, ``fit``,+ ``checkpoint``, ``on_epoch_end``, ``on_before_model``+Preprocess and augmentations----------------------------diff --git a/docs/source/metrics.rst b/docs/source/metrics.rstindex 590599665..4758e7c15 100644--- a/docs/source/metrics.rst+++ b/docs/source/metrics.rst@@ -6,24 +6,24 @@ kornia.metricsModule containing metrics for training networksClassification-==============+--------------.. autofunction:: accuracySegmentation-============+------------.. autofunction:: confusion_matrix.. autofunction:: mean_iouImage Quality-==============+-------------.. autofunction:: psnr.. autofunction:: ssim.. autoclass:: SSIMMonitoring-==========+----------.. autoclass:: AverageMeterdiff --git a/docs/source/x.rst b/docs/source/x.rstindex bc1b4ce9c..226c016db 100644--- a/docs/source/x.rst+++ b/docs/source/x.rst@@ -12,6 +12,7 @@ Domain trainers---------------.. autoclass:: ImageClassifierTrainer+.. autoclass:: SemanticSegmentationTrainerCallbacksdiff --git a/kornia/x/__init__.py b/kornia/x/__init__.pyindex a876c5b5f..2fb043a12 100644--- a/kornia/x/__init__.py+++ b/kornia/x/__init__.py@@ -1,4 +1,4 @@from .callbacks import EarlyStopping, ModelCheckpointfrom .trainer import Trainer-from .trainer_classification import ImageClassifierTrainer-from .utils import Configuration, TrainerState+from .trainer_classification import ImageClassifierTrainer, SemanticSegmentationTrainer+from .utils import Configuration, Lambda, TrainerStatediff --git a/kornia/x/trainer.py b/kornia/x/trainer.pyindex 0696815c4..9d33bfdf3 100644--- a/kornia/x/trainer.py+++ b/kornia/x/trainer.py@@ -17,7 +17,18 @@ from kornia.metrics import AverageMeterfrom .utils import Configuration, TrainerStatecallbacks_whitelist = [- "preprocess", "augmentations", "evaluate", "fit", "checkpoint", "terminate"+ # high level functions+ "preprocess",+ "augmentations",+ "evaluate",+ "fit",+ "fit_epoch",+ # events (by calling order)+ "on_epoch_start",+ "on_before_model",+ "on_after_model",+ "on_checkpoint",+ "on_epoch_end",]@@ -77,11 +88,13 @@ class Trainer:for fn_name, fn in callbacks.items():if fn_name not in callbacks_whitelist:raise ValueError(f"Not supported: {fn_name}.")- setattr(self, fn_name, fn)+ setattr(Trainer, fn_name, fn)# hyper-paramsself.num_epochs = config.num_epochs+ self.state = TrainerState.STARTING+self._logger = logging.getLogger('train')@property@@ -96,19 +109,20 @@ class Trainer:self.model.train()losses = AverageMeter()for sample_id, sample in enumerate(self.train_dataloader):- source, target = sample # this might change with new pytorch dataset structure+ sample = {"input": sample[0], "target": sample[1]} # new dataset api will come like thisself.optimizer.zero_grad()-# perform the preprocess and augmentations in batch- img = self.preprocess(source)- img = self.augmentations(img)+ sample = self.preprocess(sample)+ sample = self.augmentations(sample)+ sample = self.on_before_model(sample)# make the actual inference- output = self.model(img)- loss = self.criterion(output, target)+ output = self.model(sample["input"])+ self.on_after_model(output, sample) # for debugging purposes+ loss = self.criterion(output, sample["target"])self.backward(loss)self.optimizer.step()- losses.update(loss.item(), img.shape[0])+ losses.update(loss.item(), sample["target"].shape[0])if sample_id % 50 == 0:self._logger.info(@@ -123,16 +137,18 @@ class Trainer:for epoch in range(self.num_epochs):# call internally the training loop# NOTE: override to customize your evaluation routine+ self.state = TrainerState.TRAININGself.fit_epoch(epoch)# call internally the evaluation loop# NOTE: override to customize your evaluation routine+ self.state = TrainerState.VALIDATEvalid_stats = self.evaluate()- self.checkpoint(self.model, epoch, valid_stats)+ self.on_checkpoint(self.model, epoch, valid_stats)- state = self.terminate(self.model, epoch, valid_stats)- if state == TrainerState.TERMINATE:+ self.on_epoch_end()+ if self.state == TrainerState.TERMINATE:break# END OF THE EPOCH@@ -140,17 +156,28 @@ class Trainer:...+ # events stubs+def evaluate(self):...- def preprocess(self, x):+ def on_epoch_start(self, *args, **kwargs):+ ...++ def preprocess(self, x: dict) -> dict:return x- def augmentations(self, x):+ def augmentations(self, x: dict) -> dict:return x- def checkpoint(self, *args, **kwargs):+ def on_before_model(self, x: dict) -> dict:+ return x++ def on_after_model(self, output: torch.Tensor, sample: dict):+ ...++ def on_checkpoint(self, *args, **kwargs):...- def terminate(self, *args, **kwargs):+ def on_epoch_end(self, *args, **kwargs):...diff --git a/kornia/x/trainer_classification.py b/kornia/x/trainer_classification.pyindex 5279e1a10..0ad544c62 100644--- a/kornia/x/trainer_classification.py+++ b/kornia/x/trainer_classification.py@@ -1,6 +1,6 @@import torch-from kornia.metrics import accuracy, AverageMeter+from kornia.metrics import accuracy, AverageMeter, mean_ioufrom .trainer import Trainer@@ -13,27 +13,27 @@ class ImageClassifierTrainer(Trainer):.. seealso::Learn how to use this class in the following- `example <https://github.com/kornia/kornia/master/examples/train/train_classifier.py>`_.+ `example <https://github.com/kornia/kornia/blob/master/examples/train/image_classifier/>`__."""@torch.no_grad()def evaluate(self) -> dict:self.model.eval()stats = {'losses': AverageMeter(), 'top1': AverageMeter(), 'top5': AverageMeter()}for sample_id, sample in enumerate(self.valid_dataloader):- source, target = sample # this might change with new pytorch ataset structure-+ sample = {"input": sample[0], "target": sample[1]} # new dataset api will come like this# perform the preprocess and augmentations in batch- img = self.preprocess(source)+ sample = self.preprocess(sample)# Forward- out = self.model(img)+ out = self.model(sample["input"])# Loss computation- val_loss = self.criterion(out, target)+ val_loss = self.criterion(out, sample["target"])# measure accuracy and record loss- acc1, acc5 = accuracy(out.detach(), target, topk=(1, 5))- stats['losses'].update(val_loss.item(), img.shape[0])- stats['top1'].update(acc1.item(), img.shape[0])- stats['top5'].update(acc5.item(), img.shape[0])+ acc1, acc5 = accuracy(out.detach(), sample["target"], topk=(1, 5))+ batch_size: int = sample["input"].shape[0]+ stats['losses'].update(val_loss.item(), batch_size)+ stats['top1'].update(acc1.item(), batch_size)+ stats['top5'].update(acc5.item(), batch_size)if sample_id % 10 == 0:self._logger.info(@@ -44,3 +44,44 @@ class ImageClassifierTrainer(Trainer):)return stats+++class SemanticSegmentationTrainer(Trainer):+ """Module to be used for Semantic segmentation purposes.++ The module subclasses :py:class:`~kornia.x.Trainer` and overrides the+ :py:meth:`~kornia.x.Trainer.evaluate` function implementing IoU :py:meth:`~kornia.utils.mean_iou`.++ .. seealso::+ Learn how to use this class in the following+ `example <https://github.com/kornia/kornia/blob/master/examples/train/semantic_segmentation/>`__.+ """+ @torch.no_grad()+ def evaluate(self) -> dict:+ self.model.eval()+ stats = {'losses': AverageMeter(), 'iou': AverageMeter()}+ for sample_id, sample in enumerate(self.valid_dataloader):+ sample = {"input": sample[0], "target": sample[1]} # new dataset api will come like this+ # perform the preprocess and augmentations in batch+ sample = self.preprocess(sample)+ sample = self.on_before_model(sample)+ # Forward+ out = self.model(sample["input"])+ self.on_after_model(out, sample)+ # Loss computation+ val_loss = self.criterion(out, sample["target"])++ # measure accuracy and record loss+ iou = mean_iou(out.argmax(1), sample["target"], out.shape[1]).mean()+ batch_size: int = sample["input"].shape[0]+ stats['losses'].update(val_loss.item(), batch_size)+ stats['iou'].update(iou, batch_size)++ if sample_id % 10 == 0:+ self._logger.info(+ f"Test: {sample_id}/{len(self.valid_dataloader)} "+ f"Loss: {stats['losses'].val:.2f} {stats['losses'].avg:.2f} "+ f"IoU: {stats['iou'].val:.2f} {stats['iou'].val:.2f} "+ )++ return statsdiff --git a/kornia/x/utils.py b/kornia/x/utils.pyindex d213bf3dc..0a24180b9 100644--- a/kornia/x/utils.py+++ b/kornia/x/utils.py@@ -1,14 +1,17 @@# TODO: remove the type: ignore in below after deprecating python 3.6from dataclasses import dataclass, field # type: ignorefrom enum import Enum-from pathlib import Path-import yaml # type: ignore+import torch.nn as nn++# import yaml # type: ignoreclass TrainerState(Enum):- TRAINING = 0- TERMINATE = 1+ STARTING = 0+ TRAINING = 1+ VALIDATE = 2+ TERMINATE = 3# NOTE: this class needs to be redefined according to the needed parameters.@@ -19,15 +22,37 @@ class Configuration:num_epochs: int = field(default=1, metadata={"help": "The number of epochs to run the training."})lr: float = field(default=1e-3, metadata={"help": "The learning rate to be used for the optimize."})output_path: str = field(default="./output", metadata={"help": "The output data directory."})+ image_size: tuple = field(default=(224, 224), metadata={"help": "The input image size."})# TODO: possibly remove because hydra already do this- def __init__(self, **entries):- for k, v in entries.items():- self.__dict__[k] = Configuration(**v) if isinstance(v, dict) else v-- @classmethod- def from_yaml(cls, config_file: str):- """Create an instance of the configuration from a yaml file."""- with open(config_file) as f:- data = yaml.safe_load(f)- return cls(**data)+ # def __init__(self, **entries):+ # for k, v in entries.items():+ # self.__dict__[k] = Configuration(**v) if isinstance(v, dict) else v++ # @classmethod+ # def from_yaml(cls, config_file: str):+ # """Create an instance of the configuration from a yaml file."""+ # with open(config_file) as f:+ # data = yaml.safe_load(f)+ # return cls(**data)+++class Lambda(nn.Module):+ """Module to create a lambda function as nn.Module.++ Args:+ fcn: a pointer to any function.++ Example:+ >>> import torch+ >>> import kornia as K+ >>> fcn = Lambda(lambda x: K.geometry.resize(x, (32, 16)))+ >>> fcn(torch.rand(1, 4, 64, 32)).shape+ torch.Size([1, 4, 32, 16])+ """+ def __init__(self, fcn):+ super().__init__()+ self.fcn = fcn++ def forward(self, x):+ return self.fcn(x)diff --git a/test/test_x.py b/test/x/test_image_classification.pysimilarity index 54%rename from test/test_x.pyrename to test/x/test_image_classification.pyindex a01295680..2214f8636 100644--- a/test/test_x.py+++ b/test/x/test_image_classification.py@@ -4,12 +4,10 @@ import torch.nn as nnfrom torch.utils.data import Datasetfrom kornia.contrib import ClassificationHead, VisionTransformer-from kornia.metrics import AverageMeter-from kornia.x import Configuration, EarlyStopping, ImageClassifierTrainer, ModelCheckpoint-from kornia.x.utils import TrainerState+from kornia.x import Configuration, ImageClassifierTrainer-class DummyDataset(Dataset):+class DummyDatasetClassification(Dataset):def __len__(self):return 10@@ -26,12 +24,8 @@ def model():@pytest.fixture-def dataset():- return DummyDataset()---def dataloader(dataset):+def dataloader():+ dataset = DummyDatasetClassification()return torch.utils.data.DataLoader(dataset, batch_size=1)@@ -58,6 +52,7 @@ def configuration():class TestImageClassifierTrainer:+def test_fit(self, model, dataloader, criterion, optimizer, scheduler, configuration):trainer = ImageClassifierTrainer(model, dataloader, dataloader, criterion, optimizer, scheduler, configuration,@@ -70,38 +65,3 @@ class TestImageClassifierTrainer:model, dataloader, dataloader, criterion, optimizer, scheduler, configuration,callbacks={'frodo': None},)---def test_callback_modelcheckpoint(tmp_path, model):- cb = ModelCheckpoint(tmp_path, 'test_monitor')- assert cb is not None-- metric = {'test_monitor': AverageMeter()}- metric['test_monitor'].avg = 1.-- cb(model, epoch=0, valid_metric=metric)- assert cb.best_metric == 1.0- assert (tmp_path / "model_0.pt").is_file()---def test_callback_earlystopping(model):- cb = EarlyStopping('test_monitor', patience=2)- assert cb is not None- assert cb.counter == 0-- metric = {'test_monitor': AverageMeter()}- metric['test_monitor'].avg = 1-- state = cb(model, epoch=0, valid_metric=metric)- assert state == TrainerState.TRAINING- assert cb.best_score == -1- assert cb.counter == 0-- metric['test_monitor'].avg = 2- state = cb(model, epoch=0, valid_metric=metric)- assert state == TrainerState.TRAINING- assert cb.best_score == -1- assert cb.counter == 1-- state = cb(model, epoch=0, valid_metric=metric)- assert state == TrainerState.TERMINATEdiff --git a/test/x/test_segmentation.py b/test/x/test_segmentation.pynew file mode 100644index 000000000..a38ea2c3c--- /dev/null+++ b/test/x/test_segmentation.py@@ -0,0 +1,62 @@+import pytest+import torch+import torch.nn as nn+from torch.utils.data import Dataset++from kornia.x import Configuration, SemanticSegmentationTrainer+++class DummyDatasetSegmentation(Dataset):+ def __len__(self):+ return 10++ def __getitem__(self, index):+ return torch.ones(3, 32, 32), torch.ones(32, 32).long()+++def model():+ return nn.Conv2d(3, 10, kernel_size=1)+++def dataloader():+ dataset = DummyDatasetSegmentation()+ return torch.utils.data.DataLoader(dataset, batch_size=1)+++def criterion():+ return nn.CrossEntropyLoss()+++def optimizer(model):+ return torch.optim.AdamW(model.parameters())+++def scheduler(optimizer, dataloader):+ return torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, len(dataloader))+++def configuration():+ config = Configuration()+ config.num_epochs = 1+ return config+++class TestsemanticSegmentationTrainer:+ def test_fit(self, model, dataloader, criterion, optimizer, scheduler, configuration):+ trainer = SemanticSegmentationTrainer(+ model, dataloader, dataloader, criterion, optimizer, scheduler, configuration,+ )+ trainer.fit()++ def test_exception(self, model, dataloader, criterion, optimizer, scheduler, configuration):+ with pytest.raises(ValueError):+ SemanticSegmentationTrainer(+ model, dataloader, dataloader, criterion, optimizer, scheduler, configuration,+ callbacks={'frodo': None},+ )diff --git a/test/x/test_x.py b/test/x/test_x.pynew file mode 100644index 000000000..7f05ad5db--- /dev/null+++ b/test/x/test_x.py@@ -0,0 +1,46 @@+import pytest+import torch.nn as nn++from kornia.metrics import AverageMeter+from kornia.x import EarlyStopping, ModelCheckpoint+from kornia.x.utils import TrainerState+++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++ metric = {'test_monitor': AverageMeter()}+ metric['test_monitor'].avg = 1.++ cb(model, epoch=0, valid_metric=metric)+ assert cb.best_metric == 1.0+ assert (tmp_path / "model_0.pt").is_file()+++def test_callback_earlystopping(model):+ cb = EarlyStopping('test_monitor', patience=2)+ assert cb is not None+ assert cb.counter == 0++ metric = {'test_monitor': AverageMeter()}+ metric['test_monitor'].avg = 1++ state = cb(model, epoch=0, valid_metric=metric)+ assert state == TrainerState.TRAINING+ assert cb.best_score == -1+ assert cb.counter == 0++ metric['test_monitor'].avg = 2+ state = cb(model, epoch=0, valid_metric=metric)+ assert state == TrainerState.TRAINING+ assert cb.best_score == -1+ assert cb.counter == 1++ state = cb(model, epoch=0, valid_metric=metric)+ assert state == TrainerState.TERMINATE