mnist.py 11.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#   Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import gzip
import struct
import numpy as np
19
from PIL import Image
20

21
import paddle
22
from paddle.io import Dataset
23
from paddle.dataset.common import _check_exists_and_download
24

25
__all__ = []
26 27 28 29


class MNIST(Dataset):
    """
30
    Implementation of `MNIST <http://yann.lecun.com/exdb/mnist/>`_ dataset.
31 32

    Args:
33 34 35 36 37 38 39 40 41 42 43
        image_path (str, optional): Path to image file, can be set None if
            :attr:`download` is True. Default: None, default data path: ~/.cache/paddle/dataset/mnist.
        label_path (str, optional): Path to label file, can be set None if
            :attr:`download` is True. Default: None, default data path: ~/.cache/paddle/dataset/mnist.
        mode (str, optional): Either train or test mode. Default 'train'.
        transform (Callable, optional): Transform to perform on image, None for no transform. Default: None.
        download (bool, optional): Download dataset automatically if
            :attr:`image_path` :attr:`label_path` is not set. Default: True.
        backend (str, optional): Specifies which type of image to be returned:
            PIL.Image or numpy.ndarray. Should be one of {'pil', 'cv2'}.
            If this option is not set, will get backend from :ref:`paddle.vision.get_image_backend <api_vision_image_get_image_backend>`,
44
            default backend is 'pil'. Default: None.
45

46
    Returns:
47
        :ref:`api_paddle_io_Dataset`. An instance of MNIST dataset.
48 49

    Examples:
50

51 52
        .. code-block:: python

53 54
            import itertools
            import paddle.vision.transforms as T
55
            from paddle.vision.datasets import MNIST
56 57


58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
            mnist = MNIST()
            print(len(mnist))
            # 60000

            for i in range(5):  # only show first 5 images
                img, label = mnist[i]
                # do something with img and label
                print(type(img), img.size, label)
                # <class 'PIL.Image.Image'> (28, 28) [5]


            transform = T.Compose(
                [
                    T.ToTensor(),
                    T.Normalize(
                        mean=[127.5],
                        std=[127.5],
                    ),
                ]
            )

            mnist_test = MNIST(
                mode="test",
                transform=transform,  # apply transform to every image
                backend="cv2",  # use OpenCV as image transform backend
            )
            print(len(mnist_test))
            # 10000

            for img, label in itertools.islice(iter(mnist_test), 5):  # only show first 5 images
                # do something with img and label
                print(type(img), img.shape, label)
                # <class 'paddle.Tensor'> [1, 28, 28] [7]
91
    """
L
LielinJiang 已提交
92 93 94 95 96 97 98 99 100 101
    NAME = 'mnist'
    URL_PREFIX = 'https://dataset.bj.bcebos.com/mnist/'
    TEST_IMAGE_URL = URL_PREFIX + 't10k-images-idx3-ubyte.gz'
    TEST_IMAGE_MD5 = '9fb629c4189551a2d022fa330f9573f3'
    TEST_LABEL_URL = URL_PREFIX + 't10k-labels-idx1-ubyte.gz'
    TEST_LABEL_MD5 = 'ec29112dd5afa0611ce80d1b7f02629c'
    TRAIN_IMAGE_URL = URL_PREFIX + 'train-images-idx3-ubyte.gz'
    TRAIN_IMAGE_MD5 = 'f68b3c2dcbeaaa9fbdd348bbdeb94873'
    TRAIN_LABEL_URL = URL_PREFIX + 'train-labels-idx1-ubyte.gz'
    TRAIN_LABEL_MD5 = 'd53e105ee54ea40749a09fcbcd1e9432'
102 103 104 105 106 107

    def __init__(self,
                 image_path=None,
                 label_path=None,
                 mode='train',
                 transform=None,
108 109
                 download=True,
                 backend=None):
110 111
        assert mode.lower() in ['train', 'test'], \
                "mode should be 'train' or 'test', but got {}".format(mode)
