This API creates a decorated reader that outputs the shuffled data. The output data from the origin reader will be saved into a buffer, and then shuffle the data. The size of buffer is determined by argument buf_size. Args: reader(callable): the original reader whose data
(reader: _Reader[_T], buf_size: int)
| 199 | |
| 200 | |
| 201 | def shuffle(reader: _Reader[_T], buf_size: int) -> _Reader[_T]: |
| 202 | """ |
| 203 | This API creates a decorated reader that outputs the shuffled data. |
| 204 | |
| 205 | The output data from the origin reader will be saved into a buffer, |
| 206 | and then shuffle the data. The size of buffer is determined by argument buf_size. |
| 207 | |
| 208 | Args: |
| 209 | reader(callable): the original reader whose data will be shuffled. |
| 210 | buf_size(int): the size of shuffled buffer. |
| 211 | |
| 212 | Returns: |
| 213 | callable: a decorated reader. |
| 214 | |
| 215 | Examples: |
| 216 | .. code-block:: pycon |
| 217 | |
| 218 | >>> # doctest: +SKIP('outputs are 0~4 unordered arrangement') |
| 219 | >>> def reader(): |
| 220 | ... for i in range(5): |
| 221 | ... yield i |
| 222 | >>> shuffled_reader = paddle.reader.decorator.shuffle(reader, 3) |
| 223 | >>> for e in shuffled_reader(): |
| 224 | ... print(e) |
| 225 | >>> # outputs are 0~4 unordered arrangement |
| 226 | """ |
| 227 | |
| 228 | def data_reader() -> Generator[_T, None, None]: |
| 229 | buf = [] |
| 230 | for e in reader(): |
| 231 | buf.append(e) |
| 232 | if len(buf) >= buf_size: |
| 233 | random.shuffle(buf) |
| 234 | for b in buf: |
| 235 | yield b |
| 236 | buf = [] |
| 237 | |
| 238 | if len(buf) > 0: |
| 239 | random.shuffle(buf) |
| 240 | for b in buf: |
| 241 | yield b |
| 242 | |
| 243 | return data_reader |
| 244 | |
| 245 | |
| 246 | def chain(*readers: _Reader[_T]) -> _Reader[_T]: |
no outgoing calls