{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# For tips on running notebooks in Google Colab, see\n",
    "# https://docs.pytorch.org/tutorials/beginner/colab\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[Learn the Basics](intro.html) \\|\\|\n",
    "[Quickstart](quickstart_tutorial.html) \\|\\|\n",
    "[Tensors](tensorqs_tutorial.html) \\|\\| **Datasets & DataLoaders** \\|\\|\n",
    "[Transforms](transforms_tutorial.html) \\|\\| [Build\n",
    "Model](buildmodel_tutorial.html) \\|\\|\n",
    "[Autograd](autogradqs_tutorial.html) \\|\\|\n",
    "[Optimization](optimization_tutorial.html) \\|\\| [Save & Load\n",
    "Model](saveloadrun_tutorial.html)\n",
    "\n",
    "# Datasets & DataLoaders\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Code for processing data samples can get messy and hard to maintain; we\n",
    "ideally want our dataset code to be decoupled from our model training\n",
    "code for better readability and modularity. PyTorch provides two data\n",
    "primitives: `torch.utils.data.DataLoader` and `torch.utils.data.Dataset`\n",
    "that allow you to use pre-loaded datasets as well as your own data.\n",
    "`Dataset` stores the samples and their corresponding labels, and\n",
    "`DataLoader` wraps an iterable around the `Dataset` to enable easy\n",
    "access to the samples.\n",
    "\n",
    "PyTorch domain libraries provide a number of pre-loaded datasets (such\n",
    "as FashionMNIST) that subclass `torch.utils.data.Dataset` and implement\n",
    "functions specific to the particular data. They can be used to prototype\n",
    "and benchmark your model. You can find them here: [Image\n",
    "Datasets](https://pytorch.org/vision/stable/datasets.html), [Text\n",
    "Datasets](https://pytorch.org/text/stable/datasets.html), and [Audio\n",
    "Datasets](https://pytorch.org/audio/stable/datasets.html)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Loading a Dataset\n",
    "\n",
    "Here is an example of how to load the\n",
    "[Fashion-MNIST](https://research.zalando.com/project/fashion_mnist/fashion_mnist/)\n",
    "dataset from TorchVision. Fashion-MNIST is a dataset of Zalando's\n",
    "article images consisting of 60,000 training examples and 10,000 test\n",
    "examples. Each example comprises a 28×28 grayscale image and an\n",
    "associated label from one of 10 classes.\n",
    "\n",
    "We load the [FashionMNIST Dataset](https://pytorch.org/vision/stable/datasets.html#fashion-mnist) with the following parameters:\n",
    "\n",
    ":   -   `root` is the path where the train/test data is stored,\n",
    "    -   `train` specifies training or test dataset,\n",
    "    -   `download=True` downloads the data from the internet if it\\'s\n",
    "        not available at `root`.\n",
    "    -   `transform` and `target_transform` specify the feature and label\n",
    "        transformations\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import torch\n",
    "from torch.utils.data import Dataset\n",
    "from torchvision import datasets\n",
    "from torchvision.transforms import v2\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "\n",
    "training_data = datasets.FashionMNIST(\n",
    "    root=\"data\",\n",
    "    train=True,\n",
    "    download=True,\n",
    "    transform=v2.Compose([v2.ToImage(), v2.ToDtype(torch.float32, scale=True)])\n",
    ")\n",
    "\n",
    "test_data = datasets.FashionMNIST(\n",
    "    root=\"data\",\n",
    "    train=False,\n",
    "    download=True,\n",
    "    transform=v2.Compose([v2.ToImage(), v2.ToDtype(torch.float32, scale=True)])\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Iterating and Visualizing the Dataset\n",
    "\n",
    "We can index `Datasets` manually like a list: `training_data[index]`. We\n",
    "use `matplotlib` to visualize some samples in our training data.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "labels_map = {\n",
    "    0: \"T-Shirt\",\n",
    "    1: \"Trouser\",\n",
    "    2: \"Pullover\",\n",
    "    3: \"Dress\",\n",
    "    4: \"Coat\",\n",
    "    5: \"Sandal\",\n",
    "    6: \"Shirt\",\n",
    "    7: \"Sneaker\",\n",
    "    8: \"Bag\",\n",
    "    9: \"Ankle Boot\",\n",
    "}\n",
    "figure = plt.figure(figsize=(8, 8))\n",
    "cols, rows = 3, 3\n",
    "for i in range(1, cols * rows + 1):\n",
    "    sample_idx = torch.randint(len(training_data), size=(1,)).item()\n",
    "    img, label = training_data[sample_idx]\n",
    "    figure.add_subplot(rows, cols, i)\n",
    "    plt.title(labels_map[label])\n",
    "    plt.axis(\"off\")\n",
    "    plt.imshow(img.squeeze(), cmap=\"gray\")\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "------------------------------------------------------------------------\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Creating a Custom Dataset for your files\n",
    "\n",
    "A custom Dataset class must implement three functions:\n",
    "[\\_\\_init\\_\\_]{.title-ref}, [\\_\\_len\\_\\_]{.title-ref}, and\n",
    "[\\_\\_getitem\\_\\_]{.title-ref}. Take a look at this implementation; the\n",
    "FashionMNIST images are stored in a directory `img_dir`, and their\n",
    "labels are stored separately in a CSV file `annotations_file`.\n",
    "\n",
    "In the next sections, we\\'ll break down what\\'s happening in each of\n",
    "these functions.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import os\n",
    "import pandas as pd\n",
    "from torchvision.io import decode_image\n",
    "\n",
    "class CustomImageDataset(Dataset):\n",
    "    def __init__(self, annotations_file, img_dir, transform=None, target_transform=None):\n",
    "        self.img_labels = pd.read_csv(annotations_file)\n",
    "        self.img_dir = img_dir\n",
    "        self.transform = transform\n",
    "        self.target_transform = target_transform\n",
    "\n",
    "    def __len__(self):\n",
    "        return len(self.img_labels)\n",
    "\n",
    "    def __getitem__(self, idx):\n",
    "        img_path = os.path.join(self.img_dir, self.img_labels.iloc[idx, 0])\n",
    "        image = decode_image(img_path)\n",
    "        label = self.img_labels.iloc[idx, 1]\n",
    "        if self.transform:\n",
    "            image = self.transform(image)\n",
    "        if self.target_transform:\n",
    "            label = self.target_transform(label)\n",
    "        return image, label"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# `__init__`\n",
    "\n",
    "The \\_\\_[init](#init__) function is run once when instantiating the\n",
    "Dataset object. We initialize the directory containing the images, the\n",
    "annotations file, and both transforms (covered in more detail in the\n",
    "next section).\n",
    "\n",
    "The labels.csv file looks like: :\n",
    "\n",
    "    tshirt1.jpg, 0\n",
    "    tshirt2.jpg, 0\n",
    "    ......\n",
    "    ankleboot999.jpg, 9\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def __init__(self, annotations_file, img_dir, transform=None, target_transform=None):\n",
    "    self.img_labels = pd.read_csv(annotations_file)\n",
    "    self.img_dir = img_dir\n",
    "    self.transform = transform\n",
    "    self.target_transform = target_transform"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# `__len__`\n",
    "\n",
    "The \\_\\_[len](#len__) function returns the number of samples in our\n",
    "dataset.\n",
    "\n",
    "Example:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def __len__(self):\n",
    "    return len(self.img_labels)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# `__getitem__`\n",
    "\n",
    "The \\_\\_[getitem](#getitem__) function loads and returns a sample from\n",
    "the dataset at the given index `idx`. Based on the index, it identifies\n",
    "the image\\'s location on disk, converts that to a tensor using\n",
    "`decode_image`, retrieves the corresponding label from the csv data in\n",
    "`self.img_labels`, calls the transform functions on them (if\n",
    "applicable), and returns the tensor image and corresponding label in a\n",
    "tuple.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def __getitem__(self, idx):\n",
    "    img_path = os.path.join(self.img_dir, self.img_labels.iloc[idx, 0])\n",
    "    image = decode_image(img_path)\n",
    "    label = self.img_labels.iloc[idx, 1]\n",
    "    if self.transform:\n",
    "        image = self.transform(image)\n",
    "    if self.target_transform:\n",
    "        label = self.target_transform(label)\n",
    "    return image, label"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "------------------------------------------------------------------------\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Preparing your data for training with DataLoaders\n",
    "\n",
    "The `Dataset` retrieves our dataset\\'s features and labels one sample at\n",
    "a time. While training a model, we typically want to pass samples in\n",
    "\\\"minibatches\\\", reshuffle the data at every epoch to reduce model\n",
    "overfitting, and use Python\\'s `multiprocessing` to speed up data\n",
    "retrieval.\n",
    "\n",
    "`DataLoader` is an iterable that abstracts this complexity for us in an\n",
    "easy API.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from torch.utils.data import DataLoader\n",
    "\n",
    "train_dataloader = DataLoader(training_data, batch_size=64, shuffle=True)\n",
    "test_dataloader = DataLoader(test_data, batch_size=64, shuffle=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Iterate through the DataLoader\n",
    "\n",
    "We have loaded that dataset into the `DataLoader` and can iterate\n",
    "through the dataset as needed. Each iteration below returns a batch of\n",
    "`train_features` and `train_labels` (containing `batch_size=64` features\n",
    "and labels respectively). Because we specified `shuffle=True`, after we\n",
    "iterate over all batches the data is shuffled (for finer-grained control\n",
    "over the data loading order, take a look at\n",
    "[Samplers](https://pytorch.org/docs/stable/data.html#data-loading-order-and-sampler)).\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# Display image and label.\n",
    "train_features, train_labels = next(iter(train_dataloader))\n",
    "print(f\"Feature batch shape: {train_features.size()}\")\n",
    "print(f\"Labels batch shape: {train_labels.size()}\")\n",
    "img = train_features[0].squeeze()\n",
    "label = train_labels[0]\n",
    "plt.imshow(img, cmap=\"gray\")\n",
    "plt.show()\n",
    "print(f\"Label: {label}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "------------------------------------------------------------------------\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Further Reading\n",
    "\n",
    "-   [torch.utils.data API](https://pytorch.org/docs/stable/data.html)\n"
   ]
  }
 ],
 "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.12.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
