blob: 6524e391eedc48ceeb709b161bc43819ef465903 [file] [log] [blame]
{
"cells": [
{
"cell_type": "markdown",
"id": "f8a593f8",
"metadata": {},
"source": [
"<!--- Licensed to the Apache Software Foundation (ASF) under one -->\n",
"<!--- or more contributor license agreements. See the NOTICE file -->\n",
"<!--- distributed with this work for additional information -->\n",
"<!--- regarding copyright ownership. The ASF licenses this file -->\n",
"<!--- to you under the Apache License, Version 2.0 (the -->\n",
"<!--- \"License\"); you may not use this file except in compliance -->\n",
"<!--- with the License. You may obtain a copy of the License at -->\n",
"\n",
"<!--- http://www.apache.org/licenses/LICENSE-2.0 -->\n",
"\n",
"<!--- Unless required by applicable law or agreed to in writing, -->\n",
"<!--- software distributed under the License is distributed on an -->\n",
"<!--- \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -->\n",
"<!--- KIND, either express or implied. See the License for the -->\n",
"<!--- specific language governing permissions and limitations -->\n",
"<!--- under the License. -->\n",
"\n",
"\n",
"# Gluon `Dataset`s and `DataLoader`\n",
"\n",
"One of the most critical steps for model training and inference is loading the data: without data you can't do Machine Learning! In this tutorial we use the Gluon API to define a [Dataset](/api/python/docs/api/gluon/data/index.html#datasets) and use a [DataLoader](/api/python/docs/api/gluon/data/index.html#dataloader) to iterate through the dataset in mini-batches.\n",
"\n",
"## Introduction to `Dataset`s\n",
"\n",
"[Dataset](/api/python/docs/api/gluon/data/index.html#datasets) objects are used to represent collections of data, and include methods to load and parse the data (that is often stored on disk). Gluon has a number of different `Dataset` classes for working with image data straight out-of-the-box, but we'll use the [ArrayDataset](/api/python/docs/api/gluon/data/index.html#mxnet.gluon.data.ArrayDataset) to introduce the idea of a `Dataset`.\n",
"\n",
"We first start by generating random data `X` (with 3 variables) and corresponding random labels `y` to simulate a typical supervised learning task. We generate 10 samples and we pass them all to the `ArrayDataset`."
]
},
{
"cell_type": "markdown",
"id": "860a252a",
"metadata": {},
"source": [
"```python\n",
"import mxnet as mx\n",
"import os\n",
"import tarfile\n",
"\n",
"mx.random.seed(42) # Fix the seed for reproducibility\n",
"X = mx.random.uniform(shape=(10, 3))\n",
"y = mx.random.uniform(shape=(10, 1))\n",
"dataset = mx.gluon.data.dataset.ArrayDataset(X, y)\n",
"```\n"
]
},
{
"cell_type": "markdown",
"id": "44e8b38a",
"metadata": {},
"source": [
"A key feature of a `Dataset` is the __*ability to retrieve a single sample given an index*__. Our random data and labels were generated in memory, so this `ArrayDataset` doesn't have to load anything from disk, but the interface is the same for all `Dataset`'s."
]
},
{
"cell_type": "markdown",
"id": "d840da5e",
"metadata": {},
"source": [
"```python\n",
"sample_idx = 4\n",
"sample = dataset[sample_idx]\n",
"\n",
"assert len(sample) == 2\n",
"assert sample[0].shape == (3, )\n",
"assert sample[1].shape == (1, )\n",
"print(sample)\n",
"```\n"
]
},
{
"cell_type": "markdown",
"id": "20b17aea",
"metadata": {},
"source": [
"(\n",
"[ 0.4375872 0.29753461 0.89177299]\n",
"<NDArray 3 @cpu(0)>,\n",
"[ 0.83261985]\n",
"<NDArray 1 @cpu(0)>)\n",
"\n",
"\n",
"We get a tuple of a data sample and its corresponding label, which makes sense because we passed the data `X` and the labels `y` in that order when we instantiated the `ArrayDataset`. We don't usually retrieve individual samples from `Dataset` objects though (unless we're quality checking the output samples). Instead we use a `DataLoader`.\n",
"\n",
"## Introduction to `DataLoader`\n",
"\n",
"A [DataLoader](/api/python/docs/api/gluon/data/index.html#dataloader) is used to create mini-batches of samples from a [Dataset](/api/python/docs/api/gluon/data/index.html#datasets), and provides a convenient iterator interface for looping these batches. It's typically much more efficient to pass a mini-batch of data through a neural network than a single sample at a time, because the computation can be performed in parallel. A required parameter of `DataLoader` is the size of the mini-batches you want to create, called `batch_size`.\n",
"\n",
"Another benefit of using `DataLoader` is the ability to easily load data in parallel using [multiprocessing](https://docs.python.org/3.6/library/multiprocessing.html). You can set the `num_workers` parameter to the number of CPUs available on your machine for maximum performance, or limit it to a lower number to spare resources."
]
},
{
"cell_type": "markdown",
"id": "5e17f2c8",
"metadata": {},
"source": [
"```python\n",
"from multiprocessing import cpu_count\n",
"CPU_COUNT = cpu_count()\n",
"\n",
"data_loader = mx.gluon.data.DataLoader(dataset, batch_size=5, num_workers=CPU_COUNT)\n",
"\n",
"for X_batch, y_batch in data_loader:\n",
" print(\"X_batch has shape {}, and y_batch has shape {}\".format(X_batch.shape, y_batch.shape))\n",
"```\n"
]
},
{
"cell_type": "markdown",
"id": "ac800af5",
"metadata": {},
"source": [
"`X_batch has shape (5, 3), and y_batch has shape (5, 1)` <!--notebook-skip-line-->\n",
"\n",
"`X_batch has shape (5, 3), and y_batch has shape (5, 1)` <!--notebook-skip-line-->\n",
"\n",
"\n",
"We can see 2 mini-batches of data (and labels), each with 5 samples, which makes sense given we started with a dataset of 10 samples. When comparing the shape of the batches to the samples returned by the `Dataset`, we've gained an extra dimension at the start which is sometimes called the batch axis.\n",
"\n",
"Our `data_loader` loop will stop when every sample of `dataset` has been returned as part of a batch. Sometimes the dataset length isn't divisible by the mini-batch size, leaving a final batch with a smaller number of samples. `DataLoader`'s default behavior is to return this smaller mini-batch, but this can be changed by setting the `last_batch` parameter to `discard` (which ignores the last batch) or `rollover` (which starts the next epoch with the remaining samples).\n",
"\n",
"## Machine learning with `Dataset`s and `DataLoader`s\n",
"\n",
"You will often use a few different `Dataset` objects in your Machine Learning project. It's essential to separate your training dataset from testing dataset, and it's also good practice to have validation dataset (a.k.a. development dataset) that can be used for optimising hyperparameters.\n",
"\n",
"Using Gluon `Dataset` objects, we define the data to be included in each of these separate datasets. Common use cases for loading data are covered already (e.g. [mxnet.gluon.data.vision.datasets.ImageFolderDataset](/api/python/docs/api/gluon/data/vision/index.html)), but it's simple to create your own custom `Dataset` classes for other types of data. You can even use included `Dataset` objects for common datasets if you want to experiment quickly; they download and parse the data for you! In this example we use the [Fashion MNIST](https://github.com/zalandoresearch/fashion-mnist) dataset from Zalando Research.\n",
"\n",
"Many of the image `Dataset`'s accept a function (via the optional `transform` parameter) which is applied to each sample returned by the `Dataset`. It's useful for performing data augmentation, but can also be used for more simple data type conversion and pixel value scaling as seen below."
]
},
{
"cell_type": "markdown",
"id": "a40b1909",
"metadata": {},
"source": [
"```python\n",
"def transform(data, label):\n",
" data = data.astype('float32')/255\n",
" return data, label\n",
"\n",
"train_dataset = mx.gluon.data.vision.datasets.FashionMNIST(train=True, transform=transform)\n",
"valid_dataset = mx.gluon.data.vision.datasets.FashionMNIST(train=False, transform=transform)\n",
"```\n"
]
},
{
"cell_type": "markdown",
"id": "fc6fb008",
"metadata": {},
"source": [
"```python\n",
"%matplotlib inline\n",
"from matplotlib.pylab import imshow\n",
"\n",
"sample_idx = 234\n",
"sample = train_dataset[sample_idx]\n",
"data = sample[0]\n",
"label = sample[1]\n",
"label_desc = {0:'T-shirt/top', 1:'Trouser', 2:'Pullover', 3:'Dress', 4:'Coat', 5:'Sandal', 6:'Shirt', 7:'Sneaker', 8:'Bag', 9:'Ankle boot'}\n",
"\n",
"imshow(data[:,:,0].asnumpy(), cmap='gray')\n",
"print(\"Data type: {}\".format(data.dtype))\n",
"print(\"Label: {}\".format(label))\n",
"print(\"Label description: {}\".format(label_desc[label]))\n",
"```\n"
]
},
{
"cell_type": "markdown",
"id": "18334840",
"metadata": {},
"source": [
"`Data type: <class 'numpy.float32'>`<!--notebook-skip-line-->\n",
"\n",
"`Label: 8`<!--notebook-skip-line-->\n",
"\n",
"`Label description: Bag`<!--notebook-skip-line-->\n",
"\n",
"\n",
"![png](https://raw.githubusercontent.com/dmlc/web-data/master/mxnet/doc/tutorials/gluon/datasets/fashion_mnist_bag.png)<!--notebook-skip-line-->\n",
"\n",
"\n",
"When training machine learning models it is important to shuffle the training samples every time you pass through the dataset (i.e. each epoch). Sometimes the order of your samples will have a spurious relationship with the target variable, and shuffling the samples helps remove this. With [DataLoader](/api/python/docs/api/gluon/data/index.html#dataloader) it's as simple as adding `shuffle=True`. You don't need to shuffle the validation and testing data though.\n",
"\n",
"If you have more complex shuffling requirements (e.g. when handling sequential data), take a look at [mxnet.gluon.data.BatchSampler](/api/python/docs/api/gluon/data/index.html#mxnet.gluon.data.BatchSampler) and pass this to your `DataLoader` instead."
]
},
{
"cell_type": "markdown",
"id": "205662bb",
"metadata": {},
"source": [
"```python\n",
"batch_size = 32\n",
"train_data_loader = mx.gluon.data.DataLoader(train_dataset, batch_size, shuffle=True, num_workers=CPU_COUNT)\n",
"valid_data_loader = mx.gluon.data.DataLoader(valid_dataset, batch_size, num_workers=CPU_COUNT)\n",
"```\n"
]
},
{
"cell_type": "markdown",
"id": "50814cde",
"metadata": {},
"source": [
"With both `DataLoader`s defined, we can now train a model to classify each image and evaluate the validation loss at each epoch. Our Fashion MNIST dataset has 10 classes including shirt, dress, sneakers, etc. We define a simple fully connected network with a softmax output and use cross entropy as our loss."
]
},
{
"cell_type": "markdown",
"id": "a353e43c",
"metadata": {},
"source": [
"```python\n",
"from mxnet import gluon, autograd, ndarray\n",
"\n",
"def construct_net():\n",
" net = gluon.nn.HybridSequential()\n",
" with net.name_scope():\n",
" net.add(gluon.nn.Dense(128, activation=\"relu\"))\n",
" net.add(gluon.nn.Dense(64, activation=\"relu\"))\n",
" net.add(gluon.nn.Dense(10))\n",
" return net\n",
"\n",
"# construct and initialize network.\n",
"ctx = mx.gpu() if mx.context.num_gpus() else mx.cpu()\n",
"\n",
"net = construct_net()\n",
"net.hybridize()\n",
"net.initialize(mx.init.Xavier(), ctx=ctx)\n",
"# define loss and trainer.\n",
"criterion = gluon.loss.SoftmaxCrossEntropyLoss()\n",
"trainer = gluon.Trainer(net.collect_params(), 'sgd', {'learning_rate': 0.1})\n",
"```\n"
]
},
{
"cell_type": "markdown",
"id": "d9ffc11c",
"metadata": {},
"source": [
"```python\n",
"\n",
"\n",
"epochs = 5\n",
"for epoch in range(epochs):\n",
" # training loop (with autograd and trainer steps, etc.)\n",
" cumulative_train_loss = mx.nd.zeros(1, ctx=ctx)\n",
" training_samples = 0\n",
" for batch_idx, (data, label) in enumerate(train_data_loader):\n",
" data = data.as_in_context(ctx).reshape((-1, 784)) # 28*28=784\n",
" label = label.as_in_context(ctx)\n",
" with autograd.record():\n",
" output = net(data)\n",
" loss = criterion(output, label)\n",
" loss.backward()\n",
" trainer.step(data.shape[0])\n",
" cumulative_train_loss += loss.sum()\n",
" training_samples += data.shape[0]\n",
" train_loss = cumulative_train_loss.asscalar()/training_samples\n",
"\n",
" # validation loop\n",
" cumulative_valid_loss = mx.nd.zeros(1, ctx)\n",
" valid_samples = 0\n",
" for batch_idx, (data, label) in enumerate(valid_data_loader):\n",
" data = data.as_in_context(ctx).reshape((-1, 784)) # 28*28=784\n",
" label = label.as_in_context(ctx)\n",
" output = net(data)\n",
" loss = criterion(output, label)\n",
" cumulative_valid_loss += loss.sum()\n",
" valid_samples += data.shape[0]\n",
" valid_loss = cumulative_valid_loss.asscalar()/valid_samples\n",
"\n",
" print(\"Epoch {}, training loss: {:.2f}, validation loss: {:.2f}\".format(epoch, train_loss, valid_loss))\n",
"```\n"
]
},
{
"cell_type": "markdown",
"id": "7d9be815",
"metadata": {},
"source": [
"`Epoch 0, training loss: 0.54, validation loss: 0.45`<!--notebook-skip-line-->\n",
"\n",
"`...`<!--notebook-skip-line-->\n",
"\n",
"`Epoch 4, training loss: 0.32, validation loss: 0.33`<!--notebook-skip-line-->\n",
"\n",
"\n",
"# Using own data with included `Dataset`s\n",
"\n",
"Gluon has a number of different [Dataset](https://mxnet.incubator.apache.org/api/python/gluon/data.html?highlight=dataset#mxnet.gluon.data.Dataset) classes for working with your own image data straight out-of-the-box. You can get started quickly using the [mxnet.gluon.data.vision.datasets.ImageFolderDataset](/api/python/docs/api/gluon/data/vision/datasets/index.html#mxnet.gluon.data.vision.datasets.ImageFolderDataset) which loads images directly from a user-defined folder, and infers the label (i.e. class) from the folders.\n",
"\n",
"We will run through an example for image classification, but a similar process applies for other vision tasks. If you already have your own collection of images to work with you should partition your data into training and test sets, and place all objects of the same class into seperate folders. Similar to:"
]
},
{
"cell_type": "markdown",
"id": "d5815326",
"metadata": {},
"source": [
"```\n",
" ./images/train/car/abc.jpg\n",
" ./images/train/car/efg.jpg\n",
" ./images/train/bus/hij.jpg\n",
" ./images/train/bus/klm.jpg\n",
" ./images/test/car/xyz.jpg\n",
" ./images/test/bus/uvw.jpg\n",
"```\n"
]
},
{
"cell_type": "markdown",
"id": "fdf2784a",
"metadata": {},
"source": [
"You can download the Caltech 101 dataset if you don't already have images to work with for this example, but please note the download is 126MB."
]
},
{
"cell_type": "markdown",
"id": "b7645115",
"metadata": {},
"source": [
"```python\n",
"\n",
"data_folder = \"data\"\n",
"dataset_name = \"101_ObjectCategories\"\n",
"archive_file = \"{}.tar.gz\".format(dataset_name)\n",
"archive_path = os.path.join(data_folder, archive_file)\n",
"data_url = \"https://s3.us-east-2.amazonaws.com/mxnet-public/\"\n",
"\n",
"if not os.path.isfile(archive_path):\n",
" mx.test_utils.download(\"{}{}\".format(data_url, archive_file), dirname = data_folder)\n",
" print('Extracting {} in {}...'.format(archive_file, data_folder))\n",
" tar = tarfile.open(archive_path, \"r:gz\")\n",
" tar.extractall(data_folder)\n",
" tar.close()\n",
" print('Data extracted.')\n",
"```\n"
]
},
{
"cell_type": "markdown",
"id": "26377e60",
"metadata": {},
"source": [
"After downloading and extracting the data archive, we have two folders: `data/101_ObjectCategories` and `data/101_ObjectCategories_test`. We load the data into separate training and testing [ImageFolderDataset](/api/python/docs/api/gluon/data/vision/datasets/index.html#mxnet.gluon.data.vision.datasets.ImageFolderDataset)s."
]
},
{
"cell_type": "markdown",
"id": "4b9a07df",
"metadata": {},
"source": [
"```python\n",
"training_path = os.path.join(data_folder, dataset_name)\n",
"testing_path = os.path.join(data_folder, \"{}_test\".format(dataset_name))\n",
"```\n"
]
},
{
"cell_type": "markdown",
"id": "c2549e0e",
"metadata": {},
"source": [
"We instantiate the [ImageFolderDataset](https://mxnet.incubator.apache.org/api/python/gluon/data.html?highlight=imagefolderdataset#mxnet.gluon.data.vision.datasets.ImageFolderDataset)s by providing the path to the data, and the folder structure will be traversed to determine which image classes are available and which images correspond to each class. You must take care to ensure the same classes are both the training and testing datasets, otherwise the label encodings can get muddled.\n",
"\n",
"Optionally, you can pass a `transform` parameter to these `Dataset`'s as we've seen before."
]
},
{
"cell_type": "markdown",
"id": "7e3e0878",
"metadata": {},
"source": [
"```python\n",
"train_dataset = mx.gluon.data.vision.datasets.ImageFolderDataset(training_path)\n",
"test_dataset = mx.gluon.data.vision.datasets.ImageFolderDataset(testing_path)\n",
"```\n"
]
},
{
"cell_type": "markdown",
"id": "48137039",
"metadata": {},
"source": [
"Samples from these datasets are tuples of data and label. Images are loaded from disk, decoded and optionally transformed when the `__getitem__(i)` method is called (equivalent to `train_dataset[i]`).\n",
"\n",
"As with the Fashion MNIST dataset the labels will be integer encoded. You can use the `synsets` property of the [ImageFolderDataset](https://mxnet.incubator.apache.org/api/python/gluon/data.html?highlight=imagefolderdataset#mxnet.gluon.data.vision.datasets.ImageFolderDataset)s to retrieve the original descriptions (e.g. `train_dataset.synsets[i]`)."
]
},
{
"cell_type": "markdown",
"id": "34a41eaa",
"metadata": {},
"source": [
"```python\n",
"sample_idx = 539\n",
"sample = train_dataset[sample_idx]\n",
"data = sample[0]\n",
"label = sample[1]\n",
"\n",
"imshow(data.asnumpy(), cmap='gray')\n",
"print(\"Data type: {}\".format(data.dtype))\n",
"print(\"Label: {}\".format(label))\n",
"print(\"Label description: {}\".format(train_dataset.synsets[label]))\n",
"assert label == 1\n",
"```\n"
]
},
{
"cell_type": "markdown",
"id": "e54cc37f",
"metadata": {},
"source": [
"`Data type: <class 'numpy.uint8'>`<!--notebook-skip-line-->\n",
"\n",
"`Label: 1`<!--notebook-skip-line-->\n",
"\n",
"`Label description: Faces_easy` <!--notebook-skip-line-->\n",
"\n",
"\n",
"![png](https://raw.githubusercontent.com/dmlc/web-data/master/mxnet/doc/tutorials/gluon/datasets/caltech101_face.png)<!--notebook-skip-line-->\n",
"\n",
"\n",
"# Using own data with custom `Dataset`s\n",
"\n",
"Sometimes you have data that doesn't quite fit the format expected by the included [Dataset](/api/python/docs/api/gluon/data/index.html#mxnet.gluon.data.Dataset)s. You might be able to preprocess your data to fit the expected format, but it is easy to create your own dataset to do this.\n",
"\n",
"All you need to do is create a class that implements a `__getitem__` method, that returns a sample (i.e. a tuple of [mx.nd.NDArray](/api/python/docs/api/ndarray/ndarray.html#mxnet.ndarray.NDArray)'s).\n",
"\n",
"# Appendix: Upgrading from Module `DataIter` to Gluon `DataLoader`\n",
"\n",
"Before Gluon's [DataLoader](/api/python/docs/api/gluon/data/index.html#dataloader), MXNet used [DataIter](/api/python/docs/api/mxnet/io/index.html#mxnet.io.DataIter) objects for loading data for training and testing. `DataIter` has a similar interface for iterating through data, but it isn't directly compatible with typical Gluon `DataLoader` loops. Unlike Gluon `DataLoader` which often returns a tuple of `(data, label)`, a `DataIter` returns a [DataBatch](/api/python/docs/api/mxnet/io/index.html#mxnet.io.DataBatch) object that has `data` and `label` properties. Switching to `DataLoader`'s is highly recommended when using Gluon, but you'll need to take care of pre-processing steps such as augmentations in a `transform` function.\n",
"\n",
"So you can get up and running with Gluon quicker if you have already implemented complex pre-processing steps using `DataIter`, we have provided a simple class to wrap existing `DataIter` objects so they can be used in a typical Gluon training loop. You can use this class for `DataIter`s such as [mxnet.image.ImageIter](/api/python/docs/api/mxnet/image/index.html#mxnet.image.ImageIter) and [mxnet.io.ImageRecordIter](/api/python/docs/api/mxnet/io/index.html#mxnet.io.ImageDetRecordIter) that have single data and label arrays."
]
},
{
"cell_type": "markdown",
"id": "dfcf79ae",
"metadata": {},
"source": [
"```python\n",
"class DataIterLoader():\n",
" def __init__(self, data_iter):\n",
" self.data_iter = data_iter\n",
"\n",
" def __iter__(self):\n",
" self.data_iter.reset()\n",
" return self\n",
"\n",
" def __next__(self):\n",
" batch = self.data_iter.__next__()\n",
" assert len(batch.data) == len(batch.label) == 1\n",
" data = batch.data[0]\n",
" label = batch.label[0]\n",
" return data, label\n",
"\n",
" def next(self):\n",
" return self.__next__() # for Python 2\n",
"```\n"
]
},
{
"cell_type": "markdown",
"id": "38995440",
"metadata": {},
"source": [
"```python\n",
"data_iter = mx.io.NDArrayIter(data=X, label=y, batch_size=5)\n",
"data_iter_loader = DataIterLoader(data_iter)\n",
"for X_batch, y_batch in data_iter_loader:\n",
" assert X_batch.shape == (5, 3)\n",
" assert y_batch.shape == (5, 1)\n",
"```\n"
]
},
{
"cell_type": "markdown",
"id": "ac98d55b",
"metadata": {},
"source": [
"<!-- INSERT SOURCE DOWNLOAD BUTTONS -->"
]
}
],
"metadata": {
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 5
}