reader.py 25.5 KB
Newer Older
S
sneaxiy 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# Copyright (c) 2019 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.

15
from . import core, dygraph
16
import sys
S
sneaxiy 已提交
17
import six
18 19
import warnings
import numpy as np
S
sneaxiy 已提交
20
import threading
21 22
import paddle
from .framework import Program, Variable, program_guard, default_main_program, default_startup_program, in_dygraph_mode
S
sneaxiy 已提交
23
from .executor import global_scope
24
from .data_feeder import DataFeeder, BatchedTensorProvider, ListTensorProvider
S
sneaxiy 已提交
25
from .layers.io import monkey_patch_reader_methods, _copy_reader_var_, double_buffer
S
sneaxiy 已提交
26
from .unique_name import UniqueNameGenerator
27
import logging
S
sneaxiy 已提交
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46

__all__ = ['PyReader']


def _convert_places(places):
    if not isinstance(places, (list, tuple)):
        places = [places]

    ret = []
    for p in places:
        if not isinstance(p, core.Place):
            tmp = core.Place()
            tmp.set_place(p)
            p = tmp

        ret.append(p)
    return ret


S
sneaxiy 已提交
47
class PyReader(object):
S
sneaxiy 已提交
48 49 50 51 52 53 54 55
    """
    Create a reader object for data feeding in Python. 
    Data would be prefetched using Python thread and be pushed
    into a queue asynchronously. Data in the queue would be extracted 
    automatically when `Executor.run(...)` is called.

    Args:  
        feed_list (list(Variable)|tuple(Variable)): feed variable list.
56 57
            The variables should be created by :code:`fluid.layers.data()`.
            it can be None under iterable mode.
S
sneaxiy 已提交
58 59 60 61
        capacity (int): capacity of the queue maintained in PyReader object. 
        use_double_buffer (bool): whether to use double_buffer_reader to 
            speed up data feeding. 
        iterable (bool): whether the created reader object is iterable.   
62
        return_list (bool): whether the return value presented as list.
S
sneaxiy 已提交
63 64 65 66 67 68 69 70 71 72 73 74 75
    Returns:
        reader (Reader): the created reader object.

    Examples:
        1. If iterable = False, the created PyReader object is almost the
           same as :code:`fluid.layers.py_reader()`. Operators would be 
           inserted into the program. User should call :code:`start()` 
           before each epoch and catch :code:`fluid.core.EOFException`
           thrown by :code:`Executor.run()` when epoch ends. Once the 
           exception is caught, user should call :code:`reset()` to reset 
           the reader manually.

        .. code-block:: python
76

H
Huihuang Zheng 已提交
77 78 79 80
           import paddle
           import paddle.fluid as fluid
           import numpy as np

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 112 113 114 115 116 117
           EPOCH_NUM = 3
           ITER_NUM = 5
           BATCH_SIZE = 3

           def reader_creator_random_image_and_label(height, width):
               def reader():
                   for i in range(ITER_NUM):
                       fake_image = np.random.uniform(low=0,
                                                      high=255,
                                                      size=[height, width])
                       fake_label = np.ones([1])
                       yield fake_image, fake_label
               return reader

           image = fluid.layers.data(name='image', shape=[784, 784], dtype='float32')
           label = fluid.layers.data(name='label', shape=[1], dtype='int64')

           reader = fluid.io.PyReader(feed_list=[image, label],
                                      capacity=4,
                                      iterable=False)

           user_defined_reader = reader_creator_random_image_and_label(784, 784)
           reader.decorate_sample_list_generator(
               paddle.batch(user_defined_reader, batch_size=BATCH_SIZE))
           # definition of network is omitted
           executor = fluid.Executor(fluid.CUDAPlace(0))
           executor.run(fluid.default_startup_program())
           for i in range(EPOCH_NUM):
               reader.start()
               while True:
                   try:
                       executor.run(feed=None)
                   except fluid.core.EOFException:
                       reader.reset()
                       break

 
S
sneaxiy 已提交
118 119 120 121 122 123 124 125
        2. If iterable=True, the created PyReader object is decoupled with
           the program. No operator would be inserted into the program. 
           In this case, the created reader is a Python generator, which 
           is iterable. User should feed the data yielded from PyReader 
           object into :code:`Executor.run(feed=...)`.  

        .. code-block:: python

H
Huihuang Zheng 已提交
126 127 128 129
           import paddle
           import paddle.fluid as fluid
           import numpy as np

130 131 132 133 134 135 136 137 138 139 140
           EPOCH_NUM = 3
           ITER_NUM = 5
           BATCH_SIZE = 10

           def reader_creator_random_image(height, width):
               def reader():
                   for i in range(ITER_NUM):
                       yield np.random.uniform(low=0, high=255, size=[height, width]),
               return reader

           image = fluid.layers.data(name='image', shape=[784, 784], dtype='float32')
141
           reader = fluid.io.PyReader(feed_list=[image], capacity=4, iterable=True, return_list=False)
142 143 144 145 146 147 148 149 150 151 152 153 154

           user_defined_reader = reader_creator_random_image(784, 784)
           reader.decorate_sample_list_generator(
               paddle.batch(user_defined_reader, batch_size=BATCH_SIZE),
               fluid.core.CUDAPlace(0))
           # definition of network is omitted
           executor = fluid.Executor(fluid.CUDAPlace(0))
           executor.run(fluid.default_main_program())

           for _ in range(EPOCH_NUM):
               for data in reader():
                   executor.run(feed=data)

155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187

        3. If return_list=True, the return values would be presented as list instead of dict`.

        .. code-block:: python

            import paddle
            import paddle.fluid as fluid
            import numpy as np

            EPOCH_NUM = 3
            ITER_NUM = 5
            BATCH_SIZE = 10

            def reader_creator_random_image(height, width):
                def reader():
                    for i in range(ITER_NUM):
                        yield np.random.uniform(low=0, high=255, size=[height, width]),
                return reader

            image = fluid.layers.data(name='image', shape=[784, 784], dtype='float32')
            reader = fluid.io.PyReader(feed_list=[image], capacity=4, iterable=True, return_list=True)

            user_defined_reader = reader_creator_random_image(784, 784)
            reader.decorate_sample_list_generator(
                paddle.batch(user_defined_reader, batch_size=BATCH_SIZE),
                fluid.core.CPUPlace())
            # definition of network is omitted
            executor = fluid.Executor(fluid.core.CPUPlace())
            executor.run(fluid.default_main_program())

            for _ in range(EPOCH_NUM):
                for data in reader():
                    executor.run(feed={"image": data[0]})
S
sneaxiy 已提交
188 189
    """

