text
stringlengths
1
93.6k
class CutMix(torch.nn.Module):
r"""CutMix image transformation.
Please see the full paper for more details:
ERROR: type should be string, got " https://arxiv.org/pdf/1905.04899.pdf\n"
"""
def __init__(self, alpha: float = 1.0, p: float = 1.0, *args, **kwargs) -> None:
"""Initialize CutMix transformation.
Args:
alpha: The alpha parameter to the Beta for producing a mixing lambda.
"""
super().__init__(*args, **kwargs)
assert alpha >= 0
assert p >= 0 and p <= 1.0
self.alpha = alpha
self.p = p
@staticmethod
def rand_bbox(size: torch.Size, lam: float) -> Tuple[int, int, int, int]:
"""Return a random bbox coordinates.
Args:
size: model input tensor shape in this format: (...,H,W)
lam: lambda sampling parameter in CutMix method. See equation 1
in the original paper: https://arxiv.org/pdf/1905.04899.pdf
Returns:
The output bbox format is a tuple: (x1, y1, x2, y2), where (x1,
y1) and (x2,y2) are the coordinates of the top-left and bottom-right
corners of the bbox in the pixel-space.
"""
assert lam >= 0 and lam <= 1.0
h = size[-2]
w = size[-1]
cut_rat = np.sqrt(1.0 - lam)
cut_h = int(h * cut_rat)
cut_w = int(w * cut_rat)
# uniform
cx = np.random.randint(h)
cy = np.random.randint(w)
bbx1 = np.clip(cx - cut_h // 2, 0, h)
bby1 = np.clip(cy - cut_w // 2, 0, w)
bbx2 = np.clip(cx + cut_h // 2, 0, h)
bby2 = np.clip(cy + cut_w // 2, 0, w)
return (bbx1, bby1, bbx2, bby2)
def get_params(
self, size: torch.Size, alpha: float
) -> Tuple[float, Tuple[int, int, int, int]]:
"""Return CutMix random parameters."""
# Skip mixing by probability 1-self.p
if alpha == 0 or torch.rand(1) > self.p:
return None
lam = np.random.beta(alpha, alpha)
# Compute mask
bbx1, bby1, bbx2, bby2 = self.rand_bbox(size, lam)
return lam, (bbx1, bby1, bbx2, bby2)
def forward(
self,
x: Tensor,
x2: Optional[Tensor] = None,
y: Optional[Tensor] = None,
y2: Optional[Tensor] = None,
) -> Tuple[Tensor, Tensor]:
"""Mix images by replacing random patches from one to the other.
Args:
x: A tensor with a batch of samples. Shape: [batch_size, ...].
x2: A tensor with exactly one matching sample for any input in `x`. Shape:
[batch_size, ...].
y: A tensor of target labels. Shape: [batch_size, ...].
y2: A tensor of target labels for paired samples. Shape: [batch_size, ...].
params: Dictionary of {'lam': lam_val} to reproduce a mixing.
"""
alpha = self.alpha
# Randomly sample lambda and bbox coordinates if not provided
params = self.get_params(x.shape, alpha)
if params is None:
return x, y
lam, (bbx1, bby1, bbx2, bby2) = params
# Randomly sample second input from the same mini-batch if not provided
if x2 is None:
batch_size = int(x.size()[0])
index = torch.randperm(batch_size, device=x.device)
x2 = x[index, :]
y2 = y[index, :] if y is not None else None
# Mix inputs and labels