sampler.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import numpy as np
  15. from ...framework import core
  16. from ...tensor import randperm
  17. class Sampler:
  18. """
  19. An abstract class to encapsulate methods and behaviors of samplers.
  20. All sampler used by :code:`paddle.io.BatchSampler` should be a subclass
  21. of :code:`paddle.io.Sampler`, BatchSampler subclasses should
  22. implement following methods:
  23. :code:`__iter__`: return sample index iterably, which iterate over indices
  24. of dataset elements
  25. :code:`__len__`: the number of sample in :attr:`data_source`
  26. Args:
  27. data_source(Dataset, optional): this could be an instance of
  28. :code:`paddle.io.Dataset` other Python object which
  29. implemented :code:`__len__` for Sampler to get indices
  30. as the range of :attr:`dataset` length. Default None.
  31. Returns:
  32. Sampler: an iterable object for sample indices iterating
  33. Examples:
  34. .. code-block:: python
  35. >>> from paddle.io import Dataset, Sampler
  36. >>> class RandomDataset(Dataset):
  37. ... def __init__(self, num_samples):
  38. ... self.num_samples = num_samples
  39. ...
  40. ... def __getitem__(self, idx):
  41. ... image = np.random.random([784]).astype('float32')
  42. ... label = np.random.randint(0, 9, (1, )).astype('int64')
  43. ... return image, label
  44. ...
  45. ... def __len__(self):
  46. ... return self.num_samples
  47. ...
  48. >>> class MySampler(Sampler):
  49. ... def __init__(self, data_source):
  50. ... self.data_source = data_source
  51. ...
  52. ... def __iter__(self):
  53. ... return iter(range(len(self.data_source)))
  54. ...
  55. ... def __len__(self):
  56. ... return len(self.data_source)
  57. ...
  58. >>> sampler = MySampler(data_source=RandomDataset(100))
  59. >>> for index in sampler:
  60. ... print(index)
  61. 0
  62. 1
  63. 2
  64. ...
  65. 99
  66. see `paddle.io.BatchSampler`
  67. see `paddle.io.DataLoader`
  68. """
  69. def __init__(self, data_source=None):
  70. self.data_source = data_source
  71. def __iter__(self):
  72. raise NotImplementedError
  73. # Not define __len__ method in this base class here for __len__
  74. # is not needed in same sence, e.g. paddle.io.IterableDataset
  75. class SequenceSampler(Sampler):
  76. """
  77. Iterate samples sequentially, yield :code:`0, 1, 2, ..., len(data_source) -1`
  78. generally,
  79. Args:
  80. data_source(Dataset): dataset to sample, this could be an
  81. instance of :code:`paddle.io.Dataset` other Python
  82. object which implemented :code:`__len__`.
  83. Returns:
  84. Sampler: a Sampler yield sample index sequentially
  85. Examples:
  86. .. code-block:: python
  87. >>> from paddle.io import Dataset, SequenceSampler
  88. >>> class RandomDataset(Dataset):
  89. ... def __init__(self, num_samples):
  90. ... self.num_samples = num_samples
  91. ...
  92. ... def __getitem__(self, idx):
  93. ... image = np.random.random([784]).astype('float32')
  94. ... label = np.random.randint(0, 9, (1, )).astype('int64')
  95. ... return image, label
  96. ...
  97. ... def __len__(self):
  98. ... return self.num_samples
  99. ...
  100. >>> sampler = SequenceSampler(data_source=RandomDataset(100))
  101. >>> for index in sampler:
  102. ... print(index)
  103. 0
  104. 1
  105. 2
  106. ...
  107. 99
  108. see `paddle.io.Sampler`
  109. """
  110. def __init__(self, data_source):
  111. self.data_source = data_source
  112. def __iter__(self):
  113. return iter(range(len(self.data_source)))
  114. def __len__(self):
  115. return len(self.data_source)
  116. class RandomSampler(Sampler):
  117. """
  118. Iterate samples randomly, yield shuffled indices, if :attr:`replacement=False`,
  119. yield shuffled indices of the whole data source, if :attr:`replacement=True`,
  120. :attr:`num_samples` can set to specify the sample number to draw.
  121. Args:
  122. data_source(Dataset): dataset to sample, this could be an
  123. instance of :ref:`api_paddle_io_Dataset` or :ref:`api_paddle_io_IterableDataset` or other Python
  124. object which implemented :code:`__len__` to get indices as the range of :code:`dataset` length. Default None.
  125. replacement(bool, optional): If False, sample the whole dataset, If True,
  126. set :attr:`num_samples` for how many samples to draw. Default False.
  127. num_samples(int, optional): set sample number to draw. Default None, which is set to the length of `data_source`.
  128. generator(Generator, optional): specify a generator to sample the :code:`data_source`. Default None, disabled.
  129. Returns:
  130. RandomSampler: a Sampler yield sample index randomly.
  131. Examples:
  132. .. code-block:: python
  133. >>> import numpy as np
  134. >>> from paddle.io import Dataset, RandomSampler
  135. >>> np.random.seed(2023)
  136. >>> class RandomDataset(Dataset):
  137. ... def __init__(self, num_samples):
  138. ... self.num_samples = num_samples
  139. ...
  140. ... def __getitem__(self, idx):
  141. ... image = np.random.random([784]).astype('float32')
  142. ... label = np.random.randint(0, 9, (1, )).astype('int64')
  143. ... return image, label
  144. ...
  145. ... def __len__(self):
  146. ... return self.num_samples
  147. ...
  148. >>> sampler = RandomSampler(data_source=RandomDataset(100))
  149. >>> for index in sampler:
  150. ... print(index)
  151. 56
  152. 12
  153. 68
  154. ...
  155. 87
  156. """
  157. def __init__(
  158. self, data_source, replacement=False, num_samples=None, generator=None
  159. ):
  160. self.data_source = data_source
  161. self.replacement = replacement
  162. self._num_samples = num_samples
  163. self.generator = generator
  164. if not isinstance(self.replacement, bool):
  165. raise TypeError(
  166. "expect boolean value for replacement, but got "
  167. f"replacement={self.replacement}"
  168. )
  169. if not self.replacement and self.num_samples > len(self.data_source):
  170. raise ValueError(
  171. "num_samples should be smaller than or equal to length of data_source when replacement is False, "
  172. f"but got num_samples: {self.num_samples} > data_source: {len(self.data_source)}"
  173. )
  174. if not isinstance(self.num_samples, int) or self.num_samples <= 0:
  175. raise ValueError(
  176. "num_samples should be a positive integer, "
  177. f"but got num_samples={self.num_samples}"
  178. )
  179. @property
  180. def num_samples(self):
  181. if self._num_samples is None:
  182. return len(self.data_source)
  183. return self._num_samples
  184. def __iter__(self):
  185. n = len(self.data_source)
  186. if self.generator:
  187. for i in range(self.num_samples):
  188. try:
  189. index = next(self.generator)
  190. except StopIteration:
  191. return
  192. yield index
  193. else:
  194. if self.replacement:
  195. for index in np.random.choice(
  196. np.arange(n), self.num_samples, replace=True
  197. ).tolist():
  198. yield index
  199. else:
  200. for index in np.random.choice(
  201. np.arange(n), self.num_samples, replace=False
  202. ).tolist():
  203. yield index
  204. def __len__(self):
  205. return self.num_samples
  206. def _weighted_sample(weights, num_samples, replacement=True):
  207. if isinstance(weights, core.LoDTensor):
  208. weights = weights.numpy()
  209. if isinstance(weights, (list, tuple)):
  210. weights = np.array(weights)
  211. assert isinstance(
  212. weights, np.ndarray
  213. ), "weights should be paddle.Tensor, numpy.ndarray, list or tuple"
  214. assert len(weights.shape) <= 2, "weights should be a 1-D or 2-D array"
  215. weights = weights.reshape((-1, weights.shape[-1]))
  216. assert np.all(weights >= 0.0), "weights should be positive value"
  217. assert not np.any(weights == np.inf), "weights should not be INF"
  218. assert not np.any(weights == np.nan), "weights should not be NaN"
  219. non_zeros = np.sum(weights > 0.0, axis=1)
  220. assert np.all(non_zeros > 0), "weights should have positive values"
  221. if not replacement:
  222. assert np.all(non_zeros >= num_samples), (
  223. "weights positive value number should not "
  224. "less than num_samples when replacement=False"
  225. )
  226. weights = weights / weights.sum(axis=1)
  227. rets = []
  228. for i in range(weights.shape[0]):
  229. ret = np.random.choice(
  230. weights.shape[1], num_samples, replacement, weights[i]
  231. )
  232. rets.append(ret)
  233. return np.array(rets)
  234. class WeightedRandomSampler(Sampler):
  235. """
  236. Random sample with given weights (probabilities), sample index will be in range
  237. [0, len(weights) - 1], if :attr:`replacement` is True, index can be sampled
  238. multiple times.
  239. Args:
  240. weights(numpy.ndarray|paddle.Tensor|list|tuple): sequence of weights,
  241. should be numpy array, paddle.Tensor, list or tuple
  242. num_samples(int): set sample number to draw from sampler.
  243. replacement(bool): Whether to draw sample with replacements, default True
  244. Returns:
  245. Sampler: a Sampler yield sample index randomly by given weights
  246. Examples:
  247. .. code-block:: python
  248. >>> import numpy as np
  249. >>> from paddle.io import WeightedRandomSampler
  250. >>> np.random.seed(2023)
  251. >>> sampler = WeightedRandomSampler(
  252. ... weights=[0.1, 0.3, 0.5, 0.7, 0.2],
  253. ... num_samples=5,
  254. ... replacement=True
  255. ... )
  256. >>> for index in sampler:
  257. ... print(index)
  258. 2
  259. 4
  260. 3
  261. 1
  262. 1
  263. """
  264. def __init__(self, weights, num_samples, replacement=True):
  265. if not isinstance(num_samples, int) or num_samples <= 0:
  266. raise ValueError("num_samples should be a positive integer")
  267. if not isinstance(replacement, bool):
  268. raise ValueError("replacement should be a boolean value")
  269. self.weights = weights
  270. self.num_samples = num_samples
  271. self.replacement = replacement
  272. def __iter__(self):
  273. idxs = _weighted_sample(
  274. self.weights, self.num_samples, self.replacement
  275. )
  276. return iter(idxs.reshape(-1).tolist())
  277. def __len__(self):
  278. mul = np.prod(self.weights.shape) // self.weights.shape[-1]
  279. return self.num_samples * mul
  280. class SubsetRandomSampler(Sampler):
  281. r"""
  282. Randomly sample elements from a given list of indices, without replacement.
  283. Args:
  284. indices (sequence): a sequence of indices
  285. Examples:
  286. .. code-block:: python
  287. >>> import paddle
  288. >>> from paddle.io import SubsetRandomSampler
  289. >>> paddle.seed(2023)
  290. >>> sampler = SubsetRandomSampler(indices=[1, 3, 5, 7, 9])
  291. >>> for index in sampler:
  292. ... print(index)
  293. 9
  294. 3
  295. 7
  296. 5
  297. 1
  298. """
  299. def __init__(self, indices):
  300. if len(indices) == 0:
  301. raise ValueError(
  302. "The length of `indices` in SubsetRandomSampler should be greater than 0."
  303. )
  304. self.indices = indices
  305. def __iter__(self):
  306. for i in randperm(len(self.indices)):
  307. yield self.indices[i]
  308. def __len__(self) -> int:
  309. return len(self.indices)