S
sneaxiy 已提交
190
    unique_name_generator = UniqueNameGenerator()
S
sneaxiy 已提交
191 192

    def __init__(self,
193 194
                 feed_list=None,
                 capacity=None,
S
sneaxiy 已提交
195
                 use_double_buffer=True,
196 197
                 iterable=True,
                 return_list=False):
S
sneaxiy 已提交
198 199
        self._tensor_reader = None
        self._thread = None
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
        self._feed_list = feed_list
        if not capacity:
            raise ValueError("Please give value to capacity.")
        # force to use iterable mode under dygraph mode
        if in_dygraph_mode():
            if not iterable:
                warnings.warn(
                    "Please NOTE: dygraph can support iterable mode only.")
            self._iterable = True
            if not return_list:
                warnings.warn(
                    "Please NOTE: dygraph can support return as list only.")
            self._return_list = True
        else:
            self._iterable = iterable
            self._return_list = return_list
            if not self._feed_list:
                raise Exception("Feed list must be given under static mode.")
S
sneaxiy 已提交
218 219 220 221
        self._use_double_buffer = use_double_buffer
        self._capacity = capacity
        if not self._iterable:
            self._init_non_iterable()
S
sneaxiy 已提交
222

S
sneaxiy 已提交
223
    def _init_iterable(self, places):
224 225 226 227
        if in_dygraph_mode():
            self._var_names = []
        else:
            self._var_names = [v.name for v in self._feed_list]
S
sneaxiy 已提交
228
        self._places = _convert_places(places)
