Shortcuts

如何使用CutMix和MixUp

注意

尝试在Colab上运行 或转到末尾下载完整的示例代码。

CutMixMixUp 是流行的增强策略 可以提高分类准确性。

这些转换与Torchvision中的其他转换略有不同,因为它们期望输入的是批量样本,而不是单个图像。在这个例子中,我们将解释如何使用它们:在DataLoader之后,或者作为整理函数的一部分。

import torch
from torchvision.datasets import FakeData
from torchvision.transforms import v2


NUM_CLASSES = 100

预处理管道

我们将使用一个简单但典型的图像分类流程:

preproc = v2.Compose([
    v2.PILToTensor(),
    v2.RandomResizedCrop(size=(224, 224), antialias=True),
    v2.RandomHorizontalFlip(p=0.5),
    v2.ToDtype(torch.float32, scale=True),  # to float32 in [0, 1]
    v2.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),  # typically from ImageNet
])

dataset = FakeData(size=1000, num_classes=NUM_CLASSES, transform=preproc)

img, label = dataset[0]
print(f"{type(img) = }, {img.dtype = }, {img.shape = }, {label = }")
type(img) = <class 'torch.Tensor'>, img.dtype = torch.float32, img.shape = torch.Size([3, 224, 224]), label = 67

需要注意的重要一点是,CutMix和MixUp都不是这个预处理流程的一部分。我们稍后在定义DataLoader时会添加它们。作为复习,如果我们不使用CutMix或MixUp,DataLoader和训练循环将如下所示:

from torch.utils.data import DataLoader

dataloader = DataLoader(dataset, batch_size=4, shuffle=True)

for images, labels in dataloader:
    print(f"{images.shape = }, {labels.shape = }")
    print(labels.dtype)
    # <rest of the training loop here>
    break
images.shape = torch.Size([4, 3, 224, 224]), labels.shape = torch.Size([4])
torch.int64

在哪里使用MixUp和CutMix

数据加载器之后

现在让我们添加CutMix和MixUp。最简单的方法是在DataLoader之后立即进行:DataLoader已经为我们批处理了图像和标签,这正是这些转换所期望的输入:

dataloader = DataLoader(dataset, batch_size=4, shuffle=True)

cutmix = v2.CutMix(num_classes=NUM_CLASSES)
mixup = v2.MixUp(num_classes=NUM_CLASSES)
cutmix_or_mixup = v2.RandomChoice([cutmix, mixup])

for images, labels in dataloader:
    print(f"Before CutMix/MixUp: {images.shape = }, {labels.shape = }")
    images, labels = cutmix_or_mixup(images, labels)
    print(f"After CutMix/MixUp: {images.shape = }, {labels.shape = }")

    # <rest of the training loop here>
    break
Before CutMix/MixUp: images.shape = torch.Size([4, 3, 224, 224]), labels.shape = torch.Size([4])
After CutMix/MixUp: images.shape = torch.Size([4, 3, 224, 224]), labels.shape = torch.Size([4, 100])

注意标签是如何被转换的:我们从形状为 (batch_size,) 的批量标签转换为了形状为 (batch_size, num_classes) 的张量。转换后的标签仍然可以直接传递给像 torch.nn.functional.cross_entropy() 这样的损失函数。

作为排序函数的一部分

在DataLoader之后传递变换是使用CutMix和MixUp的最简单方法,但一个缺点是它没有利用DataLoader的多进程处理。为此,我们可以将这些变换作为整理函数的一部分传递(请参阅PyTorch文档以了解更多关于整理的信息)。

from torch.utils.data import default_collate


def collate_fn(batch):
    return cutmix_or_mixup(*default_collate(batch))


dataloader = DataLoader(dataset, batch_size=4, shuffle=True, num_workers=2, collate_fn=collate_fn)

for images, labels in dataloader:
    print(f"{images.shape = }, {labels.shape = }")
    # No need to call cutmix_or_mixup, it's already been called as part of the DataLoader!
    # <rest of the training loop here>
    break
images.shape = torch.Size([4, 3, 224, 224]), labels.shape = torch.Size([4, 100])

非标准输入格式

到目前为止,我们使用了一个典型的样本结构,其中我们将(images, labels)作为输入传递。默认情况下,MixUp和CutMix将与大多数常见的样本结构神奇地工作:元组,其中第二个参数是张量标签,或带有“label[s]”键的字典。查看labels_getter参数的文档以获取更多详细信息。

如果你的样本结构不同,你仍然可以通过传递一个可调用对象给labels_getter参数来使用CutMix和MixUp。例如:

batch = {
    "imgs": torch.rand(4, 3, 224, 224),
    "target": {
        "classes": torch.randint(0, NUM_CLASSES, size=(4,)),
        "some_other_key": "this is going to be passed-through"
    }
}


def labels_getter(batch):
    return batch["target"]["classes"]


out = v2.CutMix(num_classes=NUM_CLASSES, labels_getter=labels_getter)(batch)
print(f"{out['imgs'].shape = }, {out['target']['classes'].shape = }")
out['imgs'].shape = torch.Size([4, 3, 224, 224]), out['target']['classes'].shape = torch.Size([4, 100])

脚本的总运行时间: (0 分钟 0.194 秒)

Gallery generated by Sphinx-Gallery