|
| 1 | +# Copyright (c) MONAI Consortium |
| 2 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 | +# you may not use this file except in compliance with the License. |
| 4 | +# You may obtain a copy of the License at |
| 5 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 6 | +# Unless required by applicable law or agreed to in writing, software |
| 7 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 8 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 9 | +# See the License for the specific language governing permissions and |
| 10 | +# limitations under the License. |
| 11 | + |
| 12 | +from __future__ import annotations |
| 13 | + |
| 14 | +from abc import abstractmethod |
| 15 | +from math import ceil, sqrt |
| 16 | + |
| 17 | +import torch |
| 18 | + |
| 19 | +from ..transform import RandomizableTransform |
| 20 | + |
| 21 | +__all__ = ["MixUp", "CutMix", "CutOut", "Mixer"] |
| 22 | + |
| 23 | + |
| 24 | +class Mixer(RandomizableTransform): |
| 25 | + def __init__(self, batch_size: int, alpha: float = 1.0) -> None: |
| 26 | + """ |
| 27 | + Mixer is a base class providing the basic logic for the mixup-class of |
| 28 | + augmentations. In all cases, we need to sample the mixing weights for each |
| 29 | + sample (lambda in the notation used in the papers). Also, pairs of samples |
| 30 | + being mixed are picked by randomly shuffling the batch samples. |
| 31 | +
|
| 32 | + Args: |
| 33 | + batch_size (int): number of samples per batch. That is, samples are expected tp |
| 34 | + be of size batchsize x channels [x depth] x height x width. |
| 35 | + alpha (float, optional): mixing weights are sampled from the Beta(alpha, alpha) |
| 36 | + distribution. Defaults to 1.0, the uniform distribution. |
| 37 | + """ |
| 38 | + super().__init__() |
| 39 | + if alpha <= 0: |
| 40 | + raise ValueError(f"Expected positive number, but got {alpha = }") |
| 41 | + self.alpha = alpha |
| 42 | + self.batch_size = batch_size |
| 43 | + |
| 44 | + @abstractmethod |
| 45 | + def apply(self, data: torch.Tensor): |
| 46 | + raise NotImplementedError() |
| 47 | + |
| 48 | + def randomize(self, data=None) -> None: |
| 49 | + """ |
| 50 | + Sometimes you need may to apply the same transform to different tensors. |
| 51 | + The idea is to get a sample and then apply it with apply() as often |
| 52 | + as needed. You need to call this method everytime you apply the transform to a new |
| 53 | + batch. |
| 54 | + """ |
| 55 | + self._params = ( |
| 56 | + torch.from_numpy(self.R.beta(self.alpha, self.alpha, self.batch_size)).type(torch.float32), |
| 57 | + self.R.permutation(self.batch_size), |
| 58 | + ) |
| 59 | + |
| 60 | + |
| 61 | +class MixUp(Mixer): |
| 62 | + """MixUp as described in: |
| 63 | + Hongyi Zhang, Moustapha Cisse, Yann N. Dauphin, David Lopez-Paz. |
| 64 | + mixup: Beyond Empirical Risk Minimization, ICLR 2018 |
| 65 | +
|
| 66 | + Class derived from :py:class:`monai.transforms.Mixer`. See corresponding |
| 67 | + documentation for details on the constructor parameters. |
| 68 | + """ |
| 69 | + |
| 70 | + def apply(self, data: torch.Tensor): |
| 71 | + weight, perm = self._params |
| 72 | + nsamples, *dims = data.shape |
| 73 | + if len(weight) != nsamples: |
| 74 | + raise ValueError(f"Expected batch of size: {len(weight)}, but got {nsamples}") |
| 75 | + |
| 76 | + if len(dims) not in [3, 4]: |
| 77 | + raise ValueError("Unexpected number of dimensions") |
| 78 | + |
| 79 | + mixweight = weight[(Ellipsis,) + (None,) * len(dims)] |
| 80 | + return mixweight * data + (1 - mixweight) * data[perm, ...] |
| 81 | + |
| 82 | + def __call__(self, data: torch.Tensor, labels: torch.Tensor | None = None): |
| 83 | + self.randomize() |
| 84 | + if labels is None: |
| 85 | + return self.apply(data) |
| 86 | + return self.apply(data), self.apply(labels) |
| 87 | + |
| 88 | + |
| 89 | +class CutMix(Mixer): |
| 90 | + """CutMix augmentation as described in: |
| 91 | + Sangdoo Yun, Dongyoon Han, Seong Joon Oh, Sanghyuk Chun, Junsuk Choe, Youngjoon Yoo. |
| 92 | + CutMix: Regularization Strategy to Train Strong Classifiers with Localizable Features, |
| 93 | + ICCV 2019 |
| 94 | +
|
| 95 | + Class derived from :py:class:`monai.transforms.Mixer`. See corresponding |
| 96 | + documentation for details on the constructor parameters. Here, alpha not only determines |
| 97 | + the mixing weight but also the size of the random rectangles used during for mixing. |
| 98 | + Please refer to the paper for details. |
| 99 | +
|
| 100 | + The most common use case is something close to: |
| 101 | +
|
| 102 | + .. code-block:: python |
| 103 | +
|
| 104 | + cm = CutMix(batch_size=8, alpha=0.5) |
| 105 | + for batch in loader: |
| 106 | + images, labels = batch |
| 107 | + augimg, auglabels = cm(images, labels) |
| 108 | + output = model(augimg) |
| 109 | + loss = loss_function(output, auglabels) |
| 110 | + ... |
| 111 | +
|
| 112 | + """ |
| 113 | + |
| 114 | + def apply(self, data: torch.Tensor): |
| 115 | + weights, perm = self._params |
| 116 | + nsamples, _, *dims = data.shape |
| 117 | + if len(weights) != nsamples: |
| 118 | + raise ValueError(f"Expected batch of size: {len(weights)}, but got {nsamples}") |
| 119 | + |
| 120 | + mask = torch.ones_like(data) |
| 121 | + for s, weight in enumerate(weights): |
| 122 | + coords = [torch.randint(0, d, size=(1,)) for d in dims] |
| 123 | + lengths = [d * sqrt(1 - weight) for d in dims] |
| 124 | + idx = [slice(None)] + [slice(c, min(ceil(c + ln), d)) for c, ln, d in zip(coords, lengths, dims)] |
| 125 | + mask[s][idx] = 0 |
| 126 | + |
| 127 | + return mask * data + (1 - mask) * data[perm, ...] |
| 128 | + |
| 129 | + def apply_on_labels(self, labels: torch.Tensor): |
| 130 | + weights, perm = self._params |
| 131 | + nsamples, *dims = labels.shape |
| 132 | + if len(weights) != nsamples: |
| 133 | + raise ValueError(f"Expected batch of size: {len(weights)}, but got {nsamples}") |
| 134 | + |
| 135 | + mixweight = weights[(Ellipsis,) + (None,) * len(dims)] |
| 136 | + return mixweight * labels + (1 - mixweight) * labels[perm, ...] |
| 137 | + |
| 138 | + def __call__(self, data: torch.Tensor, labels: torch.Tensor | None = None): |
| 139 | + self.randomize() |
| 140 | + augmented = self.apply(data) |
| 141 | + return (augmented, self.apply_on_labels(labels)) if labels is not None else augmented |
| 142 | + |
| 143 | + |
| 144 | +class CutOut(Mixer): |
| 145 | + """Cutout as described in the paper: |
| 146 | + Terrance DeVries, Graham W. Taylor. |
| 147 | + Improved Regularization of Convolutional Neural Networks with Cutout, |
| 148 | + arXiv:1708.04552 |
| 149 | +
|
| 150 | + Class derived from :py:class:`monai.transforms.Mixer`. See corresponding |
| 151 | + documentation for details on the constructor parameters. Here, alpha not only determines |
| 152 | + the mixing weight but also the size of the random rectangles being cut put. |
| 153 | + Please refer to the paper for details. |
| 154 | + """ |
| 155 | + |
| 156 | + def apply(self, data: torch.Tensor): |
| 157 | + weights, _ = self._params |
| 158 | + nsamples, _, *dims = data.shape |
| 159 | + if len(weights) != nsamples: |
| 160 | + raise ValueError(f"Expected batch of size: {len(weights)}, but got {nsamples}") |
| 161 | + |
| 162 | + mask = torch.ones_like(data) |
| 163 | + for s, weight in enumerate(weights): |
| 164 | + coords = [torch.randint(0, d, size=(1,)) for d in dims] |
| 165 | + lengths = [d * sqrt(1 - weight) for d in dims] |
| 166 | + idx = [slice(None)] + [slice(c, min(ceil(c + ln), d)) for c, ln, d in zip(coords, lengths, dims)] |
| 167 | + mask[s][idx] = 0 |
| 168 | + |
| 169 | + return mask * data |
| 170 | + |
| 171 | + def __call__(self, data: torch.Tensor): |
| 172 | + self.randomize() |
| 173 | + return self.apply(data) |
0 commit comments