π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Added container operation weights and OneOf documentation (#1443)
Jian Shi2837ea2fdd27
diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.pyindex ba1a9c028..d3c6fd975 100644--- a/kornia/augmentation/container/augment.py+++ b/kornia/augmentation/container/augment.py@@ -82,7 +82,6 @@ class AugmentationSequential(ImageSequential):This example demonstrates the integration of VideoSequential and AugmentationSequential.- Examples:>>> import kornia>>> input = torch.randn(2, 3, 5, 6)[None]>>> bbox = torch.tensor([[@@ -102,6 +101,32 @@ class AugmentationSequential(ImageSequential):>>> out = aug_list(input, input, bbox, points)>>> [o.shape for o in out][torch.Size([1, 2, 3, 5, 6]), torch.Size([1, 2, 3, 5, 6]), torch.Size([1, 2, 4, 2]), torch.Size([1, 2, 1, 2])]++ Perform ``OneOf`` transformation with ``random_apply=1`` and ``random_apply_weights`` in ``AugmentationSequential``.++ >>> import kornia+ >>> input = torch.randn(2, 3, 5, 6)[None]+ >>> bbox = torch.tensor([[+ ... [1., 1.],+ ... [2., 1.],+ ... [2., 2.],+ ... [1., 2.],+ ... ]]).expand(2, -1, -1)[None]+ >>> points = torch.tensor([[[1., 1.]]]).expand(2, -1, -1)[None]+ >>> aug_list = AugmentationSequential(+ ... VideoSequential(+ ... kornia.augmentation.RandomAffine(360, p=1.0),+ ... ),+ ... VideoSequential(+ ... kornia.augmentation.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),+ ... ),+ ... data_keys=["input", "mask", "bbox", "keypoints"],+ ... random_apply=1,+ ... random_apply_weights=[0.5, 0.3]+ ... )+ >>> out = aug_list(input, input, bbox, points)+ >>> [o.shape for o in out]+ [torch.Size([1, 2, 3, 5, 6]), torch.Size([1, 2, 3, 5, 6]), torch.Size([1, 2, 4, 2]), torch.Size([1, 2, 1, 2])]"""def __init__(@@ -112,6 +137,7 @@ class AugmentationSequential(ImageSequential):return_transform: Optional[bool] = None,keepdim: Optional[bool] = None,random_apply: Union[int, bool, Tuple[int, int]] = False,+ random_apply_weights: Optional[List[float]] = None,) -> None:super().__init__(*args,@@ -119,6 +145,7 @@ class AugmentationSequential(ImageSequential):return_transform=return_transform,keepdim=keepdim,random_apply=random_apply,+ random_apply_weights=random_apply_weights,)self.data_keys = [DataKey.get(inp) for inp in data_keys]diff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.pyindex 97b42a277..5aaa8e813 100644--- a/kornia/augmentation/container/image.py+++ b/kornia/augmentation/container/image.py@@ -31,12 +31,14 @@ class ImageSequential(SequentialBase):keepdim: whether to keep the output shape the same as input (True) or broadcast itto the batch form (False). If None, it will not overwrite the function-wise settings.random_apply: randomly select a sublist (order agnostic) of args to- apply transformation.+ apply transformation. The selection probablity aligns to the ``random_apply_weights``.If int, a fixed number of transformations will be selected.If (a,), x number of transformations (a <= x <= len(args)) will be selected.If (a, b), x number of transformations (a <= x <= b) will be selected.If True, the whole list of args will be processed as a sequence in a random order.If False, the whole list of args will be processed as a sequence in original order.+ random_apply_weights: a list of selection weights for each operation. The length shall be as+ same as the number of operations. By default, operations are sampled uniformly... note::Transformation matrix returned only considers the transformation applied in ``kornia.augmentation`` module.@@ -68,6 +70,22 @@ class ImageSequential(SequentialBase):>>> out2, lab2 = aug_list(input, label=label, params=aug_list._params)>>> torch.equal(out[0], out2[0]), torch.equal(out[1], out2[1]), torch.equal(lab[1], lab2[1])(True, True, True)++ Perform ``OneOf`` transformation with ``random_apply=1`` and ``random_apply_weights`` in ``ImageSequential``.++ >>> import kornia+ >>> input = torch.randn(2, 3, 5, 6)+ >>> aug_list = ImageSequential(+ ... kornia.color.BgrToRgb(),+ ... kornia.augmentation.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),+ ... kornia.filters.MedianBlur((3, 3)),+ ... kornia.augmentation.RandomAffine(360, p=1.0),+ ... random_apply=1,+ ... random_apply_weights=[0.5, 0.3, 0.2, 0.5]+ ... )+ >>> out= aug_list(input)+ >>> out.shape+ torch.Size([2, 3, 5, 6])"""def __init__(@@ -77,11 +95,18 @@ class ImageSequential(SequentialBase):return_transform: Optional[bool] = None,keepdim: Optional[bool] = None,random_apply: Union[int, bool, Tuple[int, int]] = False,+ random_apply_weights: Optional[List[float]] = None,if_unsupported_ops: str = 'raise') -> None:super().__init__(*args, same_on_batch=same_on_batch, return_transform=return_transform, keepdim=keepdim)self.random_apply: Union[Tuple[int, int], bool] = self._read_random_apply(random_apply, len(args))+ if random_apply_weights is not None and len(random_apply_weights) != len(self):+ raise ValueError(+ "The length of `random_apply_weights` must be as same as the number of operations."+ f"Got {len(random_apply_weights)} and {len(self)}."+ )+ self.random_apply_weights = torch.as_tensor(random_apply_weights or torch.ones((len(self),)))self.return_label: Optional[bool] = Noneself.apply_inverse_func: Type[ApplyInverseInterface] = InputApplyInverseself.if_unsupported_ops = if_unsupported_ops@@ -123,7 +148,7 @@ class ImageSequential(SequentialBase):Mix augmentations (e.g. RandomMixUp) will be only applied once even in a random forward."""num_samples = int(torch.randint(*self.random_apply, (1,)).item()) # type: ignore- multinomial_weights = torch.ones((len(self),))+ multinomial_weights = self.random_apply_weights.clone()# Mix augmentation can only be applied once per forwardmix_indices = self.get_mix_augmentation_indices(self.named_children())# kick out the mix augmentationsdiff --git a/kornia/augmentation/container/patch.py b/kornia/augmentation/container/patch.pyindex c04171fef..88bbd6214 100644--- a/kornia/augmentation/container/patch.py+++ b/kornia/augmentation/container/patch.py@@ -86,6 +86,27 @@ class PatchSequential(ImageSequential):>>> out1 = seq(input, params=seq._params)>>> torch.equal(out, out1)True++ Perform ``OneOf`` transformation with ``random_apply=1`` and ``random_apply_weights`` in ``PatchSequential``.++ >>> import kornia+ >>> input = torch.randn(2, 3, 224, 224)+ >>> seq = PatchSequential(+ ... ImageSequential(+ ... K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=0.5),+ ... K.RandomPerspective(0.2, p=0.5),+ ... K.RandomSolarize(0.1, 0.1, p=0.5),+ ... ),+ ... K.RandomAffine(360, p=1.0),+ ... K.RandomSolarize(0.1, 0.1, p=0.1),+ ... grid_size=(2,2),+ ... patchwise_apply=False,+ ... random_apply=1,+ ... random_apply_weights=[0.5, 0.3, 0.8]+ ... )+ >>> out = seq(input)+ >>> out.shape+ torch.Size([2, 3, 224, 224])"""def __init__(@@ -97,6 +118,7 @@ class PatchSequential(ImageSequential):keepdim: Optional[bool] = None,patchwise_apply: bool = True,random_apply: Union[int, bool, Tuple[int, int]] = False,+ random_apply_weights: Optional[List[float]] = None,) -> None:_random_apply: Optional[Union[int, Tuple[int, int]]]@@ -116,7 +138,8 @@ class PatchSequential(ImageSequential):else:_random_apply = random_applysuper().__init__(- *args, same_on_batch=same_on_batch, return_transform=False, keepdim=keepdim, random_apply=_random_apply+ *args, same_on_batch=same_on_batch, return_transform=False, keepdim=keepdim, random_apply=_random_apply,+ random_apply_weights=random_apply_weights)if padding not in ("same", "valid"):raise ValueError(f"`padding` must be either `same` or `valid`. Got {padding}.")diff --git a/kornia/augmentation/container/video.py b/kornia/augmentation/container/video.pyindex 84dfaa6df..752345b31 100644--- a/kornia/augmentation/container/video.py+++ b/kornia/augmentation/container/video.py@@ -74,6 +74,23 @@ class VideoSequential(ImageSequential):>>> out2, lab2 = aug_list(input, label, params=aug_list._params)>>> torch.equal(output, out2)True++ Perform ``OneOf`` transformation with ``random_apply=1`` and ``random_apply_weights`` in ``VideoSequential``.++ >>> import kornia+ >>> input, label = torch.randn(2, 3, 1, 5, 6).repeat(1, 1, 4, 1, 1), torch.tensor([0, 1])+ >>> aug_list = VideoSequential(+ ... kornia.augmentation.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),+ ... kornia.augmentation.RandomAffine(360, p=1.0),+ ... kornia.augmentation.RandomMixUp(p=1.0),+ ... data_format="BCTHW",+ ... same_on_frame=False,+ ... random_apply=1,+ ... random_apply_weights=[0.5, 0.3, 0.8]+ ... )+ >>> out= aug_list(input, label)+ >>> out[0].shape+ torch.Size([2, 3, 4, 5, 6])"""def __init__(@@ -82,8 +99,12 @@ class VideoSequential(ImageSequential):data_format: str = "BTCHW",same_on_frame: bool = True,random_apply: Union[int, bool, Tuple[int, int]] = False,+ random_apply_weights: Optional[List[float]] = None,) -> None:- super().__init__(*args, same_on_batch=None, return_transform=None, keepdim=None, random_apply=random_apply)+ super().__init__(+ *args, same_on_batch=None, return_transform=None, keepdim=None, random_apply=random_apply,+ random_apply_weights=random_apply_weights+ )self.same_on_frame = same_on_frameself.data_format = data_format.upper()if self.data_format not in ["BCTHW", "BTCHW"]:diff --git a/test/augmentation/test_container.py b/test/augmentation/test_container.pyindex 8cdee66ff..ad5d31ddf 100644--- a/test/augmentation/test_container.py+++ b/test/augmentation/test_container.py@@ -150,10 +150,15 @@ class TestVideoSequential:class TestSequential:- def test_exception(self, device, dtype):++ @pytest.mark.parametrize('random_apply_weights', [None, [0.8, 0.9]])+ def test_exception(self, random_apply_weights, device, dtype):inp = torch.randn(1, 3, 30, 30, device=device, dtype=dtype)with pytest.raises(Exception): # AssertError and NotImplementedError- K.ImageSequential(K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0)).inverse(inp)+ K.ImageSequential(+ K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),+ random_apply_weights=random_apply_weights+ ).inverse(inp)@pytest.mark.parametrize('same_on_batch', [True, False, None])@pytest.mark.parametrize("return_transform", [True, False, None])