Run this notebook online:\ |Binder| or Colab: |Colab| .. |Binder| image:: https://mybinder.org/badge_logo.svg :target: https://mybinder.org/v2/gh/deepjavalibrary/d2l-java/master?filepath=chapter_linear-networks/image-classification-dataset.ipynb .. |Colab| image:: https://colab.research.google.com/assets/colab-badge.svg :target: https://colab.research.google.com/github/deepjavalibrary/d2l-java/blob/colab/chapter_linear-networks/image-classification-dataset.ipynb .. _sec_fashion_mnist: The Image Classification Dataset ================================ In :numref:`sec_naive_bayes`, we trained a naive Bayes classifier, using the MNIST dataset introduced in 1998 :cite:`LeCun.Bottou.Bengio.ea.1998`. While MNIST had a good run as a benchmark dataset, even simple models by today's standards achieve classification accuracy over 95% making it unsuitable for distinguishing between stronger models and weaker ones. Today, MNIST serves as more of sanity checks than as a benchmark. To up the ante just a bit, we will focus our discussion in the coming sections on the qualitatively similar, but comparatively complex Fashion-MNIST dataset :cite:`Xiao.Rasul.Vollgraf.2017`, which was released in 2017. .. code:: java %load ../utils/djl-imports %load ../utils/StopWatch.java %load ../utils/ImageUtils.java .. code:: java import ai.djl.basicdataset.cv.classification.*; import ai.djl.training.dataset.Record; import java.awt.image.BufferedImage; import java.awt.Graphics2D; import java.awt.Color; Getting the Dataset ------------------- Just as with MNIST, DJL makes it easy to download and load the Fashion-MNIST dataset into memory via the ``FashionMnist`` class contained in ``ai.djl.basicdataset``. We briefly work through the mechanics of loading and exploring the dataset below. Please refer to :numref:`sec_naive_bayes` for more details on loading data. Let us first define the ``getDataset()`` function that obtains and reads the Fashion-MNIST dataset. It returns the dataset for the training set or the validation set depending on the passed in ``usage`` (``Dataset.Usage.TRAIN`` for training and ``Dataset.Usage.TEST`` for validation). You can then call ``getData(manager)`` on the dataset to get the corresponding iterator. It also takes in the ``batchSize`` and ``randomShuffle`` which dictates the size of each batch and whether to randomly shuffle the data respectively. .. code:: java int batchSize = 256; boolean randomShuffle = true; FashionMnist mnistTrain = FashionMnist.builder() .optUsage(Dataset.Usage.TRAIN) .setSampling(batchSize, randomShuffle) .optLimit(Long.getLong("DATASET_LIMIT", Long.MAX_VALUE)) .build(); FashionMnist mnistTest = FashionMnist.builder() .optUsage(Dataset.Usage.TEST) .setSampling(batchSize, randomShuffle) .optLimit(Long.getLong("DATASET_LIMIT", Long.MAX_VALUE)) .build(); mnistTrain.prepare(); mnistTest.prepare(); NDManager manager = NDManager.newBaseManager(); Fashion-MNIST consists of images from 10 categories, each represented by 60k images in the training set and by 10k in the test set. Consequently the training set and the test set contain 60k and 10k images, respectively. .. code:: java System.out.println(mnistTrain.size()); System.out.println(mnistTest.size()); .. parsed-literal:: :class: output 60000 10000 The images in Fashion-MNIST are associated with the following categories: t-shirt, trousers, pullover, dress, coat, sandal, shirt, sneaker, bag and ankle boot. The following function converts between numeric label indices and their names in text. .. code:: java // Saved in the FashionMnist class for later use public String[] getFashionMnistLabels(int[] labelIndices) { String[] textLabels = {"t-shirt", "trouser", "pullover", "dress", "coat", "sandal", "shirt", "sneaker", "bag", "ankle boot"}; String[] convertedLabels = new String[labelIndices.length]; for (int i = 0; i < labelIndices.length; i++) { convertedLabels[i] = textLabels[labelIndices[i]]; } return convertedLabels; } public String getFashionMnistLabel(int labelIndice) { String[] textLabels = {"t-shirt", "trouser", "pullover", "dress", "coat", "sandal", "shirt", "sneaker", "bag", "ankle boot"}; return textLabels[labelIndice]; } We can now create a function to visualize these examples. Don't worry too much about the specifics of visualization. This is simply just to help intuitively understand the data. We essentially read in a number of datapoints and convert their RGB value from 0-255 to between 0-1. We then set the color as grayscale and then display it along with their labels in an external window. .. code:: java // Saved in the FashionMnistUtils class for later use public static BufferedImage showImages( ArrayDataset dataset, int number, int width, int height, int scale, NDManager manager) { // Plot a list of images BufferedImage[] images = new BufferedImage[number]; String[] labels = new String[number]; for (int i = 0; i < number; i++) { Record record = dataset.get(manager, i); NDArray array = record.getData().get(0).squeeze(-1); int y = (int) record.getLabels().get(0).getFloat(); images[i] = toImage(array, width, height); labels[i] = getFashionMnistLabel(y); } int w = images[0].getWidth() * scale; int h = images[0].getHeight() * scale; return ImageUtils.showImages(images, labels, w, h); } private static BufferedImage toImage(NDArray array, int width, int height) { System.setProperty("apple.awt.UIElement", "true"); BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY); Graphics2D g = (Graphics2D) img.getGraphics(); for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { float c = array.getFloat(j, i) / 255; // scale down to between 0 and 1 g.setColor(new Color(c, c, c)); // set as a gray color g.fillRect(i, j, 1, 1); } } g.dispose(); return img; } Here are the images and their corresponding labels (in text) for the first few examples in the training dataset. .. code:: java final int SCALE = 4; final int WIDTH = 28; final int HEIGHT = 28; showImages(mnistTrain, 6, WIDTH, HEIGHT, SCALE, manager) .. figure:: output_image-classification-dataset_89a587_14_0.png Reading a Minibatch ------------------- To make our life easier when reading from the training and test sets, we use the ``getData(manager)``. Recall that at each iteration, ``getData(manager)`` reads a minibatch of data with size ``batchSize`` each time. We then get the X and y by calling ``getData()`` and ``getLabels()`` on each batch respectively. Note: During training, reading data can be a significant performance bottleneck, especially when our model is simple or when our computer is fast. Let us look at the time it takes to read the training data. .. code:: java StopWatch stopWatch = new StopWatch(); stopWatch.start(); for (Batch batch : mnistTrain.getData(manager)) { NDArray x = batch.getData().head(); NDArray y = batch.getLabels().head(); } System.out.println(String.format("%.2f sec", stopWatch.stop())); .. parsed-literal:: :class: output 0.21 sec We are now ready to work with the Fashion-MNIST dataset in the sections that follow. Summary ------- - Fashion-MNIST is an apparel classification dataset consisting of images representing 10 categories. - We will use this dataset in subsequent sections and chapters to evaluate various classification algorithms. - We store the shape of each image with height :math:`h` width :math:`w` pixels as :math:`h \times w` or ``(h, w)``. - Data iterators are a key component for efficient performance. Rely on well-implemented iterators that exploit multi-threading to avoid slowing down your training loop. Exercises --------- 1. Does reducing the ``batchSize`` (for instance, to 1) affect read performance? 2. Use the DJL documentation to see which other datasets are available in ``ai.djl.basicdataset``.