Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Add `ObjectDetectorTrainer` (#1414)

Jian Shi34e10df97677
diff --git a/docs/source/metrics.rst b/docs/source/metrics.rst
index 4758e7c15..6936971a0 100644
--- a/docs/source/metrics.rst
+++ b/docs/source/metrics.rst
@@ -16,6 +16,12 @@ Segmentation
.. autofunction:: confusion_matrix
.. autofunction:: mean_iou
+Detection
+---------
+
+.. autofunction:: mean_average_precision
+.. autofunction:: mean_iou_bbox
+
Image Quality
-------------
diff --git a/docs/source/x.rst b/docs/source/x.rst
index 226c016db..5c5671c60 100644
--- a/docs/source/x.rst
+++ b/docs/source/x.rst
@@ -13,6 +13,7 @@ Domain trainers
.. autoclass:: ImageClassifierTrainer
.. autoclass:: SemanticSegmentationTrainer
+.. autoclass:: ObjectDetectionTrainer
Callbacks
diff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.py
index 799363126..4162a4624 100644
--- a/kornia/augmentation/container/image.py
+++ b/kornia/augmentation/container/image.py
@@ -253,7 +253,9 @@ class ImageSequential(SequentialBase):
res_mat: torch.Tensor = kornia.eye_like(3, input)
for (_, module), param in zip(named_modules, params):
if isinstance(module, (_AugmentationBase, MixAugmentationBase)):
- mat = module.compute_transformation(input, param.data) # type: ignore
+ mat: torch.Tensor = kornia.eye_like(3, input)
+ to_apply = param.data['batch_prob'] # type: ignore
+ mat[to_apply] = module.compute_transformation(input[to_apply], param.data) # type: ignore
res_mat = mat @ res_mat
elif isinstance(module, (ImageSequential,)):
mat = module.get_transformation_matrix(input, param.data) # type: ignore
diff --git a/kornia/augmentation/container/utils.py b/kornia/augmentation/container/utils.py
index a79420eda..b119eb781 100644
--- a/kornia/augmentation/container/utils.py
+++ b/kornia/augmentation/container/utils.py
@@ -94,9 +94,13 @@ class ApplyInverseImpl(ApplyInverseInterface):
"""
mat: Optional[torch.Tensor] = cls._get_transformation(input, module, param)
+ to_apply = None
+ if isinstance(module, _AugmentationBase):
+ to_apply = param.data['batch_prob'] # type: ignore
- if mat is not None:
- input = cls.apply_func(mat, input)
+ # If any inputs need to be transformed.
+ if mat is not None and to_apply is not None and to_apply.sum() != 0:
+ input[to_apply] = cls.apply_func(mat, input[to_apply])
return input, label
diff --git a/kornia/geometry/bbox.py b/kornia/geometry/bbox.py
index 65f570ea8..4a58c4a86 100644
--- a/kornia/geometry/bbox.py
+++ b/kornia/geometry/bbox.py
@@ -1,4 +1,5 @@
-from typing import Tuple
+import warnings
+from typing import Optional, Tuple
import torch
@@ -432,7 +433,9 @@ def bbox_generator3d(
return bbox
-def transform_bbox(trans_mat: torch.Tensor, boxes: torch.Tensor, mode: str = "xyxy") -> torch.Tensor:
+def transform_bbox(
+ trans_mat: torch.Tensor, boxes: torch.Tensor, mode: str = "xyxy", restore_coordinates: Optional[bool] = None
+) -> torch.Tensor:
r"""Function that applies a transformation matrix to a box or batch of boxes. Boxes must
be a tensor of the shape (N, 4) or a batch of boxes (B, N, 4) and trans_mat must be a (3, 3)
transformation matrix or a batch of transformation matrices (B, 3, 3)
@@ -443,6 +446,9 @@ def transform_bbox(trans_mat: torch.Tensor, boxes: torch.Tensor, mode: str = "xy
mode: The format in which the boxes are provided. If set to 'xyxy' the boxes are assumed to be in the format
``xmin, ymin, xmax, ymax``. If set to 'xywh' the boxes are assumed to be in the format
``xmin, ymin, width, height``
+ restore_coordinates: In case the boxes are flipped, adding a post processing step to restore the
+ coordinates to a valid bounding box.
+
Returns:
The set of transformed points in the specified mode
"""
@@ -453,14 +459,32 @@ def transform_bbox(trans_mat: torch.Tensor, boxes: torch.Tensor, mode: str = "xy
if mode not in ("xyxy", "xywh"):
raise ValueError(f"Mode must be one of 'xyxy', 'xywh'. Got {mode}")
+ # (B, 4, 2) shaped polygon boxes do not need to be restored.
+ if restore_coordinates is None and boxes.shape[-2:] != torch.Size([4, 2]):
+ warnings.warn(
+ "Previous behaviour produces incorrect box coordinates if a flip transformation performed on boxes."
+ "The previous wrong behaviour has been corrected and will be removed in the future versions."
+ "If you wish to keep the previous behaviour, please set `restore_coordinates=False`."
+ "Otherwise, set `restore_coordinates=True` as an acknowledgement."
+ )
+
# convert boxes to format xyxy
if mode == "xywh":
- boxes[..., -2] = boxes[..., 0] + boxes[..., -2] # x + w
- boxes[..., -1] = boxes[..., 1] + boxes[..., -1] # y + h
+ boxes[..., 2] = boxes[..., 0] + boxes[..., 2] # x + w
+ boxes[..., 3] = boxes[..., 1] + boxes[..., 3] # y + h
transformed_boxes: torch.Tensor = transform_points(trans_mat, boxes.view(boxes.shape[0], -1, 2))
transformed_boxes = transformed_boxes.view_as(boxes)
+ if (restore_coordinates is None or restore_coordinates) and boxes.shape[-2:] != torch.Size([4, 2]):
+ restored_boxes = transformed_boxes.clone()
+ # In case the boxes are flipped, we ensure it is ordered like left-top -> right-bot points
+ restored_boxes[..., 0] = torch.min(transformed_boxes[..., [0, 2]], dim=-1)[0]
+ restored_boxes[..., 1] = torch.min(transformed_boxes[..., [1, 3]], dim=-1)[0]
+ restored_boxes[..., 2] = torch.max(transformed_boxes[..., [0, 2]], dim=-1)[0]
+ restored_boxes[..., 3] = torch.max(transformed_boxes[..., [1, 3]], dim=-1)[0]
+ transformed_boxes = restored_boxes
+
if mode == 'xywh':
transformed_boxes[..., 2] = transformed_boxes[..., 2] - transformed_boxes[..., 0]
transformed_boxes[..., 3] = transformed_boxes[..., 3] - transformed_boxes[..., 1]
diff --git a/kornia/metrics/__init__.py b/kornia/metrics/__init__.py
index 40dada0af..ac19c5d59 100644
--- a/kornia/metrics/__init__.py
+++ b/kornia/metrics/__init__.py
@@ -1,7 +1,8 @@
from .accuracy import accuracy
from .average_meter import AverageMeter
from .confusion_matrix import confusion_matrix
-from .mean_iou import mean_iou
+from .mean_average_precision import mean_average_precision
+from .mean_iou import mean_iou, mean_iou_bbox
from .psnr import psnr
from .ssim import ssim, SSIM
@@ -10,6 +11,8 @@ __all__ = [
"AverageMeter",
"confusion_matrix",
"mean_iou",
+ "mean_iou_bbox",
+ "mean_average_precision",
"psnr",
"ssim",
"SSIM",
diff --git a/kornia/metrics/mean_average_precision.py b/kornia/metrics/mean_average_precision.py
new file mode 100644
index 000000000..70f6f8256
--- /dev/null
+++ b/kornia/metrics/mean_average_precision.py
@@ -0,0 +1,154 @@
+from typing import List, Tuple
+
+import torch
+
+from .mean_iou import mean_iou_bbox
+
+
+def mean_average_precision(
+ pred_boxes: List[torch.Tensor], pred_labels: List[torch.Tensor], pred_scores: List[torch.Tensor],
+ gt_boxes: List[torch.Tensor], gt_labels: List[torch.Tensor], n_classes: int, threshold: float = 0.5
+) -> Tuple[torch.Tensor, dict]:
+ """Calculate the Mean Average Precision (mAP) of detected objects.
+
+ Code altered from https://github.com/sgrvinod/a-PyTorch-Tutorial-to-Object-Detection/blob/master/utils.py#L271.
+ Background class (0 index) is excluded.
+
+ Args:
+ pred_boxes: a tensor list of predicted bounding boxes.
+ pred_labels: a tensor list of predicted labels.
+ pred_scores: a tensor list of predicted labels' scores.
+ gt_boxes: a tensor list of ground truth bounding boxes.
+ gt_labels: a tensor list of ground truth labels.
+ n_classes: the number of classes.
+ threshold: count as a positive if the overlap is greater than the threshold.
+
+ Returns:
+ mean average precision (mAP), list of average precisions for each class.
+
+ Examples:
+ >>> boxes, labels, scores = torch.tensor([[100, 50, 150, 100.]]), torch.tensor([1]), torch.tensor([.7])
+ >>> gt_boxes, gt_labels = torch.tensor([[100, 50, 150, 100.]]), torch.tensor([1])
+ >>> mean_average_precision([boxes], [labels], [scores], [gt_boxes], [gt_labels], 2)
+ (tensor(1.), {1: 1.0})
+ """
+ # these are all lists of tensors of the same length, i.e. number of images
+ if not len(pred_boxes) == len(pred_labels) == len(pred_scores) == len(gt_boxes) == len(gt_labels):
+ raise AssertionError
+
+ # Store all (true) objects in a single continuous tensor while keeping track of the image it is from
+ gt_images = []
+ for i, labels in enumerate(gt_labels):
+ gt_images.extend([i] * labels.size(0))
+ # (n_objects), n_objects is the total no. of objects across all images
+ _gt_boxes = torch.cat(gt_boxes, dim=0) # (n_objects, 4)
+ _gt_labels = torch.cat(gt_labels, dim=0) # (n_objects)
+ _gt_images = torch.tensor(gt_images, device=_gt_boxes.device, dtype=torch.long)
+
+ if not _gt_images.size(0) == _gt_boxes.size(0) == _gt_labels.size(0):
+ raise AssertionError
+
+ # Store all detections in a single continuous tensor while keeping track of the image it is from
+ pred_images = []
+ for i, labels in enumerate(pred_labels):
+ pred_images.extend([i] * labels.size(0))
+ _pred_boxes = torch.cat(pred_boxes, dim=0) # (n_detections, 4)
+ _pred_labels = torch.cat(pred_labels, dim=0) # (n_detections)
+ _pred_scores = torch.cat(pred_scores, dim=0) # (n_detections)
+ _pred_images = torch.tensor(pred_images, device=_pred_boxes.device, dtype=torch.long) # (n_detections)
+
+ if not _pred_images.size(0) == _pred_boxes.size(0) == _pred_labels.size(0) == _pred_scores.size(0):
+ raise AssertionError
+
+ # Calculate APs for each class (except background)
+ average_precisions = torch.zeros(
+ (n_classes - 1), device=_pred_boxes.device, dtype=_pred_boxes.dtype) # (n_classes - 1)
+ for c in range(1, n_classes):
+ # Extract only objects with this class
+ gt_class_images = _gt_images[_gt_labels == c] # (n_class_objects)
+ gt_class_boxes = _gt_boxes[_gt_labels == c] # (n_class_objects, 4)
+
+ # Keep track of which true objects with this class have already been 'detected'
+ # (n_class_objects)
+ gt_class_boxes_detected = torch.zeros(
+ (gt_class_images.size(0)), dtype=torch.uint8, device=gt_class_images.device)
+
+ # Extract only detections with this class
+ pred_class_images = _pred_images[_pred_labels == c] # (n_class_detections)
+ pred_class_boxes = _pred_boxes[_pred_labels == c] # (n_class_detections, 4)
+ pred_class_scores = _pred_scores[_pred_labels == c] # (n_class_detections)
+ n_class_detections = pred_class_boxes.size(0)
+ if n_class_detections == 0:
+ continue
+
+ # Sort detections in decreasing order of confidence/scores
+ pred_class_scores, sort_ind = torch.sort(pred_class_scores, dim=0, descending=True) # (n_class_detections)
+ pred_class_images = pred_class_images[sort_ind] # (n_class_detections)
+ pred_class_boxes = pred_class_boxes[sort_ind] # (n_class_detections, 4)
+
+ # In the order of decreasing scores, check if true or false positive
+ gt_positives = torch.zeros(
+ (n_class_detections,), dtype=pred_class_boxes.dtype, device=pred_class_boxes.device) # (n_class_detections)
+ false_positives = torch.zeros(
+ (n_class_detections,), dtype=pred_class_boxes.dtype, device=pred_class_boxes.device) # (n_class_detections)
+ for d in range(n_class_detections):
+ this_detection_box = pred_class_boxes[d].unsqueeze(0) # (1, 4)
+ this_image = pred_class_images[d] # (), scalar
+
+ # Find objects in the image with this class, their difficulties, and whether they have been detected before
+ object_boxes = gt_class_boxes[gt_class_images == this_image] # (n_class_objects_in_img)
+ # If no such object in this image, then the detection is a false positive
+ if object_boxes.size(0) == 0:
+ false_positives[d] = 1
+ continue
+
+ # Find maximum overlap of this detection with objects in this image of this class
+ overlaps = mean_iou_bbox(this_detection_box, object_boxes) # (1, n_class_objects_in_img)
+ max_overlap, ind = torch.max(overlaps.squeeze(0), dim=0) # (), () - scalars
+
+ # 'ind' is the index of the object in these image-level tensors 'object_boxes', 'object_difficulties'
+ # In the original class-level tensors 'gt_class_boxes', etc., 'ind' corresponds to object with index...
+ original_ind = torch.tensor(
+ range(gt_class_boxes.size(0)), device=gt_class_boxes_detected.device, dtype=torch.long
+ )[gt_class_images == this_image][ind]
+ # We need 'original_ind' to update 'gt_class_boxes_detected'
+
+ # If the maximum overlap is greater than the threshold of 0.5, it's a match
+ if max_overlap.item() > threshold:
+ # If this object has already not been detected, it's a true positive
+ if gt_class_boxes_detected[original_ind] == 0:
+ gt_positives[d] = 1
+ gt_class_boxes_detected[original_ind] = 1 # this object has now been detected/accounted for
+ # Otherwise, it's a false positive (since this object is already accounted for)
+ else:
+ false_positives[d] = 1
+ # Otherwise, the detection occurs in a different location than the actual object, and is a false positive
+ else:
+ false_positives[d] = 1
+
+ # Compute cumulative precision and recall at each detection in the order of decreasing scores
+ cumul_gt_positives = torch.cumsum(gt_positives, dim=0) # (n_class_detections)
+ cumul_false_positives = torch.cumsum(false_positives, dim=0) # (n_class_detections)
+ cumul_precision = cumul_gt_positives / (
+ cumul_gt_positives + cumul_false_positives + 1e-10) # (n_class_detections)
+ cumul_recall = cumul_gt_positives / _gt_boxes.size(0) # (n_class_detections)
+
+ # Find the mean of the maximum of the precisions corresponding to recalls above the threshold 't'
+ recall_thresholds = torch.arange(start=0, end=1.1, step=.1).tolist() # (11)
+ precisions = torch.zeros(
+ (len(recall_thresholds)), device=_gt_boxes.device, dtype=_gt_boxes.dtype) # (11)
+ for i, t in enumerate(recall_thresholds):
+ recalls_above_t = cumul_recall >= t
+ if recalls_above_t.any():
+ precisions[i] = cumul_precision[recalls_above_t].max()
+ else:
+ precisions[i] = 0.
+ average_precisions[c - 1] = precisions.mean() # c is in [1, n_classes - 1]
+
+ # Calculate Mean Average Precision (mAP)
+ mean_ap = average_precisions.mean()
+
+ # Keep class-wise average precisions in a dictionary
+ ap_dict = {c + 1: v for c, v in enumerate(average_precisions.tolist())}
+
+ return mean_ap, ap_dict
diff --git a/kornia/metrics/mean_iou.py b/kornia/metrics/mean_iou.py
index 9d9b4b1cd..2aebf9938 100644
--- a/kornia/metrics/mean_iou.py
+++ b/kornia/metrics/mean_iou.py
@@ -19,7 +19,7 @@ def mean_iou(input: torch.Tensor, target: torch.Tensor, num_classes: int, eps: f
num_classes: total possible number of classes in target.
Returns:
- ta tensor representing the mean intersection-over union
+ a tensor representing the mean intersection-over union
with shape :math:`(B, K)` where K is the number of classes.
Example:
@@ -58,3 +58,45 @@ def mean_iou(input: torch.Tensor, target: torch.Tensor, num_classes: int, eps: f
# prediction or ground truth are taken into account.
ious = (conf_mat_diag + eps) / (denominator + eps)
return ious
+
+
+def mean_iou_bbox(boxes_1: torch.Tensor, boxes_2: torch.Tensor) -> torch.Tensor:
+ """Compute the IoU of the cartisian product of two sets of boxes.
+
+ Each box in each set shall be (x1, y1, x2, y2).
+
+ Args:
+ boxes_1: a tensor of bounding boxes in :math:`(B1, 4)`.
+ boxes_2: a tensor of bounding boxes in :math:`(B2, 4)`.
+
+ Returns:
+ a tensor in dimensions :math:`(B1, B2)`, representing the
+ intersection of each of the boxes in set 1 with respect to each of the boxes in set 2.
+
+ Example:
+ >>> boxes_1 = torch.tensor([[40, 40, 60, 60], [30, 40, 50, 60]])
+ >>> boxes_2 = torch.tensor([[40, 50, 60, 70], [30, 40, 40, 50]])
+ >>> mean_iou_bbox(boxes_1, boxes_2)
+ tensor([[0.3333, 0.0000],
+ [0.1429, 0.2500]])
+ """
+ # TODO: support more box types. e.g. xywh,
+ if not (((boxes_1[:, 2] - boxes_1[:, 0]) > 0).all() or ((boxes_1[:, 3] - boxes_1[:, 1]) > 0).all()):
+ raise AssertionError("Boxes_1 does not follow (x1, y1, x2, y2) format.")
+ if not (((boxes_2[:, 2] - boxes_2[:, 0]) > 0).all() or ((boxes_2[:, 3] - boxes_2[:, 1]) > 0).all()):
+ raise AssertionError("Boxes_2 does not follow (x1, y1, x2, y2) format.")
+ # find intersection
+ lower_bounds = torch.max(boxes_1[:, :2].unsqueeze(1), boxes_2[:, :2].unsqueeze(0)) # (n1, n2, 2)
+ upper_bounds = torch.min(boxes_1[:, 2:].unsqueeze(1), boxes_2[:, 2:].unsqueeze(0)) # (n1, n2, 2)
+ intersection_dims = torch.clamp(upper_bounds - lower_bounds, min=0) # (n1, n2, 2)
+ intersection = intersection_dims[:, :, 0] * intersection_dims[:, :, 1] # (n1, n2)
+
+ # Find areas of each box in both sets
+ areas_set_1 = (boxes_1[:, 2] - boxes_1[:, 0]) * (boxes_1[:, 3] - boxes_1[:, 1]) # (n1)
+ areas_set_2 = (boxes_2[:, 2] - boxes_2[:, 0]) * (boxes_2[:, 3] - boxes_2[:, 1]) # (n2)
+
+ # Find the union
+ # PyTorch auto-broadcasts singleton dimensions
+ union = areas_set_1.unsqueeze(1) + areas_set_2.unsqueeze(0) - intersection # (n1, n2)
+
+ return intersection / union # (n1, n2)
diff --git a/kornia/x/__init__.py b/kornia/x/__init__.py
index 2fb043a12..7642fb692 100644
--- a/kornia/x/__init__.py
+++ b/kornia/x/__init__.py
@@ -1,4 +1,4 @@
from .callbacks import EarlyStopping, ModelCheckpoint
from .trainer import Trainer
-from .trainer_classification import ImageClassifierTrainer, SemanticSegmentationTrainer
+from .trainers import ImageClassifierTrainer, ObjectDetectionTrainer, SemanticSegmentationTrainer
from .utils import Configuration, Lambda, TrainerState
diff --git a/kornia/x/trainer.py b/kornia/x/trainer.py
index 9d33bfdf3..3bbef51fc 100644
--- a/kornia/x/trainer.py
+++ b/kornia/x/trainer.py
@@ -1,5 +1,5 @@
import logging
-from typing import Callable, Dict
+from typing import Callable, Dict, Optional
import torch
import torch.nn as nn
@@ -14,7 +14,7 @@ except ImportError:
from kornia.metrics import AverageMeter
-from .utils import Configuration, TrainerState
+from .utils import Configuration, StatsTracker, TrainerState
callbacks_whitelist = [
# high level functions
@@ -63,7 +63,7 @@ class Trainer:
model: nn.Module,
train_dataloader: DataLoader,
valid_dataloader: DataLoader,
- criterion: nn.Module,
+ criterion: Optional[nn.Module],
optimizer: torch.optim.Optimizer,
scheduler: torch.optim.lr_scheduler.CosineAnnealingLR,
config: Configuration,
@@ -79,7 +79,7 @@ class Trainer:
self.model = self.accelerator.prepare(model)
self.train_dataloader = self.accelerator.prepare(train_dataloader)
self.valid_dataloader = self.accelerator.prepare(valid_dataloader)
- self.criterion = criterion.to(self.device)
+ self.criterion = None if criterion is None else criterion.to(self.device)
self.optimizer = self.accelerator.prepare(optimizer)
self.scheduler = scheduler
self.config = config
@@ -116,13 +116,13 @@ class Trainer:
sample = self.augmentations(sample)
sample = self.on_before_model(sample)
# make the actual inference
- output = self.model(sample["input"])
+ output = self.on_model(self.model, sample)
self.on_after_model(output, sample) # for debugging purposes
- loss = self.criterion(output, sample["target"])
+ loss = self.compute_loss(output, sample["target"])
self.backward(loss)
self.optimizer.step()
- losses.update(loss.item(), sample["target"].shape[0])
+ losses.update(loss.item(), len(sample["input"]))
if sample_id % 50 == 0:
self._logger.info(
@@ -158,8 +158,33 @@ class Trainer:
# events stubs
- def evaluate(self):
- ...
+ @torch.no_grad()
+ def evaluate(self) -> dict:
+ self.model.eval()
+ stats = StatsTracker()
+ 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.on_model(self.model, sample)
+ self.on_after_model(out, sample)
+
+ batch_size: int = len(sample["input"])
+ # measure accuracy and record loss
+ # Loss computation
+ if self.criterion is not None:
+ val_loss = self.compute_loss(out, sample["target"])
+ stats.update('losses', val_loss.item(), batch_size)
+ stats.update_from_dict(self.compute_metrics(out, sample['target']), batch_size)
+
+ if sample_id % 10 == 0:
+ self._logger.info(
+ f"Test: {sample_id}/{len(self.valid_dataloader)} {stats}"
+ )
+
+ return stats.as_dict()
def on_epoch_start(self, *args, **kwargs):
...
@@ -170,9 +195,21 @@ class Trainer:
def augmentations(self, x: dict) -> dict:
return x
+ def compute_metrics(self, *args: torch.Tensor) -> Dict[str, float]:
+ """Compute metrics during the evaluation."""
+ return {}
+
+ def compute_loss(self, *args: torch.Tensor) -> torch.Tensor:
+ if self.criterion is None:
+ raise RuntimeError("`criterion` should not be None.")
+ return self.criterion(*args)
+
def on_before_model(self, x: dict) -> dict:
return x
+ def on_model(self, model, sample: dict):
+ return model(sample["input"])
+
def on_after_model(self, output: torch.Tensor, sample: dict):
...
diff --git a/kornia/x/trainer_classification.py b/kornia/x/trainer_classification.py
deleted file mode 100644
index a50fa7cf9..000000000
--- a/kornia/x/trainer_classification.py
+++ /dev/null
@@ -1,88 +0,0 @@
-import torch
-
-from kornia.metrics import accuracy, AverageMeter, mean_iou
-
-from .trainer import Trainer
-
-
-class ImageClassifierTrainer(Trainer):
- """Module to be used for Image Classification purposes.
-
- The module subclasses :py:class:`~kornia.x.Trainer` and overrides the
- :py:func:`~kornia.x.Trainer.evaluate` function implementing a standard
- :py:func:`~kornia.metrics.accuracy` topk@[1, 5].
-
- .. seealso::
- Learn how to use this class in the following
- `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):
- 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)
- # Forward
- out = self.model(sample["input"])
- # Loss computation
- val_loss = self.criterion(out, sample["target"])
-
- # measure accuracy and record loss
- 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(
- f"Test: {sample_id}/{len(self.valid_dataloader)} "
- f"Loss: {stats['losses'].val:.2f} {stats['losses'].avg:.2f} "
- f"Acc@1: {stats['top1'].val:.2f} {stats['top1'].val:.2f} "
- f"Acc@5: {stats['top5'].val:.2f} {stats['top5'].val:.2f} "
- )
-
- 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:func:`~kornia.x.Trainer.evaluate` function implementing IoU :py:func:`~kornia.metrics.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 stats
diff --git a/kornia/x/trainers.py b/kornia/x/trainers.py
new file mode 100644
index 000000000..e8a2d3cfc
--- /dev/null
+++ b/kornia/x/trainers.py
@@ -0,0 +1,111 @@
+from typing import Callable, Dict, Optional
+
+import torch
+import torch.nn as nn
+from torch.utils.data import DataLoader
+
+from kornia.metrics import accuracy, mean_average_precision, mean_iou
+
+from .trainer import Trainer
+from .utils import Configuration
+
+
+class ImageClassifierTrainer(Trainer):
+ """Module to be used for image classification purposes.
+
+ The module subclasses :py:class:`~kornia.x.Trainer` and overrides the
+ :py:func:`~kornia.x.Trainer.evaluate` function implementing a standard
+ :py:func:`~kornia.metrics.accuracy` topk@[1, 5].
+
+ .. seealso::
+ Learn how to use this class in the following
+ `example <https://github.com/kornia/kornia/blob/master/examples/train/image_classifier/>`__.
+ """
+
+ def compute_metrics(self, *args: torch.Tensor) -> Dict[str, float]:
+ if len(args) != 2:
+ raise AssertionError
+ out, target = args
+ acc1, acc5 = accuracy(out, target, topk=(1, 5))
+ return dict(top1=acc1.item(), top5=acc5.item())
+
+
+class SemanticSegmentationTrainer(Trainer):
+ """Module to be used for semantic segmentation purposes.
+
+ The module subclasses :py:class:`~kornia.x.Trainer` and overrides the
+ :py:func:`~kornia.x.Trainer.evaluate` function implementing IoU :py:func:`~kornia.metrics.mean_iou`.
+
+ .. seealso::
+ Learn how to use this class in the following
+ `example <https://github.com/kornia/kornia/blob/master/examples/train/semantic_segmentation/>`__.
+ """
+
+ def compute_metrics(self, *args: torch.Tensor) -> Dict[str, float]:
+ if len(args) != 2:
+ raise AssertionError
+ out, target = args
+ iou = mean_iou(out.argmax(1), target, out.shape[1]).mean()
+ return dict(iou=iou.item())
+
+
+class ObjectDetectionTrainer(Trainer):
+ """Module to be used for object detection purposes.
+
+ The module subclasses :py:class:`~kornia.x.Trainer` and overrides the
+ :py:func:`~kornia.x.Trainer.evaluate` function implementing IoU :py:func:`~kornia.metrics.mean_iou`.
+
+ .. seealso::
+ Learn how to use this class in the following
+ `example <https://github.com/kornia/kornia/blob/master/examples/train/object_detection/>`__.
+ """
+ def __init__(
+ self,
+ model: nn.Module,
+ train_dataloader: DataLoader,
+ valid_dataloader: DataLoader,
+ criterion: Optional[nn.Module],
+ optimizer: torch.optim.Optimizer,
+ scheduler: torch.optim.lr_scheduler.CosineAnnealingLR,
+ config: Configuration,
+ num_classes: int,
+ callbacks: Dict[str, Callable] = None,
+ loss_computed_by_model: Optional[bool] = None,
+ ) -> None:
+ if callbacks is None:
+ callbacks = {}
+ super().__init__(
+ model, train_dataloader, valid_dataloader, criterion, optimizer, scheduler, config, callbacks
+ )
+ # TODO: auto-detect if the model is from TorchVision
+ self.loss_computed_by_model = loss_computed_by_model
+ self.num_classes = num_classes
+
+ def on_model(self, model: nn.Module, sample: dict):
+ if self.loss_computed_by_model and model.training:
+ return model(sample["input"], sample["target"])
+ return model(sample["input"])
+
+ def compute_loss(self, *args: torch.Tensor) -> torch.Tensor:
+ if self.loss_computed_by_model:
+ return torch.stack(list(args[0])).sum()
+ if self.criterion is None:
+ raise RuntimeError("`criterion` should not be None if `loss_computed_by_model` is False.")
+ return self.criterion(*args)
+
+ def compute_metrics(self, *args: torch.Tensor) -> Dict[str, float]:
+ if (
+ isinstance(args[0], dict) and "boxes" in args[0] and "labels" in args[0] and "scores" in args[0]
+ and isinstance(args[1], dict) and "boxes" in args[1] and "labels" in args[1]
+ ):
+ mAP, _ = mean_average_precision(
+ [a['boxes'] for a in args[0]],
+ [a['labels'] for a in args[0]],
+ [a['scores'] for a in args[0]],
+ [a['boxes'] for a in args[1]],
+ [a['labels'] for a in args[1]],
+ n_classes=self.num_classes,
+ threshold=0.000001
+ )
+ return {'mAP': mAP.item()}
+ return super().compute_metrics(*args)
diff --git a/kornia/x/utils.py b/kornia/x/utils.py
index 0a24180b9..e54003eb6 100644
--- a/kornia/x/utils.py
+++ b/kornia/x/utils.py
@@ -1,9 +1,12 @@
# TODO: remove the type: ignore in below after deprecating python 3.6
from dataclasses import dataclass, field # type: ignore
from enum import Enum
+from typing import Dict
import torch.nn as nn
+from kornia.metrics.average_meter import AverageMeter
+
# import yaml # type: ignore
@@ -56,3 +59,31 @@ class Lambda(nn.Module):
def forward(self, x):
return self.fcn(x)
+
+
+class StatsTracker:
+ """Stats tracker for computing metrics on the fly."""
+ def __init__(self) -> None:
+ self._stats: Dict[str, AverageMeter] = {}
+
+ @property
+ def stats(self,):
+ return self._stats
+
+ def update(self, key: str, val: float, batch_size: int) -> None:
+ """Update the stats by the key value pair."""
+ if key not in self._stats:
+ self._stats[key] = AverageMeter()
+ self._stats[key].update(val, batch_size)
+
+ def update_from_dict(self, dic: Dict[str, float], batch_size: int) -> None:
+ """Update the stats by the dict."""
+ for k, v in dic.items():
+ self.update(k, v, batch_size)
+
+ def __repr__(self) -> str:
+ return " ".join([f"{k.upper()}: {v.val:.2f} {v.val:.2f} " for k, v in self._stats.items()])
+
+ def as_dict(self) -> Dict[str, AverageMeter]:
+ """Return the dict format."""
+ return self._stats
diff --git a/test/augmentation/test_container.py b/test/augmentation/test_container.py
index 95d8b424a..102d9910b 100644
--- a/test/augmentation/test_container.py
+++ b/test/augmentation/test_container.py
@@ -292,8 +292,8 @@ class TestAugmentationSequential:
K.RandomHorizontalFlip(p=1.0), data_keys=["input", "bbox"], return_transform=False, same_on_batch=False
)
- out_ver = aug_ver(inp, bbox)
- out_hor = aug_hor(inp, bbox)
+ out_ver = aug_ver(inp.clone(), bbox.clone())
+ out_hor = aug_hor(inp.clone(), bbox.clone())
assert_close(out_ver[1], expected_bbox_vertical_flip)
assert_close(out_hor[1], expected_bbox_horizontal_flip)
diff --git a/test/geometry/test_bbox.py b/test/geometry/test_bbox.py
index a28f2cf7c..d311ff344 100644
--- a/test/geometry/test_bbox.py
+++ b/test/geometry/test_bbox.py
@@ -69,11 +69,11 @@ class TestTransformBoxes2D:
boxes = torch.tensor([[139.2640, 103.0150, 397.3120, 410.5225]], device=device, dtype=dtype)
- expected = torch.tensor([[372.7360, 103.0150, 114.6880, 410.5225]], device=device, dtype=dtype)
+ expected = torch.tensor([[114.6880, 103.0150, 372.7360, 410.5225]], device=device, dtype=dtype)
trans_mat = torch.tensor([[[-1.0, 0.0, 512.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
- out = transform_bbox(trans_mat, boxes)
+ out = transform_bbox(trans_mat, boxes, restore_coordinates=True)
assert_allclose(out, expected, atol=1e-4, rtol=1e-4)
def test_transform_multiple_boxes(self, device, dtype):
@@ -94,10 +94,10 @@ class TestTransformBoxes2D:
expected = torch.tensor(
[
[
- [372.7360, 103.0150, 114.6880, 410.5225],
- [510.9760, 80.5547, 0.0000, 512.0000],
- [346.7947, 262.1440, 1.3653, 508.9280],
- [392.1920, 144.2067, 254.9760, 410.1292],
+ [114.6880, 103.0150, 372.7360, 410.5225],
+ [0.0000, 80.5547, 510.9760, 512.0000],
+ [1.3652, 262.1440, 346.7947, 508.9280],
+ [254.9760, 144.2067, 392.1920, 410.1292],
],
[
[139.2640, 103.0150, 397.3120, 410.5225],
@@ -119,7 +119,7 @@ class TestTransformBoxes2D:
dtype=dtype,
)
- out = transform_bbox(trans_mat, boxes)
+ out = transform_bbox(trans_mat, boxes, restore_coordinates=True)
assert_allclose(out, expected, atol=1e-4, rtol=1e-4)
def test_transform_boxes_wh(self, device, dtype):
@@ -137,10 +137,10 @@ class TestTransformBoxes2D:
expected = torch.tensor(
[
- [372.7360, 103.0150, -258.0480, 307.5075],
- [510.9760, 80.5547, -510.9760, 431.4453],
- [346.7947, 262.1440, -345.4293, 246.7840],
- [392.1920, 144.2067, -137.2160, 265.9225],
+ [114.6880, 103.0150, 258.0480, 307.5075],
+ [0.0000, 80.5547, 510.9760, 431.4453],
+ [1.3654, 262.1440, 345.4293, 246.7840],
+ [254.9760, 144.2067, 137.2160, 265.9225]
],
device=device,
dtype=dtype,
@@ -148,7 +148,7 @@ class TestTransformBoxes2D:
trans_mat = torch.tensor([[[-1.0, 0.0, 512.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
- out = transform_bbox(trans_mat, boxes, mode='xywh')
+ out = transform_bbox(trans_mat, boxes, mode='xywh', restore_coordinates=True)
assert_allclose(out, expected, atol=1e-4, rtol=1e-4)
def test_gradcheck(self, device, dtype):
@@ -169,7 +169,7 @@ class TestTransformBoxes2D:
trans_mat = utils.tensor_to_gradcheck_var(trans_mat)
boxes = utils.tensor_to_gradcheck_var(boxes)
- assert gradcheck(transform_bbox, (trans_mat, boxes), raise_exception=True)
+ assert gradcheck(transform_bbox, (trans_mat, boxes, "xyxy", True), raise_exception=True)
def test_jit(self, device, dtype):
boxes = torch.tensor([[139.2640, 103.0150, 258.0480, 307.5075]], device=device, dtype=dtype)
diff --git a/test/test_metrics.py b/test/test_metrics.py
index 9a46a5185..cf8e54c4d 100644
--- a/test/test_metrics.py
+++ b/test/test_metrics.py
@@ -1,3 +1,4 @@
+import pytest
import torch
import kornia
@@ -193,3 +194,31 @@ class TestPsnr:
expected = torch.tensor(20.0, device=device, dtype=dtype)
actual = kornia.metrics.psnr(input, 1.2 * input, 2.0)
assert_close(actual, expected)
+
+
+class TestMeanAveragePrecision:
+ def test_smoke(self, device, dtype):
+ boxes = torch.tensor([[100, 50, 150, 100.]], device=device, dtype=dtype)
+ labels = torch.tensor([1], device=device, dtype=torch.long)
+ scores = torch.tensor([.7], device=device, dtype=dtype)
+
+ gt_boxes = torch.tensor([[100, 50, 150, 100.]], device=device, dtype=dtype)
+ gt_labels = torch.tensor([1], device=device, dtype=torch.long)
+
+ mean_ap = kornia.metrics.mean_average_precision(
+ [boxes], [labels], [scores], [gt_boxes], [gt_labels], 2)
+
+ assert_close(mean_ap[0], torch.tensor(1., device=device, dtype=dtype))
+ assert_close(mean_ap[1][1], 1.0)
+
+ def test_raise(self, device, dtype):
+ boxes = torch.tensor([[100, 50, 150, 100.]], device=device, dtype=dtype)
+ labels = torch.tensor([1], device=device, dtype=torch.long)
+ scores = torch.tensor([.7], device=device, dtype=dtype)
+
+ gt_boxes = torch.tensor([[100, 50, 150, 100.]], device=device, dtype=dtype)
+ gt_labels = torch.tensor([1], device=device, dtype=torch.long)
+
+ with pytest.raises(AssertionError):
+ _ = kornia.metrics.mean_average_precision(
+ boxes[0], [labels], [scores], [gt_boxes], [gt_labels], 2)
diff --git a/test/x/test_detection.py b/test/x/test_detection.py
new file mode 100644
index 000000000..a250b8d8d
--- /dev/null
+++ b/test/x/test_detection.py
@@ -0,0 +1,76 @@
+import pytest
+import torch
+import torch.nn as nn
+from torch.utils.data import Dataset
+
+from kornia.x import Configuration, ObjectDetectionTrainer
+
+
+class DummyDatasetDetection(Dataset):
+ def __len__(self):
+ return 10
+
+ def __getitem__(self, index):
+ return torch.ones(3, 32, 32), torch.tensor([10., 10., 15., 15.])
+
+
+class DummyModel(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.model = nn.Sequential(
+ nn.Conv2d(3, 1, kernel_size=16, stride=16),
+ nn.Flatten()
+ )
+
+ def forward(self, x, y=None):
+ return self.model(x)
+
+
+def model():
+ return DummyModel()
+
+
+def dataloader():
+ dataset = DummyDatasetDetection()
+ return torch.utils.data.DataLoader(dataset, batch_size=1)
+
+
+def criterion():
+ return nn.MSELoss()
+
+
+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 TestObjectDetectionTrainer:
+ @pytest.mark.parametrize("loss_computed_by_model", [True, False])
+ def test_fit(self, model, dataloader, criterion, optimizer, scheduler, configuration, loss_computed_by_model):
+ trainer = ObjectDetectionTrainer(
+ model, dataloader, dataloader, criterion, optimizer, scheduler, configuration, num_classes=3,
+ loss_computed_by_model=loss_computed_by_model
+ )
+ trainer.fit()
+
+ def test_exception(self, model, dataloader, criterion, optimizer, scheduler, configuration):
+ with pytest.raises(ValueError):
+ ObjectDetectionTrainer(
+ model, dataloader, dataloader, criterion, optimizer, scheduler, configuration, num_classes=3,
+ callbacks={'frodo': None}
+ )