112 113 114 115 116

        if backend is None:
            backend = paddle.vision.get_image_backend()
        if backend not in ['pil', 'cv2']:
            raise ValueError(
117 118
                "Expected backend are one of ['pil', 'cv2'], but got {}".format(
                    backend))
119 120
        self.backend = backend

121 122 123
        self.mode = mode.lower()
        self.image_path = image_path
        if self.image_path is None:
K
Kaipeng Deng 已提交
124
            assert download, "image_path is not set and downloading automatically is disabled"
L
LielinJiang 已提交
125 126
            image_url = self.TRAIN_IMAGE_URL if mode == 'train' else self.TEST_IMAGE_URL
            image_md5 = self.TRAIN_IMAGE_MD5 if mode == 'train' else self.TEST_IMAGE_MD5
127
            self.image_path = _check_exists_and_download(
L
LielinJiang 已提交
128
                image_path, image_url, image_md5, self.NAME, download)
129 130 131

        self.label_path = label_path
        if self.label_path is None:
K
Kaipeng Deng 已提交
132
            assert download, "label_path is not set and downloading automatically is disabled"
L
LielinJiang 已提交
133 134
            label_url = self.TRAIN_LABEL_URL if self.mode == 'train' else self.TEST_LABEL_URL
            label_md5 = self.TRAIN_LABEL_MD5 if self.mode == 'train' else self.TEST_LABEL_MD5
135
            self.label_path = _check_exists_and_download(
L
LielinJiang 已提交
136
                label_path, label_url, label_md5, self.NAME, download)
137 138 139 140 141 142

        self.transform = transform

        # read dataset into memory
        self._parse_dataset()

143 144
        self.dtype = paddle.get_default_dtype()

145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
    def _parse_dataset(self, buffer_size=100):
        self.images = []
        self.labels = []
        with gzip.GzipFile(self.image_path, 'rb') as image_file:
            img_buf = image_file.read()
            with gzip.GzipFile(self.label_path, 'rb') as label_file:
                lab_buf = label_file.read()

                step_label = 0
                offset_img = 0
                # read from Big-endian
                # get file info from magic byte
                # image file : 16B
                magic_byte_img = '>IIII'
                magic_img, image_num, rows, cols = struct.unpack_from(
                    magic_byte_img, img_buf, offset_img)
                offset_img += struct.calcsize(magic_byte_img)

                offset_lab = 0
                # label file : 8B
                magic_byte_lab = '>II'
166 167
                magic_lab, label_num = struct.unpack_from(
                    magic_byte_lab, lab_buf, offset_lab)
168 169 170 171 172 173 174 175 176 177 178 179 180
                offset_lab += struct.calcsize(magic_byte_lab)

                while True:
                    if step_label >= label_num:
                        break
                    fmt_label = '>' + str(buffer_size) + 'B'
                    labels = struct.unpack_from(fmt_label, lab_buf, offset_lab)
                    offset_lab += struct.calcsize(fmt_label)
                    step_label += buffer_size

                    fmt_images = '>' + str(buffer_size * rows * cols) + 'B'
                    images_temp = struct.unpack_from(fmt_images, img_buf,
                                                     offset_img)
181 182 183
                    images = np.reshape(
                        images_temp,
                        (buffer_size, rows * cols)).astype('float32')
184 185 186 187 188 189 190 191 192
                    offset_img += struct.calcsize(fmt_images)

                    for i in range(buffer_size):
                        self.images.append(images[i, :])
                        self.labels.append(
                            np.array([labels[i]]).astype('int64'))

    def __getitem__(self, idx):
        image, label = self.images[idx], self.labels[idx]
193 194 195
        image = np.reshape(image, [28, 28])

        if self.backend == 'pil':
L
LielinJiang 已提交
196
            image = Image.fromarray(image.astype('uint8'), mode='L')
197

198 199
        if self.transform is not None:
            image = self.transform(image)
200 201 202 203

        if self.backend == 'pil':
            return image, label.astype('int64')