S
sneaxiy 已提交
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
        self._queue = core.init_lod_tensor_blocking_queue(core.Variable(),
                                                          self._capacity)
        self._reader = core.create_py_reader(
            self.queue, self._var_names, self._places, self._use_double_buffer)

    def _init_non_iterable(self):
        lod_levels = []
        dtypes = []
        shape_concat = []
        ranks = []
        shapes = []

        for feed_data in self._feed_list:
            dtypes.append(feed_data.dtype)
            shape_concat.extend(feed_data.shape)
            ranks.append(len(feed_data.shape))
            shapes.append(feed_data.shape)
            lod_levels.append(feed_data.lod_level)

        queue_name = PyReader.unique_name_generator('lod_tensor_blocking_queue')
        reader_name = PyReader.unique_name_generator('create_py_reader')
        double_buffer_name = PyReader.unique_name_generator('double_buffer')

S
sneaxiy 已提交
252
        var = global_scope().var(queue_name)
S
sneaxiy 已提交
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
        self._queue = core.init_lod_tensor_blocking_queue(var, self._capacity)

        startup_blk = default_startup_program().current_block()
        startup_var = startup_blk.create_var(name=reader_name)

        startup_blk.append_op(
            type='create_py_reader',
            inputs={'blocking_queue': [queue_name]},
            outputs={'Out': [startup_var]},
            attrs={
                'shape_concat': shape_concat,
                'lod_levels': lod_levels,
                'ranks': ranks
            })

        startup_var.desc.set_dtypes(dtypes)
        startup_var.persistable = True

        main_prog_var = _copy_reader_var_(
            default_main_program().current_block(), startup_var)

        main_prog_var.stop_gradient = True
        main_prog_var.persistable = True

        reader = monkey_patch_reader_methods(main_prog_var)
        if self._use_double_buffer:
            double_buffer_reader = double_buffer(
                reader, name=double_buffer_name)
            # we return a double buffer reader. However, the reset method comes from
            # py_reader.
            double_buffer_reader.reset = reader.reset
            reader = double_buffer_reader

        self._reader = reader

        default_main_program().current_block().append_op(
            type='read',
            inputs={'Reader': [self._reader]},
            outputs={'Out': self._feed_list})

    @property
    def queue(self):
        return self._queue

    @property
    def iterable(self):
        return self._iterable
S
sneaxiy 已提交
300 301

    def __call__(self):
S
sneaxiy 已提交
302
        assert self.iterable, "PyReader is not iterable"
S
sneaxiy 已提交
303 304 305 306 307
        assert self._tensor_reader is not None, \
            "Data source of PyReader has not set yet"

        class Iterator(object):
            def __init__(self, reader):
S
sneaxiy 已提交
308 309
                self._reader = reader._reader
                self._reset = reader._reset
310
                self._return_list = reader._return_list
S
sneaxiy 已提交
311 312 313 314

            def __iter__(self):
                return self

S
sneaxiy 已提交
315 316 317
            def __next__(self):
                return self.next()

S
sneaxiy 已提交
318
            def next(self):
319 320 321 322 323 324 325 326 327 328 329 330
                if not in_dygraph_mode():
                    if self._return_list:
                        ret = self._reader.read_next_list()
                        ret = ret[0] if ret is not None and len(
                            ret) > 0 else None
                    else:
                        ret = self._reader.read_next()
                    if ret:
                        return ret
                    else:
                        self._reset()
                        raise StopIteration
S
sneaxiy 已提交
331
                else:
332 333 334 335 336 337 338 339 340
                    ret = self._reader.read_next_list()
                    if ret and ret[0]:
                        return [
                            dygraph.base.to_variable(np.array(v))
                            for v in ret[0]
                        ]
                    else:
                        self._reset()
                        raise StopIteration
S
sneaxiy 已提交
341

S
sneaxiy 已提交
342
        self._start()
S
sneaxiy 已提交
343 344
        return Iterator(self)

S
sneaxiy 已提交
345
    def _reset(self):
S
sneaxiy 已提交
346 347 348 349
        self._reader.reset()
        self._thread.join()

    def start(self):
