sampler.py 11.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#   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 numpy as np

17
from ...framework import core
18 19


20
class Sampler:
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
    """
    An abstract class to encapsulate methods and behaviors of samplers.

    All sampler used by :code:`paddle.io.BatchSampler` should be a subclass
    of :code:`paddle.io.Sampler`, BatchSampler subclasses should
    implement following methods:

    :code:`__iter__`: return sample index iterably, which iterate over indices
    of dataset elements

    :code:`__len__`: the number of sample in :attr:`data_source`


    Args:
        data_source(Dataset, optional): this could be an instance of
                :code:`paddle.io.Dataset` other Python object which
                implemented :code:`__len__` for Sampler to get indices
                as the range of :attr:`dataset` length. Default None.

    Returns:
        Sampler: an iterable object for sample indices iterating

    Examples:
44

45
        .. code-block:: python
46

47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
            >>> from paddle.io import Dataset, Sampler

            >>> class RandomDataset(Dataset):
            ...     def __init__(self, num_samples):
            ...         self.num_samples = num_samples
            ...
            ...     def __getitem__(self, idx):
            ...         image = np.random.random([784]).astype('float32')
            ...         label = np.random.randint(0, 9, (1, )).astype('int64')
            ...         return image, label
            ...
            ...     def __len__(self):
            ...         return self.num_samples
            ...
            >>> class MySampler(Sampler):
            ...     def __init__(self, data_source):
            ...         self.data_source = data_source
            ...
            ...     def __iter__(self):
            ...         return iter(range(len(self.data_source)))
            ...
            ...     def __len__(self):
            ...         return len(self.data_source)
            ...
            >>> sampler = MySampler(data_source=RandomDataset(100))

            >>> for index in sampler:
            ...     print(index)
            0
            1
            2
            ...
            99
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 106 107 108 109 110 111

    see `paddle.io.BatchSampler`
    see `paddle.io.DataLoader`

    """

    def __init__(self, data_source=None):
        self.data_source = data_source

    def __iter__(self):
        raise NotImplementedError

    # Not define __len__ method in this base class here for __len__
    # is not needed in same sence, e.g. paddle.io.IterableDataset


class SequenceSampler(Sampler):
    """
    Iterate samples sequentially, yield :code:`0, 1, 2, ..., len(data_source) -1`
    generally,

    Args:
        data_source(Dataset): dataset to sample, this could be an
                instance of :code:`paddle.io.Dataset` other Python
                object which implemented :code:`__len__`.

    Returns:
        Sampler: a Sampler yield sample index sequentially

    Examples:

        .. code-block:: python
112

113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
            >>> from paddle.io import Dataset, SequenceSampler

            >>> class RandomDataset(Dataset):
            ...     def __init__(self, num_samples):
            ...         self.num_samples = num_samples
            ...
            ...     def __getitem__(self, idx):
            ...         image = np.random.random([784]).astype('float32')
            ...         label = np.random.randint(0, 9, (1, )).astype('int64')
            ...         return image, label
            ...
            ...     def __len__(self):
            ...         return self.num_samples
            ...
            >>> sampler = SequenceSampler(data_source=RandomDataset(100))

            >>> for index in sampler:
            ...     print(index)
            0
            1
            2
            ...
            99
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157

    see `paddle.io.Sampler`
    """

    def __init__(self, data_source):
        self.data_source = data_source

    def __iter__(self):
        return iter(range(len(self.data_source)))

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


class RandomSampler(Sampler):
    """
    Iterate samples randomly, yield shuffled indices, if :attr:`replacement=False`,
    yield shuffled indices of the whole data souce, if :attr:`replacement=True`,
    :attr:`num_samples` can set to specify the sample number to draw.

    Args:
        data_source(Dataset): dataset to sample, this could be an
1
1want2sleep 已提交
158 159 160 161 162 163 164
                instance of :ref:`api_paddle_io_Dataset` or :ref:`api_paddle_io_IterableDataset` or other Python
                object which implemented :code:`__len__` to get indices as the range of :code:`dataset` length. Default None.
        replacement(bool, optional): If False, sample the whole dataset, If True,
                set :attr:`num_samples` for how many samples to draw. Default False.
        num_samples(int, optional): set sample number to draw if :attr:`replacement`
                is True, then it will take samples according to the number you set. Default None, disabled.
        generator(Generator, optional): specify a generator to sample the :code:`data_source`. Default None, disabled.
165

166
    Returns:
1
1want2sleep 已提交
167
        RandomSampler: a Sampler yield sample index randomly.
168 169 170 171

    Examples:

        .. code-block:: python
172

173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
            >>> import numpy as np
            >>> from paddle.io import Dataset, RandomSampler

            >>> np.random.seed(2023)
            >>> class RandomDataset(Dataset):
            ...     def __init__(self, num_samples):
            ...         self.num_samples = num_samples
            ...
            ...     def __getitem__(self, idx):
            ...         image = np.random.random([784]).astype('float32')
            ...         label = np.random.randint(0, 9, (1, )).astype('int64')
            ...         return image, label
            ...
            ...     def __len__(self):
            ...         return self.num_samples
            ...
            >>> sampler = RandomSampler(data_source=RandomDataset(100))

            >>> for index in sampler:
            ...     print(index)
            56
            12
            68
            ...
            87
198 199
    """