204
        return image.astype(self.dtype), label.astype('int64')
205 206 207

    def __len__(self):
        return len(self.labels)
L
LielinJiang 已提交
208 209 210 211


class FashionMNIST(MNIST):
    """
212
    Implementation of `Fashion-MNIST <https://github.com/zalandoresearch/fashion-mnist>`_ dataset.
L
LielinJiang 已提交
213 214

    Args:
215 216 217 218 219 220 221 222 223 224 225
        image_path (str, optional): Path to image file, can be set None if
            :attr:`download` is True. Default: None, default data path: ~/.cache/paddle/dataset/fashion-mnist.
        label_path (str, optional): Path to label file, can be set None if
            :attr:`download` is True. Default: None, default data path: ~/.cache/paddle/dataset/fashion-mnist.
        mode (str, optional): Either train or test mode. Default 'train'.
        transform (Callable, optional): Transform to perform on image, None for no transform. Default: None.
        download (bool, optional): Whether to download dataset automatically if
            :attr:`image_path` :attr:`label_path` is not set. Default: True.
        backend (str, optional): Specifies which type of image to be returned:
            PIL.Image or numpy.ndarray. Should be one of {'pil', 'cv2'}.
            If this option is not set, will get backend from :ref:`paddle.vision.get_image_backend <api_vision_image_get_image_backend>`,
L
LielinJiang 已提交
226
            default backend is 'pil'. Default: None.
227

L
LielinJiang 已提交
228
    Returns:
229
        :ref:`api_paddle_io_Dataset`. An instance of FashionMNIST dataset.
L
LielinJiang 已提交
230 231

    Examples:
232

L
LielinJiang 已提交
233 234
        .. code-block:: python

235 236
            import itertools
            import paddle.vision.transforms as T
L
LielinJiang 已提交
237 238 239
            from paddle.vision.datasets import FashionMNIST


240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
            fashion_mnist = FashionMNIST()
            print(len(fashion_mnist))
            # 60000

            for i in range(5):  # only show first 5 images
                img, label = fashion_mnist[i]
                # do something with img and label
                print(type(img), img.size, label)
                # <class 'PIL.Image.Image'> (28, 28) [9]


            transform = T.Compose(
                [
                    T.ToTensor(),
                    T.Normalize(
                        mean=[127.5],
                        std=[127.5],
                    ),
                ]
            )

            fashion_mnist_test = FashionMNIST(
                mode="test",
                transform=transform,  # apply transform to every image
                backend="cv2",  # use OpenCV as image transform backend
            )
            print(len(fashion_mnist_test))
            # 10000

            for img, label in itertools.islice(iter(fashion_mnist_test), 5):  # only show first 5 images
                # do something with img and label
                print(type(img), img.shape, label)
                # <class 'paddle.Tensor'> [1, 28, 28] [9]
L
LielinJiang 已提交
273 274 275 276 277 278 279 280 281 282 283 284
    """

    NAME = 'fashion-mnist'
    URL_PREFIX = 'https://dataset.bj.bcebos.com/fashion_mnist/'
    TEST_IMAGE_URL = URL_PREFIX + 't10k-images-idx3-ubyte.gz'
    TEST_IMAGE_MD5 = 'bef4ecab320f06d8554ea6380940ec79'
    TEST_LABEL_URL = URL_PREFIX + 't10k-labels-idx1-ubyte.gz'
    TEST_LABEL_MD5 = 'bb300cfdad3c16e7a12a480ee83cd310'
    TRAIN_IMAGE_URL = URL_PREFIX + 'train-images-idx3-ubyte.gz'
    TRAIN_IMAGE_MD5 = '8d4fb7e6c68d591d4c3dfef9ec88bf0d'
    TRAIN_LABEL_URL = URL_PREFIX + 'train-labels-idx1-ubyte.gz'
    TRAIN_LABEL_MD5 = '25c81989df183df01b3e8a0aad5dffbe'