AI Logic

Data Augmentation

GridMask

Updated:

GridMask diagram. Left: the flow of one training step (mini-batch, usual data augmentation, normalization, decide whether to apply with probability p, choose d, δx, δy, build the grid mask, rotate the mask (only when used), multiply the image by the mask, model, loss). Right: an example of a mask with r = 0.4 applied to an image of a circle (a 32 × 32 grid), showing unit side d = 10 and d = 15 side by side, with the label unchanged in both. Below: the contents of one mask unit (keep bands of width r·d and set a square of side (1 − r)d to 0) and the formulas.

What is GridMask?

GridMask is a data augmentation technique that, during training, fills a set of squares arranged at regular intervals in a grid with 0 and trains with the label unchanged. It was proposed by Chen et al. in 2020.

Cutout and Random Erasing erase a single large rectangle. Depending on the rectangle's position and size, this can erase the object entirely or miss the object completely. The former yields an unanswerable image, and the latter an image that is effectively unchanged. GridMask spreads small squares evenly across the whole image, making it easier to produce "just right" images in which only part of the object is erased.

In formulas:

x~=x×M,y~=y\tilde{x} = x \times M, \qquad \tilde{y} = y

Here, xx is the image and M∈{0,1}H×WM \in \{0, 1\}^{H \times W} is a grid-shaped mask that is 0 only where pixels are erased. The ground-truth label yy is not changed.

As an analogy, it is like looking outside through a window fitted with a lattice. The lattice bars hide part of the view, but every object remains partly visible, so it is still possible to tell what is there.

GridMask is not a method that chooses erased locations at random, but one that gives the erased locations a fixed structure (a grid). The paper also tried a variant that randomly decides, with a fixed probability, whether to erase each unit's square, but accuracy dropped.

Procedure

The mask is built by tiling square "units" of side dd across the whole image (bottom right of the top figure). In each unit, bands of width r⋅dr \cdot d along the top and left are kept, and the remaining square of side (1−r)d(1 - r)d is set to 0. The shape of the mask is determined by four numbers (r,d,δx,δy)(r, d, \delta_x, \delta_y).

For each image, the following is done during training (left of the top figure).

  1. If using the usual data augmentation such as cropping and horizontal flipping, apply it first, then normalize the image. GridMask is applied after normalization.
  2. Decide with probability pp whether to apply GridMask. Images not selected are used as is.
  3. Randomly choose the unit side dd from the range [dmin⁡,dmax⁡][d_{\min}, d_{\max}].
  4. Randomly choose the grid offsets δx\delta_x and δy\delta_y, each from 00 to d−1d - 1. δx\delta_x and δy\delta_y are the distances from the image edge to the first complete unit.
  5. Build the mask MM from the chosen dd, δx\delta_x, δy\delta_y and the preset rr. In the ImageNet experiments, the mask is rotated before use.
  6. Multiply the image by the mask and, without changing the label, train as usual with a loss such as cross-entropy.

Ignoring incomplete units at the edges, the fraction of the image kept (the keep ratio) kk is given by the following formula.

k=sum(M)H×W=1−(1−r)2k = \frac{\mathrm{sum}(M)}{H \times W} = 1 - (1 - r)^2

rr determines the keep ratio, and dd determines only the size of the erased squares. Changing dd does not change the keep ratio.

Eq. (4) in the paper writes the side of the erased square as l=r×dl = r \times d. However, consistent with the keep ratio formula (Eq. (3)) and the official implementation (which uses l = ceil(d * ratio) as the width of the kept bands and sets everything else to 0), what is kept is bands of width r⋅dr \cdot d, and the erased square has side (1−r)d(1 - r)d. The larger rr is, the more is kept.

GridMask is used only during training. For evaluation and inference, feed the original image as is.

Choosing the hyperparameters

Three things are tuned: rr, which sets the keep ratio; the unit size range [dmin⁡,dmax⁡][d_{\min}, d_{\max}]; and the probability of applying it. The values chosen in the paper are as follows.

SettingImageNet (ResNet-50 etc.)CIFAR-10COCO (object detection)
rr0.60.40.5
Range of dd[96,224][96, 224] (images are 224 × 224)−−
ProbabilityRaised from 0 to 0.8 over 240 epochs, then held until epoch 300Same schedule as ImageNetConstant p=0.7p = 0.7
  • rr: The paper compared rr = 0.4–0.8 on ImageNet and 0.2–0.6 on CIFAR-10, choosing 0.6 and 0.4 respectively. Keeping more for harder datasets (avoiding underfitting) and erasing more for easier datasets (suppressing overfitting) worked better.
  • dd: Smaller dd reduces failures (erasing too much or too little of the object), but squares that are too small mean little to convolutions. The results of varying the range on ImageNet are shown below; choosing from a wide range for diversity worked better than fixing a narrow range.
