cifar.py 9.1 KB
Newer Older
K
Kaipeng Deng 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#   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.

from __future__ import print_function

import tarfile
import numpy as np
import six
20
from PIL import Image
K
Kaipeng Deng 已提交
21 22
from six.moves import cPickle as pickle

23
import paddle
K
Kaipeng Deng 已提交
24
from paddle.io import Dataset
25
from paddle.dataset.common import _check_exists_and_download
K
Kaipeng Deng 已提交
26

27
__all__ = []
K
Kaipeng Deng 已提交
28 29 30 31 32 33 34 35 36 37 38

URL_PREFIX = 'https://dataset.bj.bcebos.com/cifar/'
CIFAR10_URL = URL_PREFIX + 'cifar-10-python.tar.gz'
CIFAR10_MD5 = 'c58f30108f718f92721af3b95e74349a'
CIFAR100_URL = URL_PREFIX + 'cifar-100-python.tar.gz'
CIFAR100_MD5 = 'eb9058c3a382ffc7106e4002c42a8d85'

MODE_FLAG_MAP = {
    'train10': 'data_batch',
    'test10': 'test_batch',
    'train100': 'train',
L
Ligoml 已提交
39
    'test100': 'test',
K
Kaipeng Deng 已提交
40 41 42 43 44 45 46 47 48
}


class Cifar10(Dataset):
    """
    Implementation of `Cifar-10 <https://www.cs.toronto.edu/~kriz/cifar.html>`_
    dataset, which has 10 categories.

    Args:
49
        data_file (str, optional): Path to data file, can be set None if
50
            :attr:`download` is True. Default None, default data path: ~/.cache/paddle/dataset/cifar
51 52 53 54 55 56
        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:`data_file` is None. 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>`,
57
            default backend is 'pil'. Default: None.
K
Kaipeng Deng 已提交
58 59

    Returns:
60
        :ref:`api_paddle_io_Dataset`. An instance of Cifar10 dataset.
K
Kaipeng Deng 已提交
61 62 63 64 65

    Examples:

        .. code-block:: python

66 67
            import itertools
            import paddle.vision.transforms as T
68
            from paddle.vision.datasets import Cifar10
K
Kaipeng Deng 已提交
69 70


71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
            cifar10 = Cifar10()
            print(len(cifar10))
            # 50000

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


            transform = T.Compose(
                [
                    T.Resize(64),
                    T.ToTensor(),
                    T.Normalize(
                        mean=[0.5, 0.5, 0.5],
                        std=[0.5, 0.5, 0.5],
                        to_rgb=True,
                    ),
                ]
            )

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

            for img, label in itertools.islice(iter(cifar10_test), 5):  # only show first 5 images
                # do something with img and label
                print(type(img), img.shape, label)
                # <class 'paddle.Tensor'> [3, 64, 64] 3
K
Kaipeng Deng 已提交
106 107
    """

L
Ligoml 已提交
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
    def __init__(
        self,
        data_file=None,
        mode='train',
        transform=None,
        download=True,
        backend=None,
    ):
        assert mode.lower() in [
            'train',
            'test',
            'train',
            'test',
        ], "mode should be 'train10', 'test10', 'train100' or 'test100', but got {}".format(
            mode
        )
K
Kaipeng Deng 已提交
124 125
        self.mode = mode.lower()

126 127 128 129
        if backend is None:
            backend = paddle.vision.get_image_backend()
        if backend not in ['pil', 'cv2']:
            raise ValueError(
130
                "Expected backend are one of ['pil', 'cv2'], but got {}".format(
L
Ligoml 已提交
131 132 133
                    backend
                )
            )
134 135
        self.backend = backend

K
Kaipeng Deng 已提交
136 137 138 139
        self._init_url_md5_flag()

        self.data_file = data_file
        if self.data_file is None:
L
Ligoml 已提交
140 141 142 143 144 145
            assert (
                download
            ), "data_file is not set and downloading automatically is disabled"
            self.data_file = _check_exists_and_download(
                data_file, self.data_url, self.data_md5, 'cifar', download
            )
K
Kaipeng Deng 已提交
146 147 148 149 150 151

        self.transform = transform

        # read dataset into memory
        self._load_data()

