π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Feat: random channel dropout (#2859)
Vicent Gilabert8edc68c6bbc5
diff --git a/benchmarks/augmentation/2d_intensity_test.py b/benchmarks/augmentation/2d_intensity_test.pyindex dc86686f5..5c433f837 100644--- a/benchmarks/augmentation/2d_intensity_test.py+++ b/benchmarks/augmentation/2d_intensity_test.py@@ -9,6 +9,7 @@ from kornia.augmentation import (RandomAutoContrast,RandomBoxBlur,RandomBrightness,+ RandomChannelDropout,RandomChannelShuffle,RandomClahe,RandomContrast,@@ -102,6 +103,16 @@ def test_aug_2d_brightness(benchmark, device, dtype, torch_optimizer, shape):assert actual.shape == shape+def test_aug_2d_channel_dropout(benchmark, device, dtype, torch_optimizer, shape):+ data = torch.rand(*shape, device=device, dtype=dtype)+ aug = RandomChannelDropout(p=1.0)+ op = torch_optimizer(aug)++ actual = benchmark(op, input=data)++ assert actual.shape == shape++def test_aug_2d_channel_shuffle(benchmark, device, dtype, torch_optimizer, shape):data = torch.rand(*shape, device=device, dtype=dtype)aug = RandomChannelShuffle(p=1.0)diff --git a/docs/generate_examples.py b/docs/generate_examples.pyindex 945f2aa05..7aecce0ca 100644--- a/docs/generate_examples.py+++ b/docs/generate_examples.py@@ -136,6 +136,7 @@ def main():"RandomBrightness": (((0.0, 1.0),), 2, 2022),"RandomContrast": (((0.0, 1.0),), 2, 2022),"RandomCrop": ((img1.shape[-2:], (50, 50)), 2, 2020),+ "RandomChannelDropout": ((), 1, 2020),"RandomChannelShuffle": ((), 1, 2020),"RandomElasticTransform": (((63, 63), (32, 32), (2.0, 2.0)), 2, 2018),"RandomEqualize": ((), 1, 2020),diff --git a/docs/source/augmentation.module.rst b/docs/source/augmentation.module.rstindex 6aca66dd1..5cd67d97e 100644--- a/docs/source/augmentation.module.rst+++ b/docs/source/augmentation.module.rst@@ -16,6 +16,7 @@ Intensity.. autoclass:: RandomAutoContrast.. autoclass:: RandomBoxBlur.. autoclass:: RandomBrightness+.. autoclass:: RandomChannelDropout.. autoclass:: RandomChannelShuffle.. autoclass:: RandomClahe.. autoclass:: RandomContrastdiff --git a/kornia/augmentation/_2d/intensity/__init__.py b/kornia/augmentation/_2d/intensity/__init__.pyindex d8c9fff6e..47d01a0a7 100644--- a/kornia/augmentation/_2d/intensity/__init__.py+++ b/kornia/augmentation/_2d/intensity/__init__.py@@ -1,6 +1,7 @@from kornia.augmentation._2d.intensity.auto_contrast import RandomAutoContrastfrom kornia.augmentation._2d.intensity.box_blur import RandomBoxBlurfrom kornia.augmentation._2d.intensity.brightness import RandomBrightness+from kornia.augmentation._2d.intensity.channel_dropout import RandomChannelDropoutfrom kornia.augmentation._2d.intensity.channel_shuffle import RandomChannelShufflefrom kornia.augmentation._2d.intensity.clahe import RandomClahefrom kornia.augmentation._2d.intensity.color_jiggle import ColorJigglediff --git a/kornia/augmentation/_2d/intensity/channel_dropout.py b/kornia/augmentation/_2d/intensity/channel_dropout.pynew file mode 100644index 000000000..e80fb5efd--- /dev/null+++ b/kornia/augmentation/_2d/intensity/channel_dropout.py@@ -0,0 +1,98 @@+from typing import Any, Dict, Optional++from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D+from kornia.augmentation.random_generator._2d import ChannelDropoutGenerator+from kornia.core import Tensor, tensor+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE, KORNIA_CHECK_TYPE+++class RandomChannelDropout(IntensityAugmentationBase2D):+ r"""Apply random channel dropout to a batch of images.++ .. image:: _static/img/RandomChannelDropout.png++ Args:+ num_drop_channels: Number of channels to drop randomly. Default is 1.+ fill_value: Value to fill the dropped channels with. Default is 0.0.+ same_on_batch: Apply the same transformation across the batch. Defaults to False.+ p: Probability of applying the transformation. Defaults to 0.5.+ keepdim: Whether to keep the output shape the same as input ``True`` or broadcast it+ to the batch form ``False``. Defaults to False.++ Shape:+ - Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`+ - Output: :math:`(C, H, W)` or :math:`(B, C, H, W)`++ .. note::+ If `num_drop_channels` is set to 1, it means that for each image in the batch,+ we will randomly choose one channel to drop.+ If `num_drop_channels` is set to 2, it means that for each image in the batch,+ we will randomly choose two channels to drop.+ If num_drop_channels is set to 3, it means that for each image in the batch,+ we will randomly choose three channels to drop (all image).++ Examples:+ >>> rng = torch.manual_seed(1)+ >>> img = torch.ones(1, 3, 3, 3)+ >>> aug = RandomChannelDropout(num_drop_channels=1, fill_value=0.0, p=1.0)+ >>> aug(img)+ tensor([[[[1., 1., 1.],+ [1., 1., 1.],+ [1., 1., 1.]],+ <BLANKLINE>+ [[0., 0., 0.],+ [0., 0., 0.],+ [0., 0., 0.]],+ <BLANKLINE>+ [[1., 1., 1.],+ [1., 1., 1.],+ [1., 1., 1.]]]])++ To apply the exact augmenation again, you may take the advantage of the previous parameter state:+ >>> input = torch.rand(1, 3, 32, 32)+ >>> aug = RandomChannelDropout(num_drop_channels=1, fill_value=0.0, p=1.0)+ >>> (aug(input) == aug(input, params=aug._params)).all()+ tensor(True)+ """++ def __init__(+ self,+ num_drop_channels: int = 1,+ fill_value: float = 0.0,+ same_on_batch: bool = False,+ p: float = 0.5,+ keepdim: bool = False,+ ) -> None:+ super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim)++ KORNIA_CHECK_TYPE(fill_value, float, f"`fill_value` must be a float. Got: {type(fill_value)}")+ KORNIA_CHECK(+ 0.0 <= fill_value <= 1.0,+ f"Invalid value in `fill_value`. Must be a float between 0 and 1. Got: {fill_value}",+ )+ self.fill_value = tensor(fill_value)++ KORNIA_CHECK_TYPE(num_drop_channels, int, f"`num_drop_channels` must be an int. Got: {type(num_drop_channels)}")+ KORNIA_CHECK(+ num_drop_channels >= 1,+ f"Invalid value in `num_drop_channels`. Must be an int greater than 1. Got: {num_drop_channels}",+ )+ self.num_drop_channels = num_drop_channels+ # Generator of random parameters.+ self._param_generator = ChannelDropoutGenerator(self.num_drop_channels)++ def apply_transform(+ self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None+ ) -> Tensor:+ KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])+ KORNIA_CHECK(+ self.num_drop_channels <= input.shape[1],+ "Invalid value in `num_drop_channels`. Cannot be greater than the number of channels of `input`.",+ )++ out = input.clone()+ out[params["batch_idx"], params["channel_idx"], ...] = self.fill_value.to(+ device=input.device, dtype=input.dtype+ )++ return outdiff --git a/kornia/augmentation/__init__.py b/kornia/augmentation/__init__.pyindex bd71f94b5..0210675c9 100644--- a/kornia/augmentation/__init__.py+++ b/kornia/augmentation/__init__.py@@ -12,6 +12,7 @@ from kornia.augmentation._2d import (RandomAutoContrast,RandomBoxBlur,RandomBrightness,+ RandomChannelDropout,RandomChannelShuffle,RandomClahe,RandomContrast,@@ -110,6 +111,7 @@ __all__ = ["RandomBoxBlur","RandomMedianBlur","RandomBrightness",+ "RandomChannelDropout","RandomChannelShuffle","RandomContrast","RandomCrop",diff --git a/kornia/augmentation/random_generator/_2d/__init__.py b/kornia/augmentation/random_generator/_2d/__init__.pyindex 3b4c6e4eb..30eb1f752 100644--- a/kornia/augmentation/random_generator/_2d/__init__.py+++ b/kornia/augmentation/random_generator/_2d/__init__.py@@ -1,4 +1,5 @@from kornia.augmentation.random_generator._2d.affine import *+from kornia.augmentation.random_generator._2d.channel_dropout import *from kornia.augmentation.random_generator._2d.color_jiggle import *from kornia.augmentation.random_generator._2d.color_jitter import *from kornia.augmentation.random_generator._2d.crop import *diff --git a/kornia/augmentation/random_generator/_2d/channel_dropout.py b/kornia/augmentation/random_generator/_2d/channel_dropout.pynew file mode 100644index 000000000..2f093228d--- /dev/null+++ b/kornia/augmentation/random_generator/_2d/channel_dropout.py@@ -0,0 +1,58 @@+from __future__ import annotations++import torch++from kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistribution+from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _range_bound+from kornia.core import Tensor+++class ChannelDropoutGenerator(RandomGeneratorBase):+ r"""Generate random dropout masks for channels in a batch of images.++ Args:+ num_drop_channels: The number of channels to drop randomly.++ Returns:+ A dictionary containing the dropout mask.+ - dropout_mask: Binary masks (bool) indicating the dropped channels with a shape of (B, C, H, W).++ Note:+ The generated random numbers are not reproducible across different devices and dtypes. By default,+ the parameters will be generated on CPU. This can be changed by calling+ ``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.+ """++ def __init__(+ self,+ num_drop_channels: int,+ ) -> None:+ super().__init__()+ self.num_drop_channels = num_drop_channels+ self.drop_sampler: UniformDistribution++ def __repr__(self) -> str:+ r"""Return a string representation of the object."""+ repr_buf = f"num_drop_channels={self.num_drop_channels}"+ return repr_buf++ def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:+ r"""Create samplers for generating random dropout parameters."""+ drop = _range_bound((0.0, 1.0), "drop", device=device, dtype=dtype)+ self.drop_sampler = UniformDistribution(drop[0], drop[1], validate_args=False)++ def forward(self, batch_shape: tuple[int, ...], same_on_batch: bool = False) -> dict[str, Tensor]:+ r"""Generates a mask for dropout channels."""+ batch_size, channels, _, _ = batch_shape+ _common_param_check(batch_size, same_on_batch)+ _device, _dtype = self.device, self.dtype++ batch_idx = torch.arange(batch_size, device=_device, dtype=torch.long).reshape(batch_size, 1)+ channel_idx = torch.argsort(+ _adapted_rsampling((batch_size, channels), self.drop_sampler, same_on_batch), dim=1+ )[:, : self.num_drop_channels].to(torch.long)++ return {+ "batch_idx": batch_idx,+ "channel_idx": channel_idx,+ }diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.pyindex 1f917b004..94592a3e5 100644--- a/tests/augmentation/test_augmentation.py+++ b/tests/augmentation/test_augmentation.py@@ -17,6 +17,7 @@ from kornia.augmentation import (PadTo,RandomBoxBlur,RandomBrightness,+ RandomChannelDropout,RandomChannelShuffle,RandomClahe,RandomContrast,@@ -4203,6 +4204,74 @@ class TestRandomLinearCornerIllumination(BaseTester):self.assert_close(output_tensor[0], output_tensor[1])+class TestRandomChannelDropout(BaseTester):+ def _get_expected(self, device, dtype):+ return torch.tensor(+ [+ [+ [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]],+ [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],+ [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]],+ ]+ ],+ device=device,+ dtype=dtype,+ )++ def test_smoke(self, device, dtype):+ torch.manual_seed(1)+ input_tensor = torch.ones(1, 3, 3, 3, device=device, dtype=dtype)+ expected = self._get_expected(device=device, dtype=dtype)+ aug = RandomChannelDropout(p=1.0)+ res = aug(input_tensor)+ assert input_tensor.shape == res.shape+ self.assert_close(res, expected, rtol=1e-4, atol=1e-4)++ def test_exception(self, device, dtype):+ num_drop_channels = 2.0+ with pytest.raises(TypeError, match=f"`num_drop_channels` must be an int. Got: {type(num_drop_channels)}"):+ RandomChannelDropout(num_drop_channels=num_drop_channels)++ num_drop_channels = 0+ with pytest.raises(+ Exception,+ match=f"Invalid value in `num_drop_channels`. Must be an int greater than 1. Got: {num_drop_channels}",+ ):+ RandomChannelDropout(num_drop_channels=num_drop_channels)++ num_drop_channels = 5+ input_tensor = torch.ones(1, 3, 3, 3, device=device, dtype=dtype)+ with pytest.raises(+ Exception,+ match="Invalid value in `num_drop_channels`. Cannot be greater than the number of channels of `input`.",+ ):+ RandomChannelDropout(num_drop_channels=num_drop_channels, p=1.0)(input_tensor)++ fill_value = 2.0+ with pytest.raises(+ Exception, match=f"Invalid value in `fill_value`. Must be a float between 0 and 1. Got: {fill_value}"+ ):+ RandomChannelDropout(fill_value=fill_value)++ fill_value = 1+ with pytest.raises(TypeError, match=f"`fill_value` must be a float. Got: {type(fill_value)}"):+ RandomChannelDropout(fill_value=fill_value)++ @pytest.mark.parametrize("channel_shape, batch_shape", [(3, 1), (1, 1), (5, 5)])+ def test_cardinality(self, batch_shape, channel_shape, device, dtype):+ input_tensor = torch.ones(batch_shape, channel_shape, 5, 5, device=device, dtype=dtype)+ transform = RandomChannelDropout(p=1.0)+ output_tensor = transform(input_tensor)+ assert input_tensor.shape[0] == output_tensor.shape[0]+ assert input_tensor.shape[1] == output_tensor.shape[1]++ def test_same_on_batch(self, device, dtype):+ input_tensor = torch.ones(2, 3, 5, 5, device=device, dtype=dtype)+ transform = RandomChannelDropout(p=1.0, same_on_batch=True)+ output_tensor = transform(input_tensor)+ self.assert_close(output_tensor[0], output_tensor[1])++class TestNormalize(BaseTester):# TODO: improve and implement more meaningful smoke tests e.g check for a consistent# return values such a Tensor variable.