Range of ddImageNet top-1 accuracy (%)
[40,60][40, 60]77.26
[96,120][96, 120]77.58
[150,170][150, 170]77.61
[200,224][200, 224]77.57
[96,224][96, 224]77.89
  • Probability of applying: The paper compared applying with a constant probability pp against raising it linearly to an upper limit PP as training progresses, and reports that the latter was better in most experiments.

Why it works

The paper argues that for information-deleting data augmentation to succeed, a balance between deleting too much and keeping too much is essential.

  • Deleting too much: If the object and its surrounding context are erased entirely, the remaining information cannot determine the answer, and the sample is no different from noisy data.
  • Keeping too much: If the object is not touched at all, the image is the same as an unaugmented one and does nothing to build robustness.

Cutout and Random Erasing erase one large region, so depending on its position and size they easily fall into one of these failures. Hide-and-Seek, which extends the idea of dropout to regions (dividing the image into small squares and erasing them at random), improves on this, but adjacent squares can happen to be erased or kept together. Because GridMask arranges squares at regular intervals, only part of an object tends to be erased wherever it is.

The paper simulated 100,000 images of size 224 × 224 containing objects of size 40–160 with the keep ratio fixed at 0.75, and counted the rate of failures where "99% or more of the object is erased, or kept." Larger squares increase failures, but GridMask's failure rate was always lower than that of Cutout (extended to multiple squares) and Hide-and-Seek, and grew more slowly. The paper therefore says GridMask is easy to use even with fairly large squares.

Also, comparing CAM (a map of where in the image the model looked to decide) for ResNet-50 trained on ImageNet, the model trained with GridMask attended to a wider range of important regions than the model trained with only the usual data augmentation. An example is shown of an image with two mobile phones in which the GridMask model attended to both.

Results reported in the paper

Results for ImageNet image classification (top-1 accuracy, %). GridMask means adding only GridMask to the usual data augmentation (cropping, horizontal flipping); no color-changing augmentation is used.

ModelAccuracy
ResNet-5076.5
ResNet-50 + Cutout77.1
ResNet-50 + Hide-and-Seek77.2
ResNet-50 + AutoAugment77.6
ResNet-50 + GridMask77.9
ResNet-101 → + GridMask78.0 → 79.1
ResNet-152 → + GridMask78.3 → 79.7

Results on CIFAR-10 (accuracy, %, average of 3 runs) are as follows.

ModelNoneRandom ErasingCutoutAutoAugmentGridMaskAutoAugment + GridMask
ResNet-1895.2895.3296.2596.0796.5496.64
WideResNet-28-1096.1396.9297.0497.0197.2497.48
Shake-Shake-26-3296.4296.4696.9696.9697.2097.42

It also improves tasks other than image classification.

TaskModelNoneGridMask
COCO object detection (mAP, %)Faster R-CNN (ResNet-50-FPN)37.439.2
COCO object detection (mAP, %)Faster R-CNN (ResNeXt-101-FPN)41.242.6
Cityscapes semantic segmentation (mIoU, %)PSPNet (ResNet-50)77.378.1
Cityscapes semantic segmentation (mIoU, %)PSPNet (ResNet-101)78.679.0

In object detection, with longer training, the model without GridMask lost accuracy to overfitting (37.4% at 2× epochs, 35.7% at 4×), whereas with GridMask it rose to 39.2% at 4× epochs. Varying the application probability pp from 0.3 to 0.9 barely changed mAP (38.0–38.3%).