152 153
        self.dtype = paddle.get_default_dtype()

K
Kaipeng Deng 已提交
154 155 156 157 158 159 160 161
    def _init_url_md5_flag(self):
        self.data_url = CIFAR10_URL
        self.data_md5 = CIFAR10_MD5
        self.flag = MODE_FLAG_MAP[self.mode + '10']

    def _load_data(self):
        self.data = []
        with tarfile.open(self.data_file, mode='r') as f:
L
Ligoml 已提交
162 163 164
            names = (
                each_item.name for each_item in f if self.flag in each_item.name
            )
K
Kaipeng Deng 已提交
165

166 167
            names = sorted(list(names))

K
Kaipeng Deng 已提交
168
            for name in names:
T
tianshuo78520a 已提交
169
                batch = pickle.load(f.extractfile(name), encoding='bytes')
K
Kaipeng Deng 已提交
170 171

                data = batch[six.b('data')]
L
Ligoml 已提交
172 173 174
                labels = batch.get(
                    six.b('labels'), batch.get(six.b('fine_labels'), None)
                )
K
Kaipeng Deng 已提交
175 176
                assert labels is not None
                for sample, label in six.moves.zip(data, labels):
177
                    self.data.append((sample, label))
K
Kaipeng Deng 已提交
178 179 180

    def __getitem__(self, idx):
        image, label = self.data[idx]
181
        image = np.reshape(image, [3, 32, 32])
182 183 184
        image = image.transpose([1, 2, 0])

        if self.backend == 'pil':
L
LielinJiang 已提交
185
            image = Image.fromarray(image.astype('uint8'))
K
Kaipeng Deng 已提交
186 187
        if self.transform is not None:
            image = self.transform(image)
188 189

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

192
        return image.astype(self.dtype), np.array(label).astype('int64')
K
Kaipeng Deng 已提交
193 194 195 196 197 198 199 200 201 202 203

    def __len__(self):
        return len(self.data)


class Cifar100(Cifar10):
    """
    Implementation of `Cifar-100 <https://www.cs.toronto.edu/~kriz/cifar.html>`_
    dataset, which has 100 categories.

    Args:
204 205 206 207 208 209 210 211
        data_file (str, optional): path to data file, can be set None if
            :attr:`download` is True. Default: None, default data path: ~/.cache/paddle/dataset/cifar
        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:`data_file` is None. 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>`,
212
            default backend is 'pil'. Default: None.
K
Kaipeng Deng 已提交
213 214

    Returns:
215
        :ref:`api_paddle_io_Dataset`. An instance of Cifar100 dataset.
K
Kaipeng Deng 已提交
216 217 218 219 220

    Examples:

        .. code-block:: python

221 222
            import itertools
            import paddle.vision.transforms as T
223
            from paddle.vision.datasets import Cifar100
K
Kaipeng Deng 已提交
224 225


226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
            cifar100 = Cifar100()
            print(len(cifar100))
            # 50000

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


            transform = T.Compose(
                [
                    T.Resize(64),
                    T.ToTensor(),
                    T.Normalize(
                        mean=[0.5, 0.5, 0.5],
                        std=[0.5, 0.5, 0.5],
                        to_rgb=True,
                    ),
                ]
            )

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

            for img, label in itertools.islice(iter(cifar100_test), 5):  # only show first 5 images
                # do something with img and label
                print(type(img), img.shape, label)
                # <class 'paddle.Tensor'> [3, 64, 64] 49
K
Kaipeng Deng 已提交
261 262
    """

L
Ligoml 已提交
263 264 265 266 267 268 269 270 271 272 273
    def __init__(
        self,
        data_file=None,
        mode='train',
        transform=None,
        download=True,
        backend=None,
    ):
        super(Cifar100, self).__init__(
            data_file, mode, transform, download, backend
        )
K
Kaipeng Deng 已提交
274 275 276 277 278

    def _init_url_md5_flag(self):
        self.data_url = CIFAR100_URL
        self.data_md5 = CIFAR100_MD5
        self.flag = MODE_FLAG_MAP[self.mode + '100']