{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# How to use CutMix and MixUp\n\n<div class=\"alert alert-info\"><h4>Note</h4><p>Try on [Colab](https://colab.research.google.com/github/pytorch/vision/blob/gh-pages/main/_generated_ipynb_notebooks/plot_cutmix_mixup.ipynb)\n    or `go to the end <sphx_glr_download_auto_examples_transforms_plot_cutmix_mixup.py>` to download the full example code.</p></div>\n\n:class:`~torchvision.transforms.v2.CutMix` and\n:class:`~torchvision.transforms.v2.MixUp` are popular augmentation strategies\nthat can improve classification accuracy.\n\nThese transforms are slightly different from the rest of the Torchvision\ntransforms, because they expect\n**batches** of samples as input, not individual images. In this example we'll\nexplain how to use them: after the ``DataLoader``, or as part of a collation\nfunction.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import torch\nfrom torchvision.datasets import FakeData\nfrom torchvision.transforms import v2\n\n\nNUM_CLASSES = 100"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Pre-processing pipeline\n\nWe'll use a simple but typical image classification pipeline:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "preproc = v2.Compose([\n    v2.PILToTensor(),\n    v2.RandomResizedCrop(size=(224, 224), antialias=True),\n    v2.RandomHorizontalFlip(p=0.5),\n    v2.ToDtype(torch.float32, scale=True),  # to float32 in [0, 1]\n    v2.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),  # typically from ImageNet\n])\n\ndataset = FakeData(size=1000, num_classes=NUM_CLASSES, transform=preproc)\n\nimg, label = dataset[0]\nprint(f\"{type(img) = }, {img.dtype = }, {img.shape = }, {label = }\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "One important thing to note is that neither CutMix nor MixUp are part of this\npre-processing pipeline. We'll add them a bit later once we define the\nDataLoader. Just as a refresher, this is what the DataLoader and training loop\nwould look like if we weren't using CutMix or MixUp:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from torch.utils.data import DataLoader\n\ndataloader = DataLoader(dataset, batch_size=4, shuffle=True)\n\nfor images, labels in dataloader:\n    print(f\"{images.shape = }, {labels.shape = }\")\n    print(labels.dtype)\n    # <rest of the training loop here>\n    break"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Where to use MixUp and CutMix\n\n### After the DataLoader\n\nNow let's add CutMix and MixUp. The simplest way to do this right after the\nDataLoader: the Dataloader has already batched the images and labels for us,\nand this is exactly what these transforms expect as input:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "dataloader = DataLoader(dataset, batch_size=4, shuffle=True)\n\ncutmix = v2.CutMix(num_classes=NUM_CLASSES)\nmixup = v2.MixUp(num_classes=NUM_CLASSES)\ncutmix_or_mixup = v2.RandomChoice([cutmix, mixup])\n\nfor images, labels in dataloader:\n    print(f\"Before CutMix/MixUp: {images.shape = }, {labels.shape = }\")\n    images, labels = cutmix_or_mixup(images, labels)\n    print(f\"After CutMix/MixUp: {images.shape = }, {labels.shape = }\")\n\n    # <rest of the training loop here>\n    break"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "Note how the labels were also transformed: we went from a batched label of\nshape (batch_size,) to a tensor of shape (batch_size, num_classes). The\ntransformed labels can still be passed as-is to a loss function like\n:func:`torch.nn.functional.cross_entropy`.\n\n### As part of the collation function\n\nPassing the transforms after the DataLoader is the simplest way to use CutMix\nand MixUp, but one disadvantage is that it does not take advantage of the\nDataLoader multi-processing. For that, we can pass those transforms as part of\nthe collation function (refer to the [PyTorch docs](https://pytorch.org/docs/stable/data.html#dataloader-collate-fn) to learn\nmore about collation).\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from torch.utils.data import default_collate\n\n\ndef collate_fn(batch):\n    return cutmix_or_mixup(*default_collate(batch))\n\n\ndataloader = DataLoader(dataset, batch_size=4, shuffle=True, num_workers=2, collate_fn=collate_fn)\n\nfor images, labels in dataloader:\n    print(f\"{images.shape = }, {labels.shape = }\")\n    # No need to call cutmix_or_mixup, it's already been called as part of the DataLoader!\n    # <rest of the training loop here>\n    break"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Non-standard input format\n\nSo far we've used a typical sample structure where we pass ``(images,\nlabels)`` as inputs. MixUp and CutMix will magically work by default with most\ncommon sample structures: tuples where the second parameter is a tensor label,\nor dict with a \"label[s]\" key. Look at the documentation of the\n``labels_getter`` parameter for more details.\n\nIf your samples have a different structure, you can still use CutMix and MixUp\nby passing a callable to the ``labels_getter`` parameter. For example:\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "batch = {\n    \"imgs\": torch.rand(4, 3, 224, 224),\n    \"target\": {\n        \"classes\": torch.randint(0, NUM_CLASSES, size=(4,)),\n        \"some_other_key\": \"this is going to be passed-through\"\n    }\n}\n\n\ndef labels_getter(batch):\n    return batch[\"target\"][\"classes\"]\n\n\nout = v2.CutMix(num_classes=NUM_CLASSES, labels_getter=labels_getter)(batch)\nprint(f\"{out['imgs'].shape = }, {out['target']['classes'].shape = }\")"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.10.22"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}