The paper also tried a regularization combining the grid shape with Mixup (replacing CutMix's rectangle with a grid), reporting 78.7% for ResNet-50 on ImageNet (CutMix: 78.6%).

Practical considerations

  • Apply it after normalization. Then the regions filled with 0 take on the mean color and do not distort the statistics much. Filling with 0 while values are still in 0–1 produces a pure black grid.
  • Adjust rr to the difficulty of the dataset. In the paper, ImageNet used 0.6 (about 16% erased) and CIFAR-10 used 0.4 (about 36% erased). Erasing too much on a hard dataset leads to underfitting.
  • Do not fix dd to a single value; choose it from a range. Narrowing the range lowered accuracy. Also avoid dd that is too small.
  • The method tends to pay off with long training. The paper's ImageNet experiments used 300 epochs, and the object detection comparisons also used longer-than-usual training. With short training, learning may appear slower because of the erased information.
  • It does not change labels. Even if part of an object is erased, the original label is kept, so for tasks with per-pixel ground truth such as segmentation, apply the mask only to the input image and leave the ground-truth mask unchanged.

torchvision has no transform named GridMask. Write it yourself following the same procedure as the paper's official implementation (the Grid class), as in the implementation example below. The official implementation has a switch (mode) for an "inverted GridMask" that swaps the mask's 0s and 1s; the paper's GridMask corresponds to mode=1.

Comparison with similar methods and how to choose

The following table compares methods that "erase part of an image or feature" from the same perspectives.

MethodWhat is erasedWhat fills the erased regionHow erased locations are chosenLabel
GridMaskMultiple squares arranged at regular intervals in a grid0 (the mean color after normalization)Only the grid size and offset are randomUnchanged
CutoutOne square (fixed size)0 (the mean color after normalization)Center chosen at randomUnchanged
Random ErasingOne rectangle (area and aspect ratio also random)A fixed value or random noisePosition chosen at randomUnchanged
Hide-and-SeekRandomly selected small squares from a partition of the imageMean of the training dataChosen at random per squareUnchanged
CutMixOne rectangleThe same region of another imagePosition chosen at randomMixed by the pasted area ratio
DropBlockSquares (multiple) in intermediate feature maps0 (the rest is rescaled)Centers chosen at randomUnchanged

Guidelines for choosing are as follows.

  • Object sizes and positions vary, and erasing too much or too little should be reduced: Use GridMask. Because of the grid, only part of an object tends to be erased wherever it is.
  • A single hyperparameter is preferred: Use Cutout. Only the side length of the square needs tuning.
  • The erased pixels should also be used for learning: Use CutMix. It pastes another image into the erased region and mixes labels by area ratio.
  • Regions should be erased inside the network rather than in the input: Use DropBlock.

GridMask can also be combined with data augmentation that selects transformations, such as AutoAugment. In the paper's CIFAR-10 experiments, using AutoAugment and GridMask together gave higher accuracy than either alone.

PyTorch example

Show code
python
import math
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.transforms.functional as TF
from torchvision import datasets, transforms
from torch.utils.data import DataLoader

"""
CIFAR-10 image classification (training with GridMask)
"""

# Hyperparameters
batch_size = 128      # batch size
epochs = 10           # number of epochs
learning_rate = 1e-3  # learning rate
ratio = 0.4           # r: fraction of each unit kept as bands (the paper's CIFAR-10 setting; ImageNet uses 0.6)
d_min, d_max = 8, 32  # range for the unit side d (the paper's ImageNet setting is [96, 224] for 224 × 224 images)
max_prob = 0.8        # upper limit P of the application probability
rise_epochs = 8       # epochs over which the probability rises from 0 to P (240 of 300 epochs for ImageNet in the paper)
rotate = 1            # upper limit of mask rotation angle (degrees). 1 means no rotation. The ImageNet setting rotates

# 'cuda' if CUDA is available, 'mps' on Apple Silicon, otherwise 'cpu'
device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'


class GridMask:
  # Same procedure as the paper's official implementation (Grid class in JIA-Lab-research/GridMask, mode=1).
  # In each unit of side d, keep bands (vertical and horizontal) of width l = ceil(d·r) and set the remaining (1 − r)d square to 0
  def __init__(self, d_min, d_max, ratio, rotate=1, prob=1.0):
    self.d_min, self.d_max = d_min, d_max
    self.ratio = ratio
    self.rotate = rotate
    self.max_prob = prob
    self.prob = prob

  def set_prob(self, epoch, rise_epochs):
    # Raise the application probability linearly to the upper limit as training progresses
    self.prob = self.max_prob * min(1.0, epoch / rise_epochs)

  def __call__(self, img):  # img: normalized [C, H, W] tensor
    if np.random.rand() > self.prob:
      return img
    h, w = img.size(1), img.size(2)
    hh = math.ceil(math.sqrt(h * h + w * w))  # build on a square with the diagonal length so it still covers the image after rotation
    d = np.random.randint(self.d_min, self.d_max)    # unit side d
    l = math.ceil(d * self.ratio)                    # width of kept bands r·d
    st_h, st_w = np.random.randint(d), np.random.randint(d)  # grid offsets δy, δx (0 to d−1)

    keep = torch.zeros(hh, hh)
    for i in range(-1, hh // d + 1):
      s = d * i + st_h
      keep[max(min(s, hh), 0):max(min(s + l, hh), 0), :] = 1   # keep horizontal bands
      s = d * i + st_w
      keep[:, max(min(s, hh), 0):max(min(s + l, hh), 0)] = 1   # keep vertical bands
    angle = float(np.random.randint(self.rotate))
    keep = TF.rotate(keep[None], angle)[0]           # rotate the mask (0 degrees if rotate=1)
    top, left = (hh - h) // 2, (hh - w) // 2
    mask = keep[top:top + h, left:left + w]          # crop the center to the image size
    return img * mask                                # x̃ = x × M. The label is unchanged


grid_mask = GridMask(d_min, d_max, ratio, rotate=rotate, prob=max_prob)

mean, std = (0.4914, 0.4822, 0.4465), (0.2470, 0.2435, 0.2616)
train_transform = transforms.Compose([
  transforms.RandomCrop(32, padding=4),   # usual data augmentation (cropping, horizontal flip)
  transforms.RandomHorizontalFlip(),
  transforms.ToTensor(),
  transforms.Normalize(mean, std),        # normalize to zero mean first (filling with 0 = filling with the mean color)
  grid_mask,                              # apply after normalization
])
test_transform = transforms.Compose([     # GridMask is not used for evaluation
  transforms.ToTensor(),
  transforms.Normalize(mean, std),
])
train_dataset = datasets.CIFAR10(root='./data', train=True, download=True, transform=train_transform)
test_dataset = datasets.CIFAR10(root='./data', train=False, download=True, transform=test_transform)
# num_workers=0: load data in the same process so that the probability changed by set_prob takes effect directly
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True, num_workers=0)
test_loader = DataLoader(test_dataset, batch_size=batch_size)


class SmallCNN(nn.Module):
  def __init__(self, num_classes=10):
    super().__init__()
    self.features = nn.Sequential(
      nn.Conv2d(3, 32, kernel_size=3, padding=1),   # [B, 3, 32, 32] -> [B, 32, 32, 32]
      nn.BatchNorm2d(32),
      nn.ReLU(),
      nn.MaxPool2d(2),                              # -> [B, 32, 16, 16]
      nn.Conv2d(32, 64, kernel_size=3, padding=1),  # -> [B, 64, 16, 16]
      nn.BatchNorm2d(64),
      nn.ReLU(),
      nn.MaxPool2d(2),                              # -> [B, 64, 8, 8]
      nn.Flatten(),
    )
    self.classifier = nn.Linear(64 * 8 * 8, num_classes)

  def forward(self, x):
    return self.classifier(self.features(x))


model = SmallCNN().to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)