200 201 202
    def __init__(
        self, data_source, replacement=False, num_samples=None, generator=None
    ):
203 204 205 206 207 208
        self.data_source = data_source
        self.replacement = replacement
        self._num_samples = num_samples
        self.generator = generator

        if not isinstance(self.replacement, bool):
209 210 211 212
            raise TypeError(
                "expect boolean value for replacement, but got "
                "replacement={}".format(self.replacement)
            )
213 214 215

        if self._num_samples is not None and not replacement:
            raise ValueError(
216 217
                "num_samples should not be specified while replacement is False"
            )
218 219

        if not isinstance(self.num_samples, int) or self.num_samples <= 0:
220 221 222 223
            raise ValueError(
                "num_samples should be a positive integer, "
                "but got num_samples={}".format(self.num_samples)
            )
224 225 226 227 228 229 230 231 232 233

    @property
    def num_samples(self):
        if self._num_samples is None:
            return len(self.data_source)
        return self._num_samples

    def __iter__(self):
        n = len(self.data_source)
        if self.generator:
234 235 236 237 238
            for i in range(self.num_samples):
                try:
                    index = next(self.generator)
                except StopIteration:
                    return
239 240 241
                yield index
        else:
            if self.replacement:
242 243 244
                for index in np.random.choice(
                    np.arange(n), self.num_samples, replace=True
                ).tolist():
245 246
                    yield index
            else:
247 248 249
                for index in np.random.choice(
                    np.arange(n), n, replace=False
                ).tolist():
250 251 252 253
                    yield index

    def __len__(self):
        return self.num_samples
254 255 256 257 258 259 260


def _weighted_sample(weights, num_samples, replacement=True):
    if isinstance(weights, core.LoDTensor):
        weights = weights.numpy()
    if isinstance(weights, (list, tuple)):
        weights = np.array(weights)
261 262 263 264
    assert isinstance(
        weights, np.ndarray
    ), "weights should be paddle.Tensor, numpy.ndarray, list or tuple"
    assert len(weights.shape) <= 2, "weights should be a 1-D or 2-D array"
265
    weights = weights.reshape((-1, weights.shape[-1]))
266 267 268 269 270 271
    assert np.all(weights >= 0.0), "weights should be positive value"
    assert not np.any(weights == np.inf), "weights shoule not be INF"
    assert not np.any(weights == np.nan), "weights shoule not be NaN"

    non_zeros = np.sum(weights > 0.0, axis=1)
    assert np.all(non_zeros > 0), "weights should have positive values"
272
    if not replacement:
273 274
        assert np.all(non_zeros >= num_samples), (
            "weights positive value number should not "
275
            "less than num_samples when replacement=False"
276
        )
277 278 279 280

    weights = weights / weights.sum(axis=1)
    rets = []
    for i in range(weights.shape[0]):
281 282 283
        ret = np.random.choice(
            weights.shape[1], num_samples, replacement, weights[i]
        )
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
        rets.append(ret)
    return np.array(rets)


class WeightedRandomSampler(Sampler):
    """
    Random sample with given weights (probabilities), sampe index will be in range
    [0, len(weights) - 1], if :attr:`replacement` is True, index can be sampled
    multiple times.

    Args:
        weights(numpy.ndarray|paddle.Tensor|list|tuple): sequence of weights,
                should be numpy array, paddle.Tensor, list or tuple
        num_samples(int): set sample number to draw from sampler.
        replacement(bool): Whether to draw sample with replacements, default True
299

300 301 302 303 304 305
    Returns:
        Sampler: a Sampler yield sample index randomly by given weights

    Examples:

        .. code-block:: python
306

307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
            >>> import numpy as np
            >>> from paddle.io import WeightedRandomSampler

            >>> np.random.seed(2023)
            >>> sampler = WeightedRandomSampler(
            ...     weights=[0.1, 0.3, 0.5, 0.7, 0.2],
            ...     num_samples=5,
            ...     replacement=True
            ... )
            >>> for index in sampler:
            ...     print(index)
            2
            4
            3
            1
            1
323 324 325 326 327 328 329 330 331 332 333 334
    """

    def __init__(self, weights, num_samples, replacement=True):
        if not isinstance(num_samples, int) or num_samples <= 0:
            raise ValueError("num_samples should be a positive integer")
        if not isinstance(replacement, bool):
            raise ValueError("replacement should be a boolean value")
        self.weights = weights
        self.num_samples = num_samples
        self.replacement = replacement

    def __iter__(self):
335 336 337
        idxs = _weighted_sample(
            self.weights, self.num_samples, self.replacement
        )
338
        return iter(idxs.reshape(-1).tolist())
339 340 341 342

    def __len__(self):
        mul = np.prod(self.weights.shape) // self.weights.shape[-1]
        return self.num_samples * mul