S
add doc  
sneaxiy 已提交
350 351 352
        '''
        Start the data feeding thread. 
        Can only call when the reader object is not iterable.  
353 354 355
        
	Example:
	    .. code-block:: python
H
Huihuang Zheng 已提交
356 357 358 359 360

                import paddle
                import paddle.fluid as fluid
                import numpy as np

361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
                BATCH_SIZE = 10

                def generator():
                    for i in range(5):
                        yield np.random.uniform(low=0, high=255, size=[784, 784]),

                image = fluid.layers.data(name='image', shape=[784, 784], dtype='float32')
                reader = fluid.io.PyReader(feed_list=[image], capacity=4, iterable=False)
                reader.decorate_sample_list_generator(
                    paddle.batch(generator, batch_size=BATCH_SIZE))

                executor = fluid.Executor(fluid.CUDAPlace(0))
                executor.run(fluid.default_startup_program())
                for i in range(3):
                    reader.start()
                    while True:
                        try:
                            executor.run(feed=None)
                        except fluid.core.EOFException:
                            reader.reset()
                            break

	'''
384 385 386
        if not in_dygraph_mode():
            assert not self._iterable, "start() cannot be called when PyReader is iterable"
            self._start()
S
sneaxiy 已提交
387

S
sneaxiy 已提交
388
    def reset(self):
S
add doc  
sneaxiy 已提交
389 390 391
        '''
        Reset the reader object when :code:`fluid.core.EOFException` raises. 
        Can only call when the reader object is not iterable.
392 393 394 395
        
        Example:
            .. code-block:: python

H
Huihuang Zheng 已提交
396 397 398 399
                import paddle
                import paddle.fluid as fluid
                import numpy as np

400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
                BATCH_SIZE = 10

                def generator():
                    for i in range(5):
                        yield np.random.uniform(low=0, high=255, size=[784, 784]),

                image = fluid.layers.data(name='image', shape=[784, 784], dtype='float32')
                reader = fluid.io.PyReader(feed_list=[image], capacity=4, iterable=False)
                reader.decorate_sample_list_generator(
                    paddle.batch(generator, batch_size=BATCH_SIZE))

                executor = fluid.Executor(fluid.CUDAPlace(0))
                executor.run(fluid.default_startup_program())
                for i in range(3):
                    reader.start()
                    while True:
                        try:
                            executor.run(feed=None)
                        except fluid.core.EOFException:
                            reader.reset()
                            break        

S
add doc  
sneaxiy 已提交
422
        '''
423 424 425
        if not in_dygraph_mode():
            assert not self._iterable, "reset() cannot be called when PyReader is iterable"
            self._reset()
S
sneaxiy 已提交
426 427

    def _start(self):
S
sneaxiy 已提交
428
        def __thread_main__():
S
sneaxiy 已提交
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
            try:
                for tensors in self._tensor_reader():
                    array = core.LoDTensorArray()
                    for item in tensors:
                        if not isinstance(item, core.LoDTensor):
                            tmp = core.LoDTensor()
                            tmp.set(item, core.CPUPlace())
                            item = tmp

                        array.append(item)

                    if not self._queue.push(array):
                        break

                self._queue.close()
            except Exception as ex:
                self._queue.close()
446
                logging.warn('Your decorated reader has raised an exception!')
447
                six.reraise(*sys.exc_info())
S
sneaxiy 已提交
448 449 450 451 452

        self._thread = threading.Thread(target=__thread_main__)
        self._thread.daemon = True
        self._thread.start()