# Training: GridMask is applied during data loading. Labels are used as is
for epoch in range(epochs):
  grid_mask.set_prob(epoch, rise_epochs)  # raise the application probability every epoch
  model.train()
  for images, labels in train_loader:
    images, labels = images.to(device), labels.to(device)
    loss = criterion(model(images), labels)
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

# Evaluation: check on the original images
model.eval()
correct = 0
total = 0
with torch.no_grad():
  for images, labels in test_loader:
    images, labels = images.to(device), labels.to(device)
    predicted = model(images).argmax(dim=1)
    total += labels.size(0)
    correct += (predicted == labels).sum().item()

print(f"Test Accuracy: {100 * correct / total:.2f}%")

FAQ

Q. How does GridMask differ from Cutout?
A.

Cutout erases one large square, while GridMask erases many small squares in a grid. Depending on position, Cutout may erase the object entirely or not at all, but because GridMask's squares are evenly spaced, it tends to produce images in which only part of the object is erased. For ResNet-50 on ImageNet in the paper, Cutout scored 77.1% and GridMask 77.9%.

Q. What value of r should be tried first?
A.

The paper chose r=0.6r = 0.6 (keep ratio k=1−0.42=0.84k = 1 - 0.4^2 = 0.84) for ImageNet and r=0.4r = 0.4 (k=0.64k = 0.64) for CIFAR-10. Use a larger rr to keep more for harder datasets, and a smaller one to erase more for easier ones.

Q. Can it be used for object detection and segmentation?
A.

Yes. In the paper, the mAP of Faster R-CNN (ResNet-50-FPN) on COCO object detection rose from 37.4% to 39.2%, and the mIoU of PSPNet (ResNet-50) on Cityscapes segmentation rose from 77.3% to 78.1%. In both cases, GridMask was added after the usual data augmentation.

References

  1. P. Chen, S. Liu, H. Zhao, X. Wang, and J. Jia, "GridMask Data Augmentation," arXiv:2001.04086, 2020.
  2. JIA-Lab-research/GridMask (the paper's official implementation)
  3. T. DeVries and G. W. Taylor, "Improved Regularization of Convolutional Neural Networks with Cutout," arXiv:1708.04552, 2017.
  4. K. K. Singh, H. Yu, A. Sarmasi, G. Pradeep, and Y. J. Lee, "Hide-and-Seek: A Data Augmentation Technique for Weakly-Supervised Localization and Beyond," arXiv:1811.02545, 2018.