S
sneaxiy 已提交
453 454 455 456 457 458 459 460 461
    def decorate_sample_generator(self,
                                  sample_generator,
                                  batch_size,
                                  drop_last=True,
                                  places=None):
        '''
        Set the data source of the PyReader object.
        
        The provided :code:`sample_generator` should be a Python generator,
462
        which yields list(numpy.ndarray)-typed data of each sample.
S
sneaxiy 已提交
463 464 465 466

        :code:`places` must be set when the PyReader object is iterable.

        If all inputs have no lods, this method is faster than 
S
sneaxiy 已提交
467
        :code:`decorate_sample_list_generator(paddle.batch(sample_generator, ...))` .
S
sneaxiy 已提交
468 469 470

        Args:
            sample_generator (generator): Python generator that yields
471
                list(numpy.ndarray)-typed sample data.
S
sneaxiy 已提交
472 473 474 475 476
            batch_size (int): batch size. Must be larger than 0.
            drop_last (bool): Whether to drop the last batch when sample number
                is less than batch_size. 
            places (None|list(CUDAPlace)|list(CPUPlace)): place list. Must
                be provided when PyReader is iterable.
477 478 479 480

        Example:
            .. code-block:: python

H
Huihuang Zheng 已提交
481 482 483
                import paddle.fluid as fluid
                import numpy as np

484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
                EPOCH_NUM = 3
                ITER_NUM = 15
                BATCH_SIZE = 3

                def random_image_and_label_generator(height, width):
                    def generator():
                        for i in range(ITER_NUM):
                            fake_image = np.random.uniform(low=0,
                                                           high=255,
                                                           size=[height, width])
                            fake_label = np.array([1])
                            yield fake_image, fake_label
                    return generator

                image = fluid.layers.data(name='image', shape=[784, 784], dtype='float32')
                label = fluid.layers.data(name='label', shape=[1], dtype='int32')
                reader = fluid.io.PyReader(feed_list=[image, label], capacity=4, iterable=True)

                user_defined_generator = random_image_and_label_generator(784, 784)
                reader.decorate_sample_generator(user_defined_generator,
                                                 batch_size=BATCH_SIZE,
                                                 places=[fluid.CUDAPlace(0)])
                # definition of network is omitted
                executor = fluid.Executor(fluid.CUDAPlace(0))
                executor.run(fluid.default_main_program())

                for _ in range(EPOCH_NUM):
                    for data in reader():
                        executor.run(feed=data)
    
S
sneaxiy 已提交
514 515
        '''
        assert batch_size > 0, "batch_size must be larger than 0"
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
        if not in_dygraph_mode():
            has_lod = False
            for f in self._feed_list:
                if f.lod_level != 0:
                    has_lod = True
                    break

            if has_lod:
                self.decorate_sample_list_generator(
                    paddle.batch(
                        sample_generator,
                        batch_size=batch_size,
                        drop_last=drop_last),
                    places=places)
            else:
                reader = BatchedTensorProvider(
                    feed_list=self._feed_list,
                    place=core.CPUPlace(),
                    batch_size=batch_size,
                    generator=sample_generator,
                    drop_last=drop_last)
                self.decorate_batch_generator(reader, places=places)
        else:
S
sneaxiy 已提交
539
            self.decorate_sample_list_generator(
S
sneaxiy 已提交
540 541 542 543 544 545
                paddle.batch(
                    sample_generator,
                    batch_size=batch_size,
                    drop_last=drop_last),
                places=places)

S
sneaxiy 已提交
546
    def decorate_sample_list_generator(self, reader, places=None):
S
add doc  
sneaxiy 已提交
547 548 549 550
        '''
        Set the data source of the PyReader object. 

        The provided :code:`reader` should be a Python generator,
S
sneaxiy 已提交
551
        which yields list(numpy.ndarray) typed batched data. 
S
add doc  
sneaxiy 已提交
552 553 554 555
        
        :code:`places` must be set when the PyReader object is iterable.

        Args:
S
sneaxiy 已提交
556 557 558 559
            reader (generator): Python generator that yields 
                list(numpy.ndarray)-typed batched data. 
            places (None|list(CUDAPlace)|list(CPUPlace)): place list. Must
                be provided when PyReader is iterable.
560 561 562 563
        
        Example:
            .. code-block:: python

H
Huihuang Zheng 已提交
564 565 566 567
                import paddle
                import paddle.fluid as fluid
                import numpy as np

568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
                EPOCH_NUM = 3
                ITER_NUM = 15
                BATCH_SIZE = 3

                def random_image_and_label_generator(height, width):
                    def generator():
                        for i in range(ITER_NUM):
                            fake_image = np.random.uniform(low=0,
                                                           high=255,
                                                           size=[height, width])
                            fake_label = np.ones([1])
                            yield fake_image, fake_label
                    return generator

                image = fluid.layers.data(name='image', shape=[784, 784], dtype='float32')
                label = fluid.layers.data(name='label', shape=[1], dtype='int32')
                reader = fluid.io.PyReader(feed_list=[image, label], capacity=4, iterable=True)

                user_defined_generator = random_image_and_label_generator(784, 784)
                reader.decorate_sample_list_generator(
                    paddle.batch(user_defined_generator, batch_size=BATCH_SIZE),
                    fluid.core.CUDAPlace(0))
                # definition of network is omitted
                executor = fluid.Executor(fluid.core.CUDAPlace(0))
                executor.run(fluid.default_main_program())

                for _ in range(EPOCH_NUM):
                    for data in reader():
                        executor.run(feed=data)
                 
S
add doc  
sneaxiy 已提交
598
        '''
S
sneaxiy 已提交
599 600
        assert self._tensor_reader is None, \
            "Cannot reset the data source of PyReader"
601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616
        if not in_dygraph_mode():
            with program_guard(Program(), Program()):
                feeder = DataFeeder(
                    feed_list=self._feed_list, place=core.CPUPlace())
                paddle_reader = feeder.decorate_reader(
                    reader, multi_devices=False)

            def __tensor_reader_impl__():
                for slots in paddle_reader():
                    yield [slots[var.name] for var in self._feed_list]
        else:
            provider = ListTensorProvider(reader, places)

            def __tensor_reader_impl__():
                for slots in provider():
                    yield slots[0]
S
sneaxiy 已提交
617

S
sneaxiy 已提交
618
        self.decorate_batch_generator(__tensor_reader_impl__, places)
S
sneaxiy 已提交
619

S
sneaxiy 已提交
620
    def decorate_batch_generator(self, reader, places=None):
S
add doc  
sneaxiy 已提交
621 622 623 624
        '''
        Set the data source of the PyReader object.

        The provided :code:`reader` should be a Python generator,
S
sneaxiy 已提交
625
        which yields numpy.ndarray-typed or LoDTensor-typed batched data.
S
add doc  
sneaxiy 已提交
626 627 628 629 630 631

        :code:`places` must be set when the PyReader object is iterable.

        Args:
            reader (generator): Python generator that yields LoDTensor-typed
                batched data.
S
sneaxiy 已提交
632
            places (None|list(CUDAPlace)|list(CPUPlace)): place list. Must
S
sneaxiy 已提交
633
                be provided when PyReader is iterable.
634 635 636 637

        Example:
            .. code-block:: python

H
Huihuang Zheng 已提交
638 639 640
                import paddle.fluid as fluid
                import numpy as np

641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668
                EPOCH_NUM = 3
                ITER_NUM = 15
                BATCH_SIZE = 3

                def random_image_and_label_generator(height, width):
                    def generator():
                        for i in range(ITER_NUM):
                            batch_image = np.random.uniform(low=0,
                                                            high=255,
                                                            size=[BATCH_SIZE, height, width])
                            batch_label = np.ones([BATCH_SIZE, 1])
                            yield batch_image, batch_label
                    return generator

                image = fluid.layers.data(name='image', shape=[784, 784], dtype='float32')
                label = fluid.layers.data(name='label', shape=[1], dtype='int32')
                reader = fluid.io.PyReader(feed_list=[image, label], capacity=4, iterable=True)

                user_defined_generator = random_image_and_label_generator(784, 784)
                reader.decorate_batch_generator(user_defined_generator, fluid.CUDAPlace(0))
                # definition of network is omitted
                executor = fluid.Executor(fluid.CUDAPlace(0))
                executor.run(fluid.default_main_program())

                for _ in range(EPOCH_NUM):
                    for data in reader():
                        executor.run(feed=data)

S
add doc  
sneaxiy 已提交
669
        '''
S
sneaxiy 已提交
670 671 672
        assert self._tensor_reader is None, \
            "Cannot reset the data source of PyReader"
        self._tensor_reader = reader
S
sneaxiy 已提交
673 674 675
        if self._iterable:
            assert places is not None, "Places cannot be None when py_reader is iterable"
            self._init_